From 608ecc3f737cd91bbcf175af7bcdef152a6f47e0 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Thu, 26 Nov 2026 22:12:44 +0000 Subject: [PATCH 1/2] fix: reject an existing shard weight past the u64 range `--existing` accepted a seconds value at or above 2^64. `ceil_seconds` then saturated that weight at the largest `u64`, and the command exited 0. Refuse the value with the same exclusive bound already used for result and summary durations. --- changelog.d/+existing-weight-bound.bugfix.md | 1 + src/bin/eb-shard-weights.rs | 27 +++++++++++++++----- tests/shard_weights.rs | 27 ++++++++++++++++++++ 3 files changed, 48 insertions(+), 7 deletions(-) create mode 100644 changelog.d/+existing-weight-bound.bugfix.md diff --git a/changelog.d/+existing-weight-bound.bugfix.md b/changelog.d/+existing-weight-bound.bugfix.md new file mode 100644 index 00000000..db8ed79f --- /dev/null +++ b/changelog.d/+existing-weight-bound.bugfix.md @@ -0,0 +1 @@ +Refuse an `--existing` shard weight that cannot fit in a whole-second weight. diff --git a/src/bin/eb-shard-weights.rs b/src/bin/eb-shard-weights.rs index f70df76a..d1d549d4 100644 --- a/src/bin/eb-shard-weights.rs +++ b/src/bin/eb-shard-weights.rs @@ -359,13 +359,26 @@ fn read_existing(path: &Path) -> Result, String> { value.trim() ) })?; - if util::checked_duration_seconds(secs, None).is_err() { - return Err(format!( - "{} line {}: `{}` is not a number of seconds", - path.display(), - i + 1, - value.trim() - )); + let max_weight_seconds = u64::MAX as f64; + match util::checked_duration_seconds(secs, Some(max_weight_seconds)) { + Ok(_) => {} + Err(util::DurationError::Invalid) => { + return Err(format!( + "{} line {}: `{}` is not a number of seconds", + path.display(), + i + 1, + value.trim() + )); + } + Err(util::DurationError::TooLarge) => { + return Err(format!( + "{} line {}: `{}` exceeds {} seconds", + path.display(), + i + 1, + value.trim(), + u64::MAX + )); + } } let module = module.trim(); if let Some(first) = first_lines.insert(module.to_string(), i + 1) { diff --git a/tests/shard_weights.rs b/tests/shard_weights.rs index 6539ec09..32a8726a 100644 --- a/tests/shard_weights.rs +++ b/tests/shard_weights.rs @@ -79,6 +79,33 @@ fn a_duration_beyond_any_integer_weight_is_refused() { } } +#[test] +fn an_existing_weight_beyond_any_integer_second_is_refused() { + for seconds in ["1e300", "18446744073709551616"] { + let dir = tempfile::tempdir().unwrap(); + let result = dir.path().join("result.json"); + let existing = dir.path().join("existing.tsv"); + std::fs::write(&result, r#"{"kind":"result","target":"cpu","lines":[]}"#).unwrap(); + std::fs::write(&existing, format!("Foo/1.0\t{seconds}\n")).unwrap(); + + let output = bin() + .args(["--result"]) + .arg(&result) + .args(["--existing"]) + .arg(&existing) + .output() + .unwrap(); + + assert_eq!(output.status.code(), Some(2), "{seconds} {output:?}"); + assert_eq!(output.stdout, b"", "{seconds}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("exceeds") && stderr.contains(seconds), + "{seconds} {stderr}" + ); + } +} + #[test] fn common_environment_falls_back_and_flags_win() { let dir = tempfile::tempdir().unwrap(); From 0019a4da3ea7e4e5d367a8bdfb8ad4001dc3c137 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Thu, 26 Nov 2026 23:59:01 +0000 Subject: [PATCH 2/2] fix: accept the `u64::MAX` weight boundary Casting `u64::MAX` to `f64` rounds the bound up to 2^64, so the check refused the largest valid weights, such as 18446744073709551615 and 18446744073709551614.5. The check now compares each `--existing` weight with the bound in exact decimal space and refuses a weight only once it reaches 2^64. A real overflow still reports the same error text. --- src/bin/eb-shard-weights.rs | 164 ++++++++++++++++++++++++++++++++++-- tests/shard_weights.rs | 42 +++++++++ 2 files changed, 197 insertions(+), 9 deletions(-) diff --git a/src/bin/eb-shard-weights.rs b/src/bin/eb-shard-weights.rs index d1d549d4..9253d06c 100644 --- a/src/bin/eb-shard-weights.rs +++ b/src/bin/eb-shard-weights.rs @@ -351,23 +351,23 @@ fn read_existing(path: &Path) -> Result, String> { i + 1 ) })?; - let secs: f64 = value.trim().parse().map_err(|_| { + let seconds_text = value.trim(); + let secs: f64 = seconds_text.parse().map_err(|_| { format!( "{} line {}: `{}` is not a number of seconds", path.display(), i + 1, - value.trim() + seconds_text ) })?; - let max_weight_seconds = u64::MAX as f64; - match util::checked_duration_seconds(secs, Some(max_weight_seconds)) { - Ok(_) => {} + let weight = match existing_weight_seconds(seconds_text, secs) { + Ok(weight) => weight, Err(util::DurationError::Invalid) => { return Err(format!( "{} line {}: `{}` is not a number of seconds", path.display(), i + 1, - value.trim() + seconds_text )); } Err(util::DurationError::TooLarge) => { @@ -375,11 +375,11 @@ fn read_existing(path: &Path) -> Result, String> { "{} line {}: `{}` exceeds {} seconds", path.display(), i + 1, - value.trim(), + seconds_text, u64::MAX )); } - } + }; let module = module.trim(); if let Some(first) = first_lines.insert(module.to_string(), i + 1) { return Err(format!( @@ -388,7 +388,7 @@ fn read_existing(path: &Path) -> Result, String> { i + 1 )); } - out.insert(module.to_string(), ceil_seconds(secs)); + out.insert(module.to_string(), weight); } Ok(out) } @@ -570,6 +570,122 @@ fn ceil_seconds(secs: f64) -> u64 { (secs.ceil() as u64).max(1) } +/// 2^64, the first whole-second weight that does not fit in `u64`. +/// +/// `u64::MAX as f64` rounds up to this value, so a float comparison refuses +/// the largest weights that still fit. +const TWO_POW_64_F64: f64 = 18446744073709551616.0; +const TWO_POW_64_DIGITS: &str = "18446744073709551616"; + +struct DecimalMagnitude { + /// Significant digits, with leading zeros removed. Empty means zero. + digits: String, + /// `value = int(digits) * 10^scale` when `digits` is non-empty. + scale: i64, +} + +/// Whole-second weight for one `--existing` seconds cell. +/// +/// A duration `f64` can tell apart from 2^64 uses the same ceiling as a +/// result duration. A duration that rounds onto 2^64 is read from the +/// original decimal text, because the float bound cannot see that it still +/// fits in `u64`. +fn existing_weight_seconds(text: &str, secs: f64) -> Result { + util::checked_duration_seconds(secs, None)?; + if secs < TWO_POW_64_F64 { + return Ok(ceil_seconds(secs)); + } + decimal_weight_below_two_pow_64(text).ok_or(util::DurationError::TooLarge) +} + +fn decimal_weight_below_two_pow_64(text: &str) -> Option { + let DecimalMagnitude { digits, scale } = parse_decimal_magnitude(text)?; + if digits.is_empty() { + return Some(1); + } + if scale >= 0 { + let zeros = usize::try_from(scale).ok()?; + if digits.len().saturating_add(zeros) > TWO_POW_64_DIGITS.len() { + return None; + } + let mut whole = String::with_capacity(digits.len() + zeros); + whole.push_str(&digits); + whole.push_str(&"0".repeat(zeros)); + if whole.len() == TWO_POW_64_DIGITS.len() && whole.as_str() >= TWO_POW_64_DIGITS { + return None; + } + return whole.parse().ok(); + } + let shift = usize::try_from(-scale).ok()?; + if shift >= digits.len() { + return Some(1); + } + let split = digits.len() - shift; + let whole = &digits[..split]; + if whole.len() > TWO_POW_64_DIGITS.len() + || (whole.len() == TWO_POW_64_DIGITS.len() && whole >= TWO_POW_64_DIGITS) + { + return None; + } + let mut weight: u64 = whole.parse().ok()?; + if digits[split..].bytes().any(|byte| byte != b'0') { + weight = weight.saturating_add(1); + } + Some(weight.max(1)) +} + +fn parse_decimal_magnitude(text: &str) -> Option { + let text = text.trim(); + let rest = text.strip_prefix('+').unwrap_or(text); + if rest.is_empty() || rest.starts_with('-') { + return None; + } + let (coeff, exp_text) = split_scientific(rest)?; + let exp: i32 = match exp_text { + Some(exp_text) => exp_text.parse().ok()?, + None => 0, + }; + let (int_digits, frac_digits) = split_fraction(coeff)?; + if int_digits.is_empty() && frac_digits.is_empty() { + return None; + } + if !is_ascii_digits(int_digits) || !is_ascii_digits(frac_digits) { + return None; + } + let mut digits = String::with_capacity(int_digits.len() + frac_digits.len()); + digits.push_str(int_digits); + digits.push_str(frac_digits); + let scale = i64::from(exp) - i64::try_from(frac_digits.len()).ok()?; + Some(DecimalMagnitude { + digits: digits.trim_start_matches('0').to_string(), + scale, + }) +} + +fn split_scientific(text: &str) -> Option<(&str, Option<&str>)> { + let mut parts = text.split(['e', 'E']); + let coeff = parts.next()?; + match parts.next() { + None => Some((coeff, None)), + Some(exp) if parts.next().is_none() => Some((coeff, Some(exp))), + Some(_) => None, + } +} + +fn split_fraction(coeff: &str) -> Option<(&str, &str)> { + match coeff.split_once('.') { + Some((int_digits, frac_digits)) if !frac_digits.contains('.') => { + Some((int_digits, frac_digits)) + } + Some(_) => None, + None => Some((coeff, "")), + } +} + +fn is_ascii_digits(text: &str) -> bool { + text.bytes().all(|byte| byte.is_ascii_digit()) +} + fn merge_weights(weights: &mut BTreeMap, obs: &[Observation], mode: Mode) { match mode { Mode::Max => { @@ -653,6 +769,36 @@ mod tests { assert_eq!(ceil_seconds(12.1), 13); } + #[test] + fn existing_seconds_text_uses_an_exact_u64_limit() { + let cases = [ + ("0", Ok(1)), + ("0.2", Ok(1)), + ("12.0", Ok(12)), + ("12.1", Ok(13)), + ("1e19", Ok(10_000_000_000_000_000_000)), + ("18446744073709549568", Ok(18_446_744_073_709_549_568)), + ("18446744073709550592", Ok(18_446_744_073_709_550_592)), + ("18446744073709551615", Ok(u64::MAX)), + ("18446744073709551614.5", Ok(u64::MAX)), + ("18446744073709551615.0", Ok(u64::MAX)), + ("+18446744073709551615", Ok(u64::MAX)), + ("1.8446744073709551615e19", Ok(u64::MAX)), + ("18446744073709551616", Err(util::DurationError::TooLarge)), + ("18446744073709551616.0", Err(util::DurationError::TooLarge)), + ("1e300", Err(util::DurationError::TooLarge)), + ("2e19", Err(util::DurationError::TooLarge)), + ("-1", Err(util::DurationError::Invalid)), + ("nan", Err(util::DurationError::Invalid)), + ("inf", Err(util::DurationError::Invalid)), + ("1e-400", Ok(1)), + ]; + for (text, want) in cases { + let secs = text.parse::().unwrap(); + assert_eq!(existing_weight_seconds(text, secs), want, "{text}"); + } + } + #[test] fn modes_combine_observations_with_existing_seed() { let observations = vec![ diff --git a/tests/shard_weights.rs b/tests/shard_weights.rs index 32a8726a..80244ba7 100644 --- a/tests/shard_weights.rs +++ b/tests/shard_weights.rs @@ -106,6 +106,48 @@ fn an_existing_weight_beyond_any_integer_second_is_refused() { } } +#[test] +fn an_existing_weight_on_the_u64_boundary_matches_the_exact_limit() { + let limit = u64::MAX.to_string(); + for (seconds, accepted) in [ + ("18446744073709551615", true), + ("18446744073709551614.5", true), + ("18446744073709551616", false), + ] { + let dir = tempfile::tempdir().unwrap(); + let result = dir.path().join("result.json"); + let existing = dir.path().join("existing.tsv"); + std::fs::write(&result, r#"{"kind":"result","target":"cpu","lines":[]}"#).unwrap(); + std::fs::write(&existing, format!("Foo/1.0\t{seconds}\n")).unwrap(); + + let output = bin() + .args(["--result"]) + .arg(&result) + .args(["--existing"]) + .arg(&existing) + .output() + .unwrap(); + + let stderr = String::from_utf8_lossy(&output.stderr); + if accepted { + assert_eq!(output.status.code(), Some(0), "{seconds} {stderr}"); + assert!(stderr.is_empty(), "{seconds} {stderr}"); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + format!("Foo/1.0\t{limit}\n"), + "{seconds}" + ); + } else { + assert_eq!(output.status.code(), Some(2), "{seconds} {output:?}"); + assert_eq!(output.stdout, b"", "{seconds}"); + assert!( + stderr.contains("exceeds") && stderr.contains(seconds) && stderr.contains(&limit), + "{seconds} {stderr}" + ); + } + } +} + #[test] fn common_environment_falls_back_and_flags_win() { let dir = tempfile::tempdir().unwrap();