Skip to content
Draft
16 changes: 12 additions & 4 deletions crates/cost/src/node/state_bytes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,11 +193,19 @@ impl StateInputRows {
.map(|rows| ((rows - 1e-9 * rows.abs().max(1.0)).ceil().max(1.0)) as u64)
}

/// Whether `other` folds what this does: the same rows once rounded,
/// sign, magnitude range and distinct values. Candidates of one input
/// group computing the same states fold the same.
/// Whether `other` folds what this does: the same rows once rounded up
/// (or to 0.1%: a filter keeping a share of a chain's windows rounds the
/// states it keeps, so a merge over them folds 60.014 rows where one
/// over all windows folds 60), sign, magnitude range and distinct
/// values. Candidates of one input group computing the same states fold
/// the same.
pub fn folds_the_same_as(&self, other: &Self) -> bool {
self.rows_per_state() == other.rows_per_state()
let rows_close = self.rows_per_state() == other.rows_per_state()
|| match (self.folded_rows_per_state, other.folded_rows_per_state) {
(Some(a), Some(b)) => (a - b).abs() <= 1e-3 * a.abs().max(b.abs()).max(1.0),
_ => false,
};
rows_close
&& self.non_negative == other.non_negative
&& self.value_magnitude_range == other.value_magnitude_range
&& self.distinct_values == other.distinct_values
Expand Down
180 changes: 180 additions & 0 deletions crates/cost/src/node/usage/kept_share.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
//! The share of rows a predicate keeps: each conjunct `column IN (k
//! values)` (also `column = v` and an `OR` of equalities on one column) on a
//! source column passed on unchanged whose distinct values N the sources
//! declare keeps k of the values left: the heaviest k's share under the
//! column's declared Zipf skew when the values stand for the heaviest ones
//! (a SIL binding from an upstream top-k), else k/N (rows per value
//! assumed uniform). Any other conjunct keeps every row.

use std::collections::{BTreeMap, BTreeSet};

use asap_types::ir::properties::selection::{constraint_of, Constraint};
use asap_types::ir::scalar::ScalarValue;
use asap_types::ir::schema::Schema;
use asap_types::ir::ScalarExpr;

/// What the sources declare about one column's values.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct DeclaredValues {
/// Its distinct values N (`distinct_values_per_label`).
pub(super) distinct: u64,
/// The Zipf exponent of rows over them (`zipf_exponent_per_label`),
/// when declared.
pub(super) zipf_exponent: Option<f64>,
}

/// What a predicate keeps of its input rows.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct KeptShare<'a> {
/// The share of rows kept, in (0, 1].
pub(super) share: f64,
/// The share of the restricted columns' values kept (k/N per column,
/// multiplied), in (0, 1]: what it keeps of per-key states, one per
/// group, whatever rows each folds. Equals `share` without skew.
pub(super) value_share: f64,
/// Each restricted column's distinct values left: the input's entries
/// with the predicate's IN-lists applied.
pub(super) kept_values_per_column: BTreeMap<&'a str, u64>,
/// The columns this predicate narrows at k/N because their sources
/// declare no skew (the `UniformRowsPerValue` assumption).
pub(super) assumed_uniform_columns: Vec<&'a str>,
}

/// The share of rows `conjuncts` keep over rows of `input_schema`, whose
/// `unchanged_columns` hold source columns as they are and whose restricted
/// columns have `kept_values_per_column` values left; `declared_values`
/// gives what the sources declare about a column, and
/// `heaviest_value_placeholders` the values standing for a column's
/// heaviest ones. Example: `host IN (10 values)` with N = 10,000 keeps 0.001
/// of the rows (0.299 when they are the heaviest 10 under Zipf(1)); a
/// second `host IN (5 of them)` above keeps 5 of the 10 left, 0.5.
pub(super) fn share_of_rows_kept<'a, C>(
conjuncts: &[&ScalarExpr<C>],
input_schema: &'a Schema,
unchanged_columns: &BTreeSet<&str>,
kept_values_per_column: &BTreeMap<&'a str, u64>,
declared_values: impl Fn(&str) -> Option<DeclaredValues>,
heaviest_value_placeholders: &[ScalarValue],
) -> KeptShare<'a> {
let mut kept = kept_values_per_column.clone();
let mut share = 1.0;
let mut value_share = 1.0;
let mut assumed_uniform_columns = Vec::new();
for conjunct in conjuncts.iter().flat_map(|c| flattened(c)) {
let Some((column, Constraint::In(values))) = constraint_of(conjunct) else {
continue;
};
let Some(field) = input_schema.fields.get(column) else {
continue;
};
let name = field.name.as_str();
if !unchanged_columns.contains(name) {
continue;
}
let Some(declared) = declared_values(name) else {
continue;
};
let before = kept.get(name).copied().unwrap_or(declared.distinct).max(1);
let after = (values.len() as u64).min(before);
let heaviest = values
.iter()
.any(|value| heaviest_value_placeholders.contains(value));
let zipf_exponent = declared.zipf_exponent.filter(|_| heaviest);
share *= share_of_rows_of_values(after, before, zipf_exponent);
value_share *= share_of_rows_of_values(after, before, None);
kept.insert(name, after);
if after < before
&& declared.zipf_exponent.is_none()
&& !assumed_uniform_columns.contains(&name)
{
assumed_uniform_columns.push(name);
}
}
KeptShare {
share,
value_share,
kept_values_per_column: kept,
assumed_uniform_columns,
}
}

