Skip to main content

vyre_driver/
numeric.rs

1//! Backend-neutral numeric boundary conversions.
2//!
3//! Concrete GPU backends cross the same host/API boundaries: host sizes become
4//! API `u64`s, high-resolution timers become telemetry `u64`s, and device
5//! timestamp deltas arrive as rounded floating-point nanoseconds. This module is
6//! the single policy for those lossy or fallible conversions; backend crates add
7//! only the backend label that makes the diagnostic actionable.
8
9use std::time::Instant;
10
11use crate::BackendError;
12
13/// Integer basis-point denominator: 10_000 bps = 100%.
14pub const BASIS_POINTS_DENOMINATOR: u32 = 10_000;
15
16/// Backend-bound numeric conversion policy.
17///
18/// Backends should keep their label in one constant of this type instead of
19/// cloning one local wrapper per numeric helper. The free functions below remain
20/// available for backend-neutral callers and tests.
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub struct BackendNumericPolicy {
23    backend: &'static str,
24}
25
26impl BackendNumericPolicy {
27    /// Create a numeric policy that annotates diagnostics with `backend`.
28    #[must_use]
29    pub const fn new(backend: &'static str) -> Self {
30        Self { backend }
31    }
32
33    /// Return the backend label used in numeric diagnostics.
34    #[must_use]
35    pub const fn backend(self) -> &'static str {
36        self.backend
37    }
38
39    /// Convert a host `usize` to a backend/API `u64`.
40    ///
41    /// # Errors
42    /// Returns [`BackendError::InvalidProgram`] when the value cannot fit in
43    /// the backend/API boundary type.
44    pub fn usize_to_u64(self, value: usize, label: &str) -> Result<u64, BackendError> {
45        usize_to_u64(value, label, self.backend)
46    }
47
48    /// Convert a wide counter to telemetry `u64`.
49    ///
50    /// # Errors
51    /// Returns [`BackendError::InvalidProgram`] when the counter does not fit in
52    /// telemetry storage.
53    pub fn u128_to_u64(self, value: u128, label: &str) -> Result<u64, BackendError> {
54        u128_to_u64(value, label, self.backend)
55    }
56
57    /// Convert elapsed wall-clock time to telemetry nanoseconds.
58    ///
59    /// # Errors
60    /// Returns [`BackendError::InvalidProgram`] when the elapsed nanoseconds
61    /// cannot fit in telemetry storage.
62    pub fn elapsed_nanos_u64(self, started: Instant, label: &str) -> Result<u64, BackendError> {
63        elapsed_nanos_u64(started, label, self.backend)
64    }
65
66    /// Round a finite floating-point nanosecond value into telemetry storage.
67    ///
68    /// # Errors
69    /// Returns [`BackendError::InvalidProgram`] when the rounded value is
70    /// negative, non-finite, or too large for telemetry storage.
71    pub fn rounded_f64_to_u64(self, value: f64, label: &str) -> Result<u64, BackendError> {
72        rounded_f64_to_u64(value, label, self.backend)
73    }
74
75    /// Compute `part / whole` as floor basis points in a `u32` telemetry domain.
76    #[must_use]
77    pub fn ratio_basis_points_u64(
78        self,
79        part: u64,
80        whole: u64,
81        denominator_zero_value: u32,
82        label: &str,
83    ) -> u32 {
84        ratio_basis_points_u64(part, whole, denominator_zero_value, label, self.backend)
85    }
86
87    /// Compute `part / whole` as floor basis points in a `u64` telemetry domain.
88    #[must_use]
89    pub fn ratio_basis_points_u64_wide(
90        self,
91        part: u64,
92        whole: u64,
93        denominator_zero_value: u64,
94        label: &str,
95    ) -> u64 {
96        ratio_basis_points_u64_wide(part, whole, denominator_zero_value, label, self.backend)
97    }
98
99    /// Compute `part / whole` as floor parts-per-million.
100    #[must_use]
101    pub fn ratio_parts_per_million_u64(
102        self,
103        part: u64,
104        whole: u64,
105        denominator_zero_value: u32,
106        label: &str,
107    ) -> u32 {
108        ratio_parts_per_million_u64(part, whole, denominator_zero_value, label, self.backend)
109    }
110
111    /// Compose two basis-point multipliers into a `u32` result.
112    #[must_use]
113    pub fn compose_basis_points_u32(self, left: u32, right: u32, label: &str) -> u32 {
114        compose_basis_points_u32(left, right, label, self.backend)
115    }
116
117    /// Apply rounded basis-point scaling with optional high clamp.
118    #[must_use]
119    pub fn scale_u64_by_basis_points_round_clamped(
120        self,
121        base: u64,
122        scale_bps: u32,
123        zero_scale_value: u64,
124        max_scale_bps: u32,
125        label: &str,
126    ) -> u64 {
127        scale_u64_by_basis_points_round_clamped(
128            base,
129            scale_bps,
130            zero_scale_value,
131            max_scale_bps,
132            label,
133            self.backend,
134        )
135    }
136
137    /// Apply floor basis-point scaling with a lower bound.
138    #[must_use]
139    pub fn scale_u64_by_basis_points_floor_min(
140        self,
141        base: u64,
142        scale_bps: u32,
143        min_value: u64,
144        label: &str,
145    ) -> u64 {
146        scale_u64_by_basis_points_floor_min(base, scale_bps, min_value, label, self.backend)
147    }
148
149    /// Convert finite non-negative floating-point telemetry to `u32` by truncation.
150    #[must_use]
151    pub fn finite_f64_to_u32_trunc(self, value: f64, label: &str) -> u32 {
152        finite_f64_to_u32_trunc(value, label, self.backend)
153    }
154
155    /// Convert finite non-negative floating-point telemetry to rounded `u32`.
156    #[must_use]
157    pub fn finite_f64_to_u32_round(self, value: f64, label: &str) -> u32 {
158        finite_f64_to_u32_round(value, label, self.backend)
159    }
160
161    /// Convert a finite floating-point ratio into floor basis points.
162    #[must_use]
163    pub fn finite_f64_ratio_basis_points_trunc(
164        self,
165        numerator: f64,
166        denominator: f64,
167        invalid_numerator_value: u32,
168        invalid_denominator_value: u32,
169        label: &str,
170    ) -> u32 {
171        finite_f64_ratio_basis_points_trunc(
172            numerator,
173            denominator,
174            invalid_numerator_value,
175            invalid_denominator_value,
176            label,
177            self.backend,
178        )
179    }
180
181    /// Convert a finite floating-point ratio into rounded basis points.
182    #[must_use]
183    pub fn finite_f64_ratio_basis_points_round(
184        self,
185        numerator: f64,
186        denominator: f64,
187        invalid_numerator_value: u32,
188        invalid_denominator_value: u32,
189        label: &str,
190    ) -> u32 {
191        finite_f64_ratio_basis_points_round(
192            numerator,
193            denominator,
194            invalid_numerator_value,
195            invalid_denominator_value,
196            label,
197            self.backend,
198        )
199    }
200
201    /// Convert a finite scalar where `1.0 == 10_000 bps` into floor basis points.
202    #[must_use]
203    pub fn finite_f64_unit_basis_points_trunc(
204        self,
205        value: f64,
206        invalid_value: u32,
207        label: &str,
208    ) -> u32 {
209        finite_f64_unit_basis_points_trunc(value, invalid_value, label, self.backend)
210    }
211
212    /// Compute `ceil(value / divisor)` in `u64`, returning `None` for zero
213    /// divisors or arithmetic overflow.
214    #[must_use]
215    pub fn checked_ceil_div_u64(self, value: u64, divisor: u64) -> Option<u64> {
216        checked_ceil_div_u64(value, divisor)
217    }
218
219    /// Multiply three `u32` launch dimensions into a `u64` without wraparound.
220    #[must_use]
221    pub fn checked_dim_product_u64(self, dims: [u32; 3]) -> Option<u64> {
222        checked_dim_product_u64(dims)
223    }
224
225    /// Multiply three `u32` launch dimensions into a `u32` without wraparound.
226    #[must_use]
227    pub fn checked_dim_product_u32(self, dims: [u32; 3]) -> Option<u32> {
228        checked_dim_product_u32(dims)
229    }
230
231    /// Align `value` upward to `alignment`, after applying `min_value`.
232    ///
233    /// # Errors
234    /// Returns [`BackendError::InvalidProgram`] when `alignment` is zero or the
235    /// padded value would overflow `u64`.
236    pub fn align_up_u64(
237        self,
238        value: u64,
239        alignment: u64,
240        min_value: u64,
241        label: &str,
242    ) -> Result<u64, BackendError> {
243        align_up_u64(value, alignment, min_value, label, self.backend)
244    }
245
246    /// Align `value` upward to `alignment`, after applying `min_value`.
247    ///
248    /// # Errors
249    /// Returns [`BackendError::InvalidProgram`] when `alignment` is zero or the
250    /// padded value would overflow `usize`.
251    pub fn align_up_usize(
252        self,
253        value: usize,
254        alignment: usize,
255        min_value: usize,
256        label: &str,
257    ) -> Result<usize, BackendError> {
258        align_up_usize(value, alignment, min_value, label, self.backend)
259    }
260}
261
262/// Convert a host `usize` to a backend/API `u64`.
263///
264/// # Errors
265/// Returns [`BackendError::InvalidProgram`] when the value cannot fit in the
266/// backend/API boundary type.
267pub fn usize_to_u64(value: usize, label: &str, backend: &str) -> Result<u64, BackendError> {
268    u64::try_from(value).map_err(|source| BackendError::InvalidProgram {
269        fix: format!(
270            "Fix: {backend} {label} cannot fit u64: {source}; split the workload before crossing the host/device boundary."
271        ),
272    })
273}
274
275/// Convert a wide counter to telemetry `u64`.
276///
277/// # Errors
278/// Returns [`BackendError::InvalidProgram`] when the counter does not fit in
279/// telemetry storage.
280pub fn u128_to_u64(value: u128, label: &str, backend: &str) -> Result<u64, BackendError> {
281    u64::try_from(value).map_err(|source| BackendError::InvalidProgram {
282        fix: format!(
283            "Fix: {backend} {label} cannot fit u64: {source}; split the dispatch before telemetry overflows."
284        ),
285    })
286}
287
288/// Convert elapsed wall-clock time to telemetry nanoseconds.
289///
290/// # Errors
291/// Returns [`BackendError::InvalidProgram`] when the elapsed nanoseconds cannot
292/// fit in telemetry storage.
293pub fn elapsed_nanos_u64(
294    started: Instant,
295    label: &str,
296    backend: &str,
297) -> Result<u64, BackendError> {
298    u128_to_u64(started.elapsed().as_nanos(), label, backend)
299}
300
301/// Round a finite floating-point nanosecond value into telemetry storage.
302///
303/// # Errors
304/// Returns [`BackendError::InvalidProgram`] when the rounded value is negative,
305/// non-finite, or too large for telemetry storage.
306pub fn rounded_f64_to_u64(value: f64, label: &str, backend: &str) -> Result<u64, BackendError> {
307    let rounded = value.round();
308    if !rounded.is_finite() || rounded < 0.0 || rounded > u64::MAX as f64 {
309        return Err(BackendError::InvalidProgram {
310            fix: format!(
311                "Fix: {backend} {label} value {value} cannot fit u64 after rounding; inspect device timing and split the dispatch before telemetry overflows."
312            ),
313        });
314    }
315    u64::try_from(rounded as u128).map_err(|source| BackendError::InvalidProgram {
316        fix: format!(
317            "Fix: {backend} {label} rounded value cannot fit u64: {source}; inspect device timing and split the dispatch before telemetry overflows."
318        ),
319    })
320}
321
322/// Compute `part / whole` as floor basis points with explicit zero-denominator
323/// policy and saturating telemetry overflow.
324///
325/// CUDA release-path planners use the same ratio encoding for memory pressure,
326/// readback savings, and device-side compaction. Keeping the arithmetic here
327/// prevents each backend module from carrying its own unchecked `as u32` cast.
328#[must_use]
329pub fn ratio_basis_points_u64(
330    part: u64,
331    whole: u64,
332    denominator_zero_value: u32,
333    label: &str,
334    backend: &str,
335) -> u32 {
336    let value = ratio_basis_points_u64_wide(
337        part,
338        whole,
339        u64::from(denominator_zero_value),
340        label,
341        backend,
342    );
343    if value > u64::from(u32::MAX) {
344        tracing::error!(
345            "{backend} {label} basis-points value exceeded u32. Fix: shard or normalize the telemetry domain before release-path planning."
346        );
347        return u32::MAX;
348    }
349    value as u32
350}
351
352/// Compute `part / whole` as floor basis points in a `u64` telemetry domain
353/// with explicit zero-denominator policy and loud overflow pinning.
354#[must_use]
355pub fn ratio_basis_points_u64_wide(
356    part: u64,
357    whole: u64,
358    denominator_zero_value: u64,
359    label: &str,
360    backend: &str,
361) -> u64 {
362    if whole == 0 {
363        return denominator_zero_value;
364    }
365    let value = (u128::from(part) * u128::from(BASIS_POINTS_DENOMINATOR)) / u128::from(whole);
366    if value > u128::from(u64::MAX) {
367        tracing::error!(
368            "{backend} {label} basis-points value exceeded u64. Fix: shard or normalize the telemetry domain before release-path planning."
369        );
370        return u64::MAX;
371    }
372    value as u64
373}
374
375/// Compute `part / whole` as floor parts-per-million with explicit
376/// zero-denominator policy and loud `u32` overflow pinning.
377#[must_use]
378pub fn ratio_parts_per_million_u64(
379    part: u64,
380    whole: u64,
381    denominator_zero_value: u32,
382    label: &str,
383    backend: &str,
384) -> u32 {
385    if whole == 0 {
386        return denominator_zero_value;
387    }
388    let value = (u128::from(part) * 1_000_000) / u128::from(whole);
389    if value > u128::from(u32::MAX) {
390        tracing::error!(
391            "{backend} {label} parts-per-million value exceeded u32. Fix: shard or normalize telemetry before release-path planning."
392        );
393        return u32::MAX;
394    }
395    value as u32
396}
397
398/// Compose two basis-point multipliers as `(left * right) / 10_000`, with
399/// widened arithmetic and loud `u32` overflow pinning.
400#[must_use]
401pub fn compose_basis_points_u32(left: u32, right: u32, label: &str, backend: &str) -> u32 {
402    let value = (u128::from(left) * u128::from(right)) / u128::from(BASIS_POINTS_DENOMINATOR);
403    if value > u128::from(u32::MAX) {
404        tracing::error!(
405            "{backend} {label} composed basis-points value exceeded u32. Fix: normalize chained multipliers before release-path planning."
406        );
407        return u32::MAX;
408    }
409    value as u32
410}
411
412/// Compose two basis-point multipliers as `(left * right) / 10_000`, returning
413/// `None` rather than saturating when the composed value cannot fit `u64`.
414#[must_use]
415pub fn checked_compose_basis_points_u64(left: u64, right: u64) -> Option<u64> {
416    let value = (u128::from(left) * u128::from(right)) / u128::from(BASIS_POINTS_DENOMINATOR);
417    u64::try_from(value).ok()
418}
419
420/// Apply a basis-point multiplier to a `u64` with nearest-integer rounding,
421/// optional high clamp, and explicit zero-scale policy.
422#[must_use]
423pub fn scale_u64_by_basis_points_round_clamped(
424    base: u64,
425    scale_bps: u32,
426    zero_scale_value: u64,
427    max_scale_bps: u32,
428    label: &str,
429    backend: &str,
430) -> u64 {
431    if scale_bps == 0 {
432        return zero_scale_value;
433    }
434    let clamped = if max_scale_bps == 0 {
435        scale_bps
436    } else {
437        scale_bps.min(max_scale_bps)
438    };
439    let value = (u128::from(base) * u128::from(clamped) + u128::from(BASIS_POINTS_DENOMINATOR / 2))
440        / u128::from(BASIS_POINTS_DENOMINATOR);
441    if value > u128::from(u64::MAX) {
442        tracing::error!(
443            "{backend} {label} rounded basis-point scaling exceeded u64. Fix: shard or normalize the cost domain before extraction."
444        );
445        return u64::MAX;
446    }
447    value as u64
448}
449
450/// Apply a basis-point multiplier to a `u64` with floor rounding and an output
451/// lower bound.
452#[must_use]
453pub fn scale_u64_by_basis_points_floor_min(
454    base: u64,
455    scale_bps: u32,
456    min_value: u64,
457    label: &str,
458    backend: &str,
459) -> u64 {
460    let value = (u128::from(base) * u128::from(scale_bps)) / u128::from(BASIS_POINTS_DENOMINATOR);
461    if value > u128::from(u64::MAX) {
462        tracing::error!(
463            "{backend} {label} floor basis-point scaling exceeded u64. Fix: shard or normalize the cost domain before extraction."
464        );
465        return u64::MAX;
466    }
467    (value as u64).max(min_value)
468}
469
470/// Weight a `u64` cost by basis points into a widened exact `u128` domain.
471#[must_use]
472pub fn weighted_u64_by_basis_points_u128(value: u64, basis_points: u32) -> u128 {
473    (u128::from(value) * u128::from(basis_points)) / u128::from(BASIS_POINTS_DENOMINATOR)
474}
475
476/// Convert a finite non-negative floating-point telemetry value to `u32` by
477/// truncating toward zero, with loud saturation on invalid or oversized input.
478#[must_use]
479pub fn finite_f64_to_u32_trunc(value: f64, label: &str, backend: &str) -> u32 {
480    if !value.is_finite() {
481        tracing::error!(
482            "{backend} {label} value {value} is not finite. Fix: normalize telemetry before release-path planning."
483        );
484        return u32::MAX;
485    }
486    if value <= 0.0 {
487        return 0;
488    }
489    if value > f64::from(u32::MAX) {
490        tracing::error!(
491            "{backend} {label} value {value} cannot fit u32. Fix: shard or normalize telemetry before release-path planning."
492        );
493        return u32::MAX;
494    }
495    value as u32
496}
497
498/// Convert a finite non-negative floating-point telemetry value to `u32` after
499/// rounding to the nearest integer, with loud saturation on invalid input.
500#[must_use]
501pub fn finite_f64_to_u32_round(value: f64, label: &str, backend: &str) -> u32 {
502    let rounded = value.round();
503    if !rounded.is_finite() {
504        tracing::error!(
505            "{backend} {label} rounded value {rounded} is not finite. Fix: normalize telemetry before release-path planning."
506        );
507        return u32::MAX;
508    }
509    if rounded <= 0.0 {
510        return 0;
511    }
512    if rounded > f64::from(u32::MAX) {
513        tracing::error!(
514            "{backend} {label} rounded value {rounded} cannot fit u32. Fix: shard or normalize telemetry before release-path planning."
515        );
516        return u32::MAX;
517    }
518    rounded as u32
519}
520
521/// Convert a finite floating-point ratio into floor basis points, with separate
522/// policies for invalid numerators and denominators.
523#[must_use]
524pub fn finite_f64_ratio_basis_points_trunc(
525    numerator: f64,
526    denominator: f64,
527    invalid_numerator_value: u32,
528    invalid_denominator_value: u32,
529    label: &str,
530    backend: &str,
531) -> u32 {
532    finite_f64_ratio_basis_points(
533        numerator,
534        denominator,
535        invalid_numerator_value,
536        invalid_denominator_value,
537        label,
538        backend,
539        finite_f64_to_u32_trunc,
540    )
541}
542
543/// Convert a finite floating-point ratio into rounded basis points, with
544/// separate policies for invalid numerators and denominators.
545#[must_use]
546pub fn finite_f64_ratio_basis_points_round(
547    numerator: f64,
548    denominator: f64,
549    invalid_numerator_value: u32,
550    invalid_denominator_value: u32,
551    label: &str,
552    backend: &str,
553) -> u32 {
554    finite_f64_ratio_basis_points(
555        numerator,
556        denominator,
557        invalid_numerator_value,
558        invalid_denominator_value,
559        label,
560        backend,
561        finite_f64_to_u32_round,
562    )
563}
564
565/// Convert a finite scalar where `1.0 == 10_000 bps` into floor basis points.
566#[must_use]
567pub fn finite_f64_unit_basis_points_trunc(
568    value: f64,
569    invalid_value: u32,
570    label: &str,
571    backend: &str,
572) -> u32 {
573    if !value.is_finite() {
574        tracing::error!(
575            "{backend} {label} value {value} is not finite. Fix: normalize telemetry before release-path planning."
576        );
577        return invalid_value;
578    }
579    finite_f64_to_u32_trunc(
580        value.max(0.0) * f64::from(BASIS_POINTS_DENOMINATOR),
581        label,
582        backend,
583    )
584}
585
586fn finite_f64_ratio_basis_points(
587    numerator: f64,
588    denominator: f64,
589    invalid_numerator_value: u32,
590    invalid_denominator_value: u32,
591    label: &str,
592    backend: &str,
593    convert: fn(f64, &str, &str) -> u32,
594) -> u32 {
595    if !numerator.is_finite() {
596        tracing::error!(
597            "{backend} {label} numerator {numerator} is not finite. Fix: record finite dispatch timing before release-path planning."
598        );
599        return invalid_numerator_value;
600    }
601    if !denominator.is_finite() || denominator <= 0.0 {
602        tracing::error!(
603            "{backend} {label} denominator {denominator} is not finite and positive. Fix: record finite dispatch timing before release-path planning."
604        );
605        return invalid_denominator_value;
606    }
607    if numerator <= 0.0 {
608        return 0;
609    }
610    convert(
611        (numerator / denominator) * f64::from(BASIS_POINTS_DENOMINATOR),
612        label,
613        backend,
614    )
615}
616
617/// Compute `ceil(value / divisor)` in `u64`, returning `None` for zero divisors
618/// or arithmetic overflow.
619#[must_use]
620pub fn checked_ceil_div_u64(value: u64, divisor: u64) -> Option<u64> {
621    if divisor == 0 {
622        return None;
623    }
624    if value == 0 {
625        return Some(0);
626    }
627    ((value - 1) / divisor).checked_add(1)
628}
629
630/// Multiply three `u32` dimensions into a `u64` without wraparound.
631///
632/// CUDA, WGPU, and runtime launch geometry all cross this same host/device
633/// boundary. Keeping the primitive here prevents each backend from carrying a
634/// slightly different overflow policy for `[x, y, z]` launch dimensions.
635#[must_use]
636pub fn checked_dim_product_u64(dims: [u32; 3]) -> Option<u64> {
637    u64::from(dims[0])
638        .checked_mul(u64::from(dims[1]))
639        .and_then(|xy| xy.checked_mul(u64::from(dims[2])))
640}
641
642/// Multiply three `u32` dimensions into a `u32` without wraparound.
643#[must_use]
644pub fn checked_dim_product_u32(dims: [u32; 3]) -> Option<u32> {
645    u32::try_from(checked_dim_product_u64(dims)?).ok()
646}
647
648macro_rules! define_align_up {
649    ($name:ident, $ty:ty) => {
650        #[doc = concat!(
651            "Align a `",
652            stringify!($ty),
653            "` value upward after applying a minimum."
654        )]
655        ///
656        /// # Errors
657        ///
658        /// Returns [`BackendError::InvalidProgram`] when `alignment` is zero or
659        /// the padded value would overflow.
660        pub fn $name(
661            value: $ty,
662            alignment: $ty,
663            min_value: $ty,
664            label: &str,
665            backend: &str,
666        ) -> Result<$ty, BackendError> {
667            if alignment == 0 {
668                return Err(BackendError::InvalidProgram {
669                    fix: format!(
670                        "Fix: {backend} {label} alignment must be non-zero before padding."
671                    ),
672                });
673            }
674            let normalized = value.max(min_value);
675            let remainder = normalized % alignment;
676            if remainder == 0 {
677                return Ok(normalized);
678            }
679            normalized.checked_add(alignment - remainder).ok_or_else(|| {
680                BackendError::InvalidProgram {
681                    fix: format!(
682                        "Fix: {backend} {label} overflows {} while padding to {alignment}-byte alignment; split the workload before crossing the host/device boundary.",
683                        stringify!($ty)
684                    ),
685                }
686            })
687        }
688    };
689}
690
691define_align_up!(align_up_u64, u64);
692define_align_up!(align_up_usize, usize);
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697
698    #[test]
699    fn usize_boundary_accepts_fit_values() {
700        assert_eq!(usize_to_u64(17, "bytes", "test").unwrap(), 17);
701    }
702
703    #[test]
704    fn backend_numeric_policy_carries_backend_label_without_local_wrappers() {
705        let policy = BackendNumericPolicy::new("CUDA");
706        assert_eq!(policy.backend(), "CUDA");
707        assert_eq!(policy.usize_to_u64(17, "bytes").unwrap(), 17);
708        assert_eq!(policy.ratio_basis_points_u64(1, 4, 0, "pressure"), 2_500);
709        assert_eq!(
710            policy.finite_f64_ratio_basis_points_round(1.0, 6.0, 99, 77, "ratio"),
711            1_667
712        );
713        assert_eq!(policy.checked_ceil_div_u64(65_537, 65_536), Some(2));
714        assert_eq!(
715            policy.checked_dim_product_u64([65_535, 2, 3]),
716            Some(393_210)
717        );
718        assert_eq!(
719            policy.checked_dim_product_u32([65_535, 2, 3]),
720            Some(393_210)
721        );
722
723        let err = policy
724            .u128_to_u64(u128::from(u64::MAX) + 1, "resident bytes")
725            .unwrap_err();
726        let rendered = err.to_string();
727        assert!(
728            rendered.contains("CUDA resident bytes"),
729            "backend policy diagnostics must carry the backend label and boundary name: {rendered}"
730        );
731    }
732
733    #[test]
734    fn u128_boundary_rejects_overflow_with_backend_label() {
735        let err = u128_to_u64(u128::from(u64::MAX) + 1, "counter", "test").unwrap_err();
736        let rendered = err.to_string();
737        assert!(
738            rendered.contains("test counter"),
739            "numeric boundary diagnostics must identify the backend and label: {rendered}"
740        );
741    }
742
743    #[test]
744    fn rounded_f64_rejects_non_finite_values() {
745        let err = rounded_f64_to_u64(f64::NAN, "timestamp", "test").unwrap_err();
746        let rendered = err.to_string();
747        assert!(
748            rendered.contains("timestamp"),
749            "rounded timestamp diagnostics must include the failing label: {rendered}"
750        );
751    }
752
753    #[test]
754    fn ratio_basis_points_preserves_zero_denominator_policy() {
755        assert_eq!(
756            ratio_basis_points_u64(1, 0, u32::MAX, "pressure", "test"),
757            u32::MAX
758        );
759        assert_eq!(ratio_basis_points_u64(0, 0, 0, "savings", "test"), 0);
760    }
761
762    #[test]
763    fn ratio_basis_points_uses_wide_arithmetic_before_clamping() {
764        assert_eq!(
765            ratio_basis_points_u64(u64::MAX, u64::MAX / 2, 0, "wide", "test"),
766            20_000
767        );
768        assert_eq!(
769            ratio_basis_points_u64(u64::MAX, 1, 0, "overflow", "test"),
770            u32::MAX
771        );
772    }
773
774    #[test]
775    fn wide_ratio_basis_points_retains_u64_telemetry_domain() {
776        assert_eq!(ratio_basis_points_u64_wide(3, 2, 0, "wide", "test"), 15_000);
777        assert_eq!(
778            ratio_basis_points_u64_wide(u64::MAX, u64::MAX / 4, 0, "wide", "test"),
779            40_000
780        );
781        assert_eq!(
782            ratio_basis_points_u64_wide(u64::MAX, 1, 0, "overflow", "test"),
783            u64::MAX
784        );
785    }
786
787    #[test]
788    fn finite_f64_to_u32_helpers_pin_invalid_values() {
789        assert_eq!(finite_f64_to_u32_trunc(12.9, "value", "test"), 12);
790        assert_eq!(finite_f64_to_u32_round(12.5, "value", "test"), 13);
791        assert_eq!(finite_f64_to_u32_trunc(-1.0, "value", "test"), 0);
792        assert_eq!(
793            finite_f64_to_u32_round(f64::INFINITY, "value", "test"),
794            u32::MAX
795        );
796        assert_eq!(
797            finite_f64_to_u32_trunc(f64::from(u32::MAX) * 2.0, "value", "test"),
798            u32::MAX
799        );
800    }
801
802    #[test]
803    fn finite_f64_basis_point_helpers_pin_invalid_policies() {
804        assert_eq!(
805            finite_f64_ratio_basis_points_trunc(1.0, 4.0, 99, 77, "ratio", "test"),
806            2_500
807        );
808        assert_eq!(
809            finite_f64_ratio_basis_points_round(1.0, 6.0, 99, 77, "ratio", "test"),
810            1_667
811        );
812        assert_eq!(
813            finite_f64_ratio_basis_points_trunc(f64::NAN, 1.0, 99, 77, "ratio", "test"),
814            99
815        );
816        assert_eq!(
817            finite_f64_ratio_basis_points_trunc(1.0, 0.0, 99, 77, "ratio", "test"),
818            77
819        );
820        assert_eq!(
821            finite_f64_ratio_basis_points_round(-1.0, 1.0, 99, 77, "ratio", "test"),
822            0
823        );
824        assert_eq!(
825            finite_f64_unit_basis_points_trunc(0.25, 33, "unit", "test"),
826            2_500
827        );
828        assert_eq!(
829            finite_f64_unit_basis_points_trunc(f64::INFINITY, 33, "unit", "test"),
830            33
831        );
832    }
833
834    #[test]
835    fn alignment_helpers_pad_minimums_and_reject_overflow() {
836        assert_eq!(align_up_u64(0, 4, 4, "copy", "test").unwrap(), 4);
837        assert_eq!(align_up_u64(5, 4, 0, "copy", "test").unwrap(), 8);
838        assert_eq!(align_up_usize(0, 4, 4, "copy", "test").unwrap(), 4);
839        assert_eq!(align_up_usize(5, 4, 0, "copy", "test").unwrap(), 8);
840
841        let zero_alignment = align_up_u64(1, 0, 0, "copy", "test").unwrap_err();
842        assert!(
843            zero_alignment
844                .to_string()
845                .contains("alignment must be non-zero"),
846            "zero-alignment diagnostics must be actionable: {zero_alignment}"
847        );
848
849        let overflow_u64 = align_up_u64(u64::MAX, 4, 0, "copy", "test").unwrap_err();
850        assert!(
851            overflow_u64.to_string().contains("overflows u64"),
852            "u64 alignment overflow diagnostics must name the target type: {overflow_u64}"
853        );
854
855        let overflow_usize = align_up_usize(usize::MAX, 4, 0, "copy", "test").unwrap_err();
856        assert!(
857            overflow_usize.to_string().contains("overflows usize"),
858            "usize alignment overflow diagnostics must name the target type: {overflow_usize}"
859        );
860    }
861
862    #[test]
863    fn checked_ceil_div_u64_handles_cuda_queue_boundaries() {
864        assert_eq!(checked_ceil_div_u64(0, 64), Some(0));
865        assert_eq!(checked_ceil_div_u64(1, 64), Some(1));
866        assert_eq!(checked_ceil_div_u64(65_537, 65_536), Some(2));
867        assert_eq!(
868            checked_ceil_div_u64(u64::MAX, 65_536),
869            Some(281_474_976_710_656)
870        );
871        assert_eq!(checked_ceil_div_u64(u64::MAX, 1), Some(u64::MAX));
872        assert_eq!(checked_ceil_div_u64(1, 0), None);
873    }
874
875    #[test]
876    fn checked_dim_product_helpers_cover_cuda_launch_boundaries() {
877        assert_eq!(checked_dim_product_u64([1, 1, 1]), Some(1));
878        assert_eq!(checked_dim_product_u64([0, 999, 999]), Some(0));
879        assert_eq!(checked_dim_product_u64([65_535, 2, 3]), Some(393_210));
880        assert_eq!(checked_dim_product_u32([65_535, 2, 3]), Some(393_210));
881        assert_eq!(
882            checked_dim_product_u64([u32::MAX, u32::MAX, u32::MAX]),
883            None
884        );
885        assert_eq!(checked_dim_product_u32([u32::MAX, 2, 1]), None);
886    }
887
888    #[test]
889    fn generated_dim_product_matrix_matches_wide_integer_reference() {
890        const VALUES: [u32; 9] = [0, 1, 2, 3, 7, 32, 255, 65_535, u32::MAX];
891        for x in VALUES {
892            for y in VALUES {
893                for z in VALUES {
894                    let wide = u128::from(x) * u128::from(y) * u128::from(z);
895                    let expected_u64 = u64::try_from(wide).ok();
896                    let expected_u32 = u32::try_from(wide).ok();
897                    assert_eq!(checked_dim_product_u64([x, y, z]), expected_u64);
898                    assert_eq!(checked_dim_product_u32([x, y, z]), expected_u32);
899                }
900            }
901        }
902    }
903
904    #[test]
905    fn ratio_parts_per_million_uses_wide_arithmetic_and_pins_overflow() {
906        assert_eq!(
907            ratio_parts_per_million_u64(1, 4, 0, "commit-rate", "test"),
908            250_000
909        );
910        assert_eq!(
911            ratio_parts_per_million_u64(1, 0, 7, "commit-rate", "test"),
912            7
913        );
914        assert_eq!(
915            ratio_parts_per_million_u64(u64::MAX, 1, 0, "commit-rate", "test"),
916            u32::MAX
917        );
918    }
919
920    #[test]
921    fn basis_point_composition_and_scaling_helpers_are_widened() {
922        assert_eq!(
923            compose_basis_points_u32(15_000, 2_500, "compose", "test"),
924            3_750
925        );
926        assert_eq!(
927            compose_basis_points_u32(u32::MAX, u32::MAX, "compose", "test"),
928            u32::MAX
929        );
930        assert_eq!(
931            checked_compose_basis_points_u64(50_000, 20_000),
932            Some(100_000)
933        );
934        assert_eq!(checked_compose_basis_points_u64(u64::MAX, u64::MAX), None);
935        assert_eq!(
936            scale_u64_by_basis_points_round_clamped(10, 1_000_000, 10, 40_000, "scale", "test"),
937            40
938        );
939        assert_eq!(
940            scale_u64_by_basis_points_round_clamped(7, 0, 7, 40_000, "scale", "test"),
941            7
942        );
943        assert_eq!(
944            scale_u64_by_basis_points_floor_min(1, 1, 1, "scale", "test"),
945            1
946        );
947        assert_eq!(
948            weighted_u64_by_basis_points_u128(u64::MAX, 10_000),
949            u128::from(u64::MAX)
950        );
951    }
952}