diff --git a/crates/engine/src/cmd/table_stats.rs b/crates/engine/src/cmd/table_stats.rs index 00302a5865..c1eccebbd8 100644 --- a/crates/engine/src/cmd/table_stats.rs +++ b/crates/engine/src/cmd/table_stats.rs @@ -19,6 +19,7 @@ use std::borrow::Cow; use std::collections::HashSet; +use rustgis_data::loss::{LossCode, Note}; use rustgis_data::{Dataset, Value as Cell}; use serde_json::{Value, json}; @@ -36,7 +37,7 @@ pub const MAX_DISTINCT_BYTES: usize = 8 << 20; /// significands at one binary exponent, in units of the smallest subnormal. 2098 bits hold /// any finite f64; usize::BITS more hold a whole column's sum. Each i128 bin holds at most /// usize::MAX 53-bit significands without overflowing, on either supported word size. -#[derive(Default)] +#[derive(Clone, Default)] struct WideSum(Vec); impl WideSum { @@ -86,6 +87,13 @@ impl WideSum { let total = significand as f64 * scale; if negative { -total } else { total } } + + /// How far `t` is from the sum: what is left once `t` is taken away, rounded once. + fn off_by(&self, t: f64) -> f64 { + let mut rest = self.clone(); + rest.add(-t); + rest.total() + } } /// Whole numbers past this (2^53) are not all held by a decimal. @@ -136,6 +144,8 @@ struct Numbers { /// How many of `count` are whole numbers, and how many of those are past 2^53. ints: usize, big: usize, + /// Of those, the ones a decimal can't hold, so rounded however the others add up. + inexact: usize, sum: f64, wide_sum: WideSum, all: Welford, @@ -165,11 +175,21 @@ impl Numbers { } } + /// Whether the sum the answer gives is off by half a unit or more: rounded at the scale of the + /// whole numbers past 2^53, as decimals alone never round a sum this far (0.1 + 0.2 isn't). + /// The sum given is the running one, or the exact one where that overflowed. + fn sum_rounded(&self) -> bool { + let given = if self.sum.is_finite() { self.sum } else { self.wide_sum.total() }; + given.is_finite() && self.wide_sum.off_by(given).abs() >= 0.5 + } + fn add_whole(&mut self, i: i64) { self.add_float(i as f64); self.ints += 1; if i.unsigned_abs() > EXACT_IN_F64 { self.big += 1; + // One a decimal still holds exactly (2^54) is rounded only as the sum adds it up. + self.inexact += usize::from((i as f64) as i128 != i128::from(i)); } self.isum += i128::from(i); self.imin = Some(self.imin.map_or(i, |m| m.min(i))); @@ -267,7 +287,8 @@ fn resolve(s: &Session, p: &Value) -> Result { /// An answer, and what it says to the user. struct Done { answer: Value, - notices: Vec, + /// What the count left out or rounded, each with its code: every one is a real loss. + notices: Vec, } /// Counts column `t.column` of `ds` over its rows, looking at Cancel as it goes (see @@ -336,25 +357,45 @@ fn gather(ds: &Dataset, t: &Target) -> Result { map.insert("max".into(), pick(max)); map.insert("stdDev".into(), pick(json!(std_dev))); if n.skipped > 0 { - notices.push(format!( - "{}: {} value(s) in '{}' that aren't finite numbers (NaN, infinity or other text) left out of the statistics", - t.layer, n.skipped, f.name + notices.push(Note::loss( + LossCode::DroppedValue, + format!( + "{}: {} value(s) in '{}' that aren't finite numbers (NaN, infinity or other text) left out of the statistics", + t.layer, n.skipped, f.name + ), )); } // Whole numbers added up exactly unless the column also holds decimals, which add them as // decimals: the whole numbers past 2^53 are then rounded. - if !whole && n.big > 0 { - notices.push(format!( - "{}: {} whole number(s) in '{}' past 2^53 are rounded in the statistics, because the column also holds decimals", - t.layer, n.big, f.name + if !whole && n.inexact > 0 { + notices.push(Note::loss( + LossCode::ChangedRounded, + format!( + "{}: {} whole number(s) in '{}' past 2^53 are rounded in the statistics, because the column also holds decimals", + t.layer, n.inexact, f.name + ), + )); + } else if !whole && n.sum_rounded() { + // A sum past 2^53 with a fraction (5 + 0.5 + 2^54, or decimals alone): a decimal holds + // no fraction there, so it is rounded by half a unit or more. Checked against the exact + // sum, so one that comes out exact, or rounds only as decimals do, says nothing. + notices.push(Note::loss( + LossCode::ChangedRounded, + format!( + "{}: the sum and mean of '{}' are rounded by half a unit or more, as a decimal number holds no fraction past 2^53", + t.layer, f.name + ), )); } if !overflowed.is_empty() { - notices.push(format!( - "{}: the {} of '{}' is too large to hold as a decimal number (past about 1.8e308) and is left out", - t.layer, - overflowed.join(" and the "), - f.name + notices.push(Note::loss( + LossCode::DroppedCalculationResult, + format!( + "{}: the {} of '{}' is too large to hold as a decimal number (past about 1.8e308) and is left out", + t.layer, + overflowed.join(" and the "), + f.name + ), )); } } else { @@ -411,18 +452,30 @@ fn gather(ds: &Dataset, t: &Target) -> Result { map.insert("distinct".into(), json!(t2.distinct.len())); if t2.capped { map.insert("distinctCapped".into(), json!(true)); - notices.push(if t2.byte_capped { format!( - "{}: '{}' reached the {} MiB distinct-text budget; it has more than {} distinct values and the distinct count stops at {}", - t.layer, f.name, MAX_DISTINCT_BYTES >> 20, t2.distinct.len(), t2.distinct.len() - ) } else { format!( - "{}: '{}' has more than {MAX_DISTINCT} distinct values; the distinct count stops at {MAX_DISTINCT}", - t.layer, f.name - ) }); + let text = if t2.byte_capped { + format!( + "{}: '{}' reached the {} MiB distinct-text budget; it has more than {} distinct values and the distinct count stops at {}", + t.layer, + f.name, + MAX_DISTINCT_BYTES >> 20, + t2.distinct.len(), + t2.distinct.len() + ) + } else { + format!( + "{}: '{}' has more than {MAX_DISTINCT} distinct values; the distinct count stops at {MAX_DISTINCT}", + t.layer, f.name + ) + }; + notices.push(Note::loss(LossCode::DroppedOverLimit, text)); } if t2.invalid_dates > 0 { - notices.push(format!( - "{}: {} value(s) in '{}' aren't dates and were left out of the date minimum and maximum", - t.layer, t2.invalid_dates, f.name + notices.push(Note::loss( + LossCode::DroppedValue, + format!( + "{}: {} value(s) in '{}' aren't dates and were left out of the date minimum and maximum", + t.layer, t2.invalid_dates, f.name + ), )); } map.insert("min".into(), json!(min)); @@ -482,7 +535,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { None => gather(&l.dataset, &target)?, }; for n in done.notices { - s.notify(n, false); + s.say(n); } Ok(done.answer) } diff --git a/crates/engine/src/tests/table_statistics.rs b/crates/engine/src/tests/table_statistics.rs index a1c27bbfdb..45230cbcf0 100644 --- a/crates/engine/src/tests/table_statistics.rs +++ b/crates/engine/src/tests/table_statistics.rs @@ -48,6 +48,7 @@ fn a_numeric_column_gives_its_numbers_over_all_rows() { assert!((v["stdDev"].as_f64().unwrap() - (8.0f64 / 3.0).sqrt()).abs() < 1e-12, "{v}"); let said: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); assert_eq!(said, ["parcels: 1 value(s) in 'area' that aren't finite numbers (NaN, infinity or other text) left out of the statistics"]); + assert!(s.notices_since(mark).iter().all(|n| n.loss() == Some(rustgis_data::loss::LossCode::DroppedValue)), "each with its code"); // Without a layer, the active one (the added layer). s.active_layer = s.map().layer_by_name("parcels").map(|l| l.id); assert_eq!(stats(&mut s, json!({"field": "N"}))["sum"], 100.0); @@ -141,6 +142,42 @@ fn whole_numbers_added_with_decimals_past_2_53_say_how_many_are_rounded() { stats(&mut s, json!({"layer": "w", "field": "x"})); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert_eq!(said, ["w: 2 whole number(s) in 'x' past 2^53 are rounded in the statistics, because the column also holds decimals"]); + assert!(s.notices_since(mark).iter().all(|n| n.loss() == Some(rustgis_data::loss::LossCode::ChangedRounded)), "each with its code"); + // Past 2^53 but held exactly (2^54): a sum with decimals that comes out rounded is said + // (2^54 + 5.5 is 2^54 + 4 as a decimal); one that comes out exact isn't. + let mut s = layer_of("w", fields.clone(), vec![vec![V::Int(5)], vec![V::Float(0.5)], vec![V::Int(1 << 54)]]); + let mark = s.notice_mark(); + assert_eq!(stats(&mut s, json!({"layer": "w", "field": "x"}))["sum"], ((1_i64 << 54) + 4) as f64); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.text.contains("are rounded"), n.loss())).collect(); + assert_eq!(said, [(true, Some(rustgis_data::loss::LossCode::ChangedRounded))]); + let mut s = layer_of("w", fields.clone(), vec![vec![V::Float(0.0)], vec![V::Int(1 << 54)]]); + let mark = s.notice_mark(); + stats(&mut s, json!({"layer": "w", "field": "x"})); + assert!(s.notices_since(mark).is_empty(), "an exact sum says nothing"); + // Decimals alone round a sum only as decimals do, which isn't said: the big ones cancel. + let cancel = vec![vec![V::Int(1 << 54)], vec![V::Int(-(1 << 54))], vec![V::Float(0.1)], vec![V::Float(0.2)]]; + let mut s = layer_of("w", fields.clone(), cancel); + let mark = s.notice_mark(); + stats(&mut s, json!({"layer": "w", "field": "x"})); + assert!(s.notices_since(mark).is_empty(), "{:?}", s.notices_since(mark)); + // Decimals alone past 2^53 round it the same way, and say so. + let mut s = layer_of("w", fields.clone(), vec![vec![V::Float((1_i64 << 54) as f64)], vec![V::Float(0.5)]]); + let mark = s.notice_mark(); + stats(&mut s, json!({"layer": "w", "field": "x"})); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| n.loss()).collect(); + assert_eq!(said, [Some(rustgis_data::loss::LossCode::ChangedRounded)]); + // So is the exact sum given where the running one overflows. + let huge = || vec![V::Float(f64::MAX), V::Float(f64::MAX), V::Float(-f64::MAX), V::Float(-f64::MAX), V::Int(1 << 54)]; + let mut rows: Vec> = huge().into_iter().map(|v| vec![v]).collect(); + rows.push(vec![V::Float(0.5)]); + let mut s = layer_of("w", fields.clone(), rows); + let mark = s.notice_mark(); + stats(&mut s, json!({"layer": "w", "field": "x"})); + assert!( + s.notices_since(mark).iter().any(|n| n.loss() == Some(rustgis_data::loss::LossCode::ChangedRounded)), + "{:?}", + s.notices_since(mark) + ); // The same column with values a decimal holds: nothing said. let mut s = layer_of("w", fields, vec![vec![V::Int(5)], vec![V::Float(0.5)]]); let mark = s.notice_mark(); @@ -159,6 +196,10 @@ fn a_sum_too_large_for_a_decimal_is_left_out_with_a_notice_and_the_mean_stays_ri assert_eq!(v["count"], 2); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert_eq!(said, ["w: the sum of 'x' is too large to hold as a decimal number (past about 1.8e308) and is left out"]); + assert!( + s.notices_since(mark).iter().all(|n| n.loss() == Some(rustgis_data::loss::LossCode::DroppedCalculationResult)), + "each with its code" + ); // Opposite extremes have a representable deviation, despite their squared spread. let mut s = layer_of("w", fields, vec![vec![V::Float(1.7e308)], vec![V::Float(-1.7e308)]]); let mark = s.notice_mark(); @@ -238,6 +279,7 @@ fn non_date_cells_in_a_date_field_are_counted_and_said() { let said: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); assert_eq!(said.len(), 1); assert!(said[0].contains("1 value(s)") && said[0].contains("aren't dates"), "{said:?}"); + assert!(s.notices_since(mark).iter().all(|n| n.loss() == Some(rustgis_data::loss::LossCode::DroppedValue)), "each with its code"); let mut clean = layer_of("w", vec![Field::new("date", FieldType::Date)], vec![vec![V::Date(Date::parse("2026-01-01").unwrap())]]); let mark = clean.notice_mark(); assert_eq!(stats(&mut clean, json!({"layer":"w","field":"date"}))["min"], "2026-01-01"); @@ -257,6 +299,7 @@ fn distinct_texts_are_counted_to_a_bound_and_past_it_the_answer_says_so() { assert_eq!(v["max"], "id99999"); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert_eq!(said, ["w: 'id' has more than 100000 distinct values; the distinct count stops at 100000"]); + assert!(s.notices_since(mark).iter().all(|n| n.loss() == Some(rustgis_data::loss::LossCode::DroppedOverLimit)), "each with its code"); // Exactly the bound: counted whole, nothing said. let mut s = layer_of("w", fields, rows(crate::cmd::table_stats::MAX_DISTINCT)); let mark = s.notice_mark();