/// The share of a column's rows that `kept` of its `values` distinct values
/// left hold: under a Zipf exponent s (`zipf_exponent`, given when the
/// values kept are the heaviest), H_kept(s)/H_values(s), the heaviest
/// values' mass (0.299 for 10 of 10,000 at s = 1); else `kept / values`,
/// rows per value uniform. Example: 10 of 10,000 hosts keep 0.001
/// uniformly.
fn share_of_rows_of_values(kept: u64, values: u64, zipf_exponent: Option<f64>) -> f64 {
match zipf_exponent {
Some(exponent) if kept < values => {
generalized_harmonic(kept, exponent) / generalized_harmonic(values, exponent)
}
Some(_) => 1.0,
None => kept as f64 / values.max(1) as f64,
}
}

/// H_n(s) = Σ_{i=1..n} 1/i^s: exact over the first 1,000 terms, the rest by
/// Euler–Maclaurin (the integral, the end and the first derivative
/// corrections; relative error below 1e-9).
fn generalized_harmonic(n: u64, exponent: f64) -> f64 {
const EXACT_TERMS: u64 = 1_000;
let exact: f64 = (1..=n.min(EXACT_TERMS))
.map(|i| (i as f64).powf(-exponent))
.sum();
if n <= EXACT_TERMS {
return exact;
}
let (m, n) = (EXACT_TERMS as f64, n as f64);
let integral = if (exponent - 1.0).abs() < 1e-12 {
(n / m).ln()
} else {
(n.powf(1.0 - exponent) - m.powf(1.0 - exponent)) / (1.0 - exponent)
};
let ends = (n.powf(-exponent) - m.powf(-exponent)) / 2.0;
let slopes = exponent * (m.powf(-exponent - 1.0) - n.powf(-exponent - 1.0)) / 12.0;
exact + integral + ends + slopes
}

/// The conjuncts of `expr`: the items of nested `AND`s, else `expr`.
fn flattened<C>(expr: &ScalarExpr<C>) -> Vec<&ScalarExpr<C>> {
if let ScalarExpr::BoolAnd(items) = expr {
items.iter().flat_map(flattened).collect()
} else {
vec![expr]
}
}

/// `rows` kept at `share`: none of none, else at least one.
pub(super) fn rows_kept(rows: u64, share: f64) -> u64 {
if rows == 0 {
0
} else {
((rows as f64 * share).round() as u64).clamp(1, rows)
}
}

#[cfg(test)]
mod tests {
use super::*;

/// The top 10 of 10,000 values under Zipf(1) hold H_10/H_10000 of the
/// rows, 0.2993 (E6 measured 0.293 on its Zipf data); uniform, 0.001.
#[test]
fn the_heaviest_values_keep_their_zipf_mass() {
let share = share_of_rows_of_values(10, 10_000, Some(1.0));
assert!((share - 0.299_253).abs() < 1e-5, "{share}");
assert_eq!(share_of_rows_of_values(10, 10_000, None), 0.001);
assert_eq!(share_of_rows_of_values(10_000, 10_000, Some(1.0)), 1.0);
}

/// The tail approximation matches the exact sum past 1,000 terms.
#[test]
fn the_harmonic_tail_matches_the_exact_sum() {
for exponent in [0.5, 1.0, 1.2] {
let exact: f64 = (1..=20_000u64).map(|i| (i as f64).powf(-exponent)).sum();
let approximate = generalized_harmonic(20_000, exponent);
assert!(((approximate - exact) / exact).abs() < 1e-9, "{exponent}");
}
}
}
Loading