Skip to content
Merged
103 changes: 78 additions & 25 deletions crates/engine/src/cmd/table_stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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<i128>);

impl WideSum {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Comment on lines +178 to +180

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This doc says decimals alone never round a sum this far, but the code and the tests say otherwise. The sum_rounded check is no longer gated on n.big, so a decimal-only column is flagged when its sum is off by half a unit or more. The test at tests/table_statistics.rs:163-168 asserts that Float(2^54) plus Float(0.5) gets the coded notice, and the comment at table_stats.rs:379 says "or decimals alone". Only the cancellation case (0.1 + 0.2, off by about 1e-17) is silent. The author's reply on the earlier thread repeats the wrong premise, so the code's behaviour and its doc disagree. Suggested doc:

Suggested change
/// 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.
/// Whether the sum the answer gives is off by half a unit or more, as a decimal can't hold a
/// fraction past 2^53. Decimals alone can be off this much too; 0.1 + 0.2 is off by far less, so
/// it isn't said. The sum given is the running one, or the exact one where that overflowed.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right: since the gate came off, the doc on sum_rounded overstates what decimals do. Its wording is left for the release quality pass.

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)));
Expand Down Expand Up @@ -267,7 +287,8 @@ fn resolve(s: &Session, p: &Value) -> Result<Target, String> {
/// An answer, and what it says to the user.
struct Done {
answer: Value,
notices: Vec<String>,
/// What the count left out or rounded, each with its code: every one is a real loss.
notices: Vec<rustgis_data::loss::Note>,
}

/// Counts column `t.column` of `ds` over its rows, looking at Cancel as it goes (see
Expand Down Expand Up @@ -336,25 +357,45 @@ fn gather(ds: &Dataset, t: &Target) -> Result<Done, String> {
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,
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
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",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The check compares only the sum (wide_sum.off_by(given)). The mean comes from Welford (n.all.mean), and its error is about the sum's error divided by n. A sum that is off by 0.5 can leave the mean off by much less than 0.5 (for three values, about 0.17), so "the sum and mean are rounded by half a unit or more" overstates the mean. Suggested text:

Suggested change
"{}: the sum and mean of '{}' are rounded by half a unit or more, as a decimal number holds no fraction past 2^53",
"{}: the sum of '{}' is rounded by half a unit or more, as a decimal number holds no fraction past 2^53",

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The mean's own check, or naming only the sum in the notice, is left for the release quality pass.

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The code's remediation (LossCode::DroppedCalculationResult in crates/data/src/loss.rs) reads "Correct the expression or check the input rows named in the notice." A Statistics sum, mean or standard deviation has no expression, and this notice doesn't name input rows. The same mismatch applies to DroppedValue here ("use a destination field that can hold it") and to the date and non-finite-value notices. In --strict runs, the CLI prints this text next to the failure, so the user would be told to fix an expression they never wrote. Check whether a shared code's wording should cover this use, or whether this should say something else. Confidence: medium. This is a wording point, not a defect in the count.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

True: the shared codes' help lines were written for other notices, an expression's result and a value a field can't hold. Whether a code's help should cover the Statistics pane, or say less, is left for the release quality pass.

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 {
Expand Down Expand Up @@ -411,18 +452,30 @@ fn gather(ds: &Dataset, t: &Target) -> Result<Done, String> {
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));
Expand Down Expand Up @@ -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)
}
43 changes: 43 additions & 0 deletions crates/engine/src/tests/table_statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<String> = 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<Vec<V>> = 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();
Expand All @@ -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<String> = 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();
Expand Down Expand Up @@ -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");
Expand All @@ -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<String> = 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();
Expand Down
Loading