diff --git a/crates/executor/src/operators/group_table.rs b/crates/executor/src/operators/group_table.rs index 96c032dc6..34a0271f2 100644 --- a/crates/executor/src/operators/group_table.rs +++ b/crates/executor/src/operators/group_table.rs @@ -18,6 +18,7 @@ use arrow::array::{ Array, ArrayRef, BooleanArray, Float64Array, Int64Array, StringArray, TimestampMillisecondArray, }; use planner_types::ir::schema::{DataType, FieldDataType}; +use std::sync::Arc; /// Approximate bytes of one hash-map entry beyond its key, for accounting. const MAP_ENTRY_BYTES: usize = 32; @@ -35,6 +36,11 @@ struct ColumnParts { first_values: Vec, /// Memory the parts hold, in bytes. memory_bytes: usize, + /// The part of each entry of the last text dictionary seen (kept + /// alive here, so its address identifies it), `u32::MAX` for an entry + /// not looked up yet: the slices of one batch (and batches sharing a + /// dictionary) look each entry up once, not once per slice. + entry_parts: Option<(ArrayRef, Vec)>, } impl ColumnParts { @@ -212,37 +218,31 @@ impl GroupTable { .downcast_ref::() .expect("batch text columns are dictionaries over strings"); let keys = dictionary.keys(); - let dense = arrow_columns::dense_dictionary(texts.len(), rows); - let mut slot_of_entry: Vec> = if dense { - vec![None; texts.len()] - } else { - Vec::new() - }; - let mut map_of_entry: HashMap = HashMap::new(); + let same_dictionary = parts + .entry_parts + .as_ref() + .is_some_and(|(values, _)| Arc::ptr_eq(values, dictionary.values())); + if !same_dictionary { + parts.entry_parts = + Some((dictionary.values().clone(), vec![u32::MAX; texts.len()])); + } + let mut entry_parts = parts.entry_parts.take().expect("set above"); let mut null_part = None; let mut lookup = |entry: u32, parts: &mut ColumnParts, key: &mut Vec| -> Result { - let cached = if dense { - slot_of_entry[entry as usize] - } else { - map_of_entry.get(&entry).copied() - }; - if let Some(part) = cached { - return Ok(part); + let cached = entry_parts.1[entry as usize]; + if cached != u32::MAX { + return Ok(cached); } let text = texts.value(entry as usize); key.clear(); key.push(4); key.extend_from_slice(text.as_bytes()); let part = parts.part(key, || Value::Utf8(text.into()))?; - if dense { - slot_of_entry[entry as usize] = Some(part); - } else { - map_of_entry.insert(entry, part); - } + entry_parts.1[entry as usize] = part; Ok(part) }; - return (0..rows) + let result = (0..rows) .map(|row| { if keys.is_null(row) { if let Some(part) = null_part { @@ -256,6 +256,8 @@ impl GroupTable { } }) .collect(); + parts.entry_parts = Some(entry_parts); + return result; } let any = array.as_any(); macro_rules! primitive { diff --git a/crates/executor/src/operators/joins/mod.rs b/crates/executor/src/operators/joins/mod.rs index 55648cc87..a8c6322c7 100644 --- a/crates/executor/src/operators/joins/mod.rs +++ b/crates/executor/src/operators/joins/mod.rs @@ -209,7 +209,36 @@ async fn relational_join( let (mut out_left, mut out_right): (Vec>, Vec>) = (Vec::new(), Vec::new()); let mut right_matched = vec![false; right.num_rows()]; + // An equi-join (a conjunction of column equalities across the sides) + // finds each left row's matches through a hash index of the right rows + // instead of evaluating the predicate on every pair; the matches and + // their order (ascending right row) are the same. + let equi = (*kind != JoinKind::Cross) + .then(|| { + equi_join_keys( + predicate.expression(), + &operator.inputs[0], + &operator.inputs[1], + ) + }) + .flatten() + .map(|keys| EquiIndex::new(left, right, &keys, &operator.inputs[0], &operator.inputs[1])) + .transpose()?; for left_row in 0..left.num_rows() as u32 { + if let Some(equi) = &equi { + let rows = equi.matches(left_row); + work.checkpoint_rows(rows.len().max(1)).await?; + emit_matches( + kind, + left_row, + rows.iter().copied(), + &mut right_matched, + &mut out_left, + &mut out_right, + ); + workspace.set_bytes(right.num_rows() + 8 * (out_left.len() + out_right.len()))?; + continue; + } // The pairs of this left row with every right row. let matches: Vec = if *kind == JoinKind::Cross { vec![true; right.num_rows()] @@ -244,35 +273,18 @@ async fn relational_join( } }; work.checkpoint_rows(right.num_rows().max(1)).await?; - let mut matched = false; - for (right_row, &is_match) in matches.iter().enumerate() { - if !is_match { - continue; - } - matched = true; - right_matched[right_row] = true; - match kind { - JoinKind::Semi => { - out_left.push(Some(left_row)); - break; - } - JoinKind::Anti => break, - _ => { - out_left.push(Some(left_row)); - out_right.push(Some(right_row as u32)); - } - } - } - if !matched { - match kind { - JoinKind::Left | JoinKind::Full => { - out_left.push(Some(left_row)); - out_right.push(None); - } - JoinKind::Anti => out_left.push(Some(left_row)), - _ => {} - } - } + emit_matches( + kind, + left_row, + matches + .iter() + .enumerate() + .filter(|(_, &is_match)| is_match) + .map(|(right_row, _)| right_row as u32), + &mut right_matched, + &mut out_left, + &mut out_right, + ); workspace.set_bytes(right.num_rows() + 8 * (out_left.len() + out_right.len()))?; } if matches!(kind, JoinKind::Right | JoinKind::Full) { @@ -317,6 +329,179 @@ async fn relational_join( Ok(result) } +/// The output pairs of `left_row` with its matching right rows +/// (ascending), as the nested-loop join emits them. +fn emit_matches( + kind: &planner_types::ir::operator::JoinKind, + left_row: u32, + matches: impl Iterator, + right_matched: &mut [bool], + out_left: &mut Vec>, + out_right: &mut Vec>, +) { + use planner_types::ir::operator::JoinKind; + let mut matched = false; + for right_row in matches { + matched = true; + right_matched[right_row as usize] = true; + match kind { + JoinKind::Semi => { + out_left.push(Some(left_row)); + break; + } + JoinKind::Anti => break, + _ => { + out_left.push(Some(left_row)); + out_right.push(Some(right_row)); + } + } + } + if !matched { + match kind { + JoinKind::Left | JoinKind::Full => { + out_left.push(Some(left_row)); + out_right.push(None); + } + JoinKind::Anti => out_left.push(Some(left_row)), + _ => {} + } + } +} + +/// The (left column, right column) pairs of a join predicate that is a +/// non-empty conjunction of SQL equalities, each between a left and a +/// right column of one type whose equality is equality of +/// [`Value::key`]s (text, integers, timestamps, dates, booleans; not +/// floats, whose `-0.0 = 0.0` and NaN differ); `None` for any other +/// predicate, which the nested loop evaluates. +fn equi_join_keys( + predicate: &planner_types::ir::ScalarExpr<()>, + left: &SchemaRef, + right: &SchemaRef, +) -> Option> { + use planner_types::ir::scalar::expr_ir::CompareOpKind; + use planner_types::ir::scalar::ExprSemantics; + use planner_types::ir::ScalarExpr; + let conjuncts: Vec<&planner_types::ir::ScalarExpr<()>> = match predicate { + ScalarExpr::BoolAnd(items) if !items.is_empty() => items.iter().collect(), + ScalarExpr::Compare { .. } => vec![predicate], + _ => return None, + }; + let width = left.fields.len(); + let key_type = |field: &planner_types::ir::schema::Field| match &field.dtype { + planner_types::ir::schema::FieldDataType::Plain( + dtype @ (DataType::Utf8 + | DataType::Int64 + | DataType::Timestamp + | DataType::Date + | DataType::Bool), + ) => Some(dtype.clone()), + _ => None, + }; + conjuncts + .into_iter() + .map(|conjunct| { + let ScalarExpr::Compare { + left: a, + op: CompareOpKind::Eq, + right: b, + semantics: ExprSemantics::Sql, + } = conjunct + else { + return None; + }; + let (ScalarExpr::Column(a), ScalarExpr::Column(b)) = (a.as_ref(), b.as_ref()) else { + return None; + }; + let (l, r) = match (*a < width, *b < width) { + (true, false) => (*a, *b - width), + (false, true) => (*b, *a - width), + _ => return None, + }; + let (lt, rt) = ( + key_type(left.fields.get(l)?)?, + key_type(right.fields.get(r)?)?, + ); + (lt == rt).then_some((l, r)) + }) + .collect() +} + +/// The right rows by their key values, and each left row's key: an +/// equi-join's matches without the pairs. A NULL in a key matches nothing. +struct EquiIndex { + rows_of_key: ahash::AHashMap, Vec>, + left_keys: Vec>>, +} + +impl EquiIndex { + fn new( + left: &Batch, + right: &Batch, + keys: &[(usize, usize)], + left_schema: &SchemaRef, + right_schema: &SchemaRef, + ) -> Result { + let row_keys = |batch: &Batch, + schema: &SchemaRef, + columns: Vec| + -> Result>>, Error> { + let decoded: Vec> = columns + .iter() + .map(|&column| { + let planner_types::ir::schema::FieldDataType::Plain(dtype) = + &schema.fields[column].dtype + else { + unreachable!("equi-join keys are plain columns") + }; + crate::values::arrow_columns::decode( + batch.column(column).as_ref(), + dtype, + crate::values::arrow_columns::ColumnDepth::BatchColumn, + ) + }) + .collect(); + (0..batch.num_rows()) + .map(|row| { + let mut key = Vec::new(); + for values in &decoded { + let value = &values[row]; + if matches!(value, Value::Null) { + return Ok(None); + } + let bytes = value.key()?; + key.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); + key.extend_from_slice(&bytes); + } + Ok(Some(key)) + }) + .collect() + }; + let left_keys = row_keys(left, left_schema, keys.iter().map(|k| k.0).collect())?; + let mut rows_of_key: ahash::AHashMap, Vec> = ahash::AHashMap::new(); + for (row, key) in row_keys(right, right_schema, keys.iter().map(|k| k.1).collect())? + .into_iter() + .enumerate() + { + if let Some(key) = key { + rows_of_key.entry(key).or_default().push(row as u32); + } + } + Ok(Self { + rows_of_key, + left_keys, + }) + } + + /// The right rows matching `left_row`, ascending. + fn matches(&self, left_row: u32) -> &[u32] { + self.left_keys[left_row as usize] + .as_ref() + .and_then(|key| self.rows_of_key.get(key)) + .map_or(&[], Vec::as_slice) + } +} + /// Left row `left_row` beside every right row: the pairs a join predicate /// is evaluated on. The right columns are shared; only the left row is /// repeated. diff --git a/crates/executor/src/summary_kernels/kmv.rs b/crates/executor/src/summary_kernels/kmv.rs index 4c0c09719..aadc7b79d 100644 --- a/crates/executor/src/summary_kernels/kmv.rs +++ b/crates/executor/src/summary_kernels/kmv.rs @@ -63,9 +63,9 @@ impl AggregateCore for KmvAccumulator { ) .into()); } - let mut merged = self.clone(); - merged.inner.merge(&other.inner); - Ok(Box::new(merged)) + Ok(Box::new(Self { + inner: union_of(&self.inner, &other.inner), + })) } /// Distinct count. @@ -81,6 +81,27 @@ impl AggregateCore for KmvAccumulator { } } +/// The KMV of `a` and `b` merged: the `k` smallest distinct hashes of +/// both, as [`Kmv::merge`] keeps them, found by one sort instead of a +/// duplicate scan of the retained hashes per merged hash (`O(k^2)`). +fn union_of(a: &Kmv, b: &Kmv) -> Kmv { + let mut hashes: Vec = a + .retained_hashes + .iter() + .chain(b.retained_hashes.iter()) + .copied() + .collect(); + hashes.sort_unstable(); + hashes.dedup(); + hashes.truncate(a.k); + let mut merged = Kmv::new(a.k); + // Largest first: each push is a leaf of the max-heap, no sift. + for &hash in hashes.iter().rev() { + merged.retained_hashes.push(hash); + } + merged +} + /// A KMV state is its own updater: it observes unkeyed sample values. impl AccumulatorUpdater for KmvAccumulator { fn update_value(&mut self, value: &crate::values::Value, _: i64) -> Result<(), String> { @@ -261,4 +282,30 @@ mod tests { .update_value(&Value::Float64(f64::INFINITY), 0) .is_err()); } + + // The sorted union keeps exactly the hashes the sketch library's + // sequential merge keeps, below, at and above k distinct items. + #[test] + fn merge_keeps_the_library_merges_hashes() { + let k = 64; + for (a, b) in [ + (0..10, 5..20), + (0..60, 30..90), + (0..500, 250..900), + (0..0, 0..70), + ] { + let (x, y) = (build(k, a), build(k, b)); + let mut expected = x.inner.clone(); + expected.merge(&y.inner); + let merged = x.merge_with(&y).unwrap(); + let merged = merged.as_any().downcast_ref::().unwrap(); + let sorted = |kmv: &Kmv| { + let mut hashes: Vec = kmv.retained_hashes.iter().copied().collect(); + hashes.sort_unstable(); + hashes + }; + assert_eq!(sorted(&merged.inner), sorted(&expected)); + assert_eq!(merged.inner.estimate(), expected.estimate()); + } + } } diff --git a/crates/executor/tests/physical_semantics.rs b/crates/executor/tests/physical_semantics.rs index 2cc18889e..d2c6387c8 100644 --- a/crates/executor/tests/physical_semantics.rs +++ b/crates/executor/tests/physical_semantics.rs @@ -2239,3 +2239,96 @@ fn float_text_matches_go_format_float() { ); } } + +/// A two-column text/integer equi-join gives the nested loop's rows, in +/// its order, for every join kind, with duplicate keys and NULLs on both +/// sides: the nested loop is forced by an extra (vacuously true) conjunct. +#[test] +fn equi_join_matches_the_nested_loop_row_for_row() { + let side = schema(&[ + ("name", DataType::Utf8, true), + ("n", DataType::Int64, true), + ("v", DataType::Float64, true), + ]); + let text = |s: &str| Value::Utf8(s.into()); + let left_rows: Vec> = vec![ + vec![text("a"), Value::Int64(1), Value::Float64(1.)], + vec![text("b"), Value::Int64(2), Value::Float64(2.)], + vec![text("a"), Value::Int64(1), Value::Float64(3.)], + vec![Value::Null, Value::Int64(1), Value::Float64(4.)], + vec![text("c"), Value::Null, Value::Float64(5.)], + vec![text("a"), Value::Int64(2), Value::Float64(6.)], + ]; + let right_rows: Vec> = vec![ + vec![text("a"), Value::Int64(1), Value::Float64(10.)], + vec![text("c"), Value::Null, Value::Float64(11.)], + vec![text("a"), Value::Int64(1), Value::Float64(12.)], + vec![text("b"), Value::Int64(2), Value::Float64(13.)], + vec![Value::Null, Value::Int64(1), Value::Float64(14.)], + vec![text("d"), Value::Int64(4), Value::Float64(15.)], + ]; + let equal = |l: usize, r: usize| ScalarExpr::Compare { + semantics: planner_types::ir::ExprSemantics::Sql, + left: Box::new(ScalarExpr::Column(l)), + op: CompareOpKind::Eq, + right: Box::new(ScalarExpr::Column(r)), + }; + // Right columns are numbered after the left ones; one equality is + // written right = left. + let equi = Predicate(ScalarExpr::BoolAnd(vec![equal(0, 3), equal(4, 1)])); + let nested = Predicate(ScalarExpr::BoolAnd(vec![ + equal(0, 3), + equal(4, 1), + ScalarExpr::BoolAnd(vec![]), + ])); + for kind in [ + JoinKind::Inner, + JoinKind::Left, + JoinKind::Right, + JoinKind::Full, + JoinKind::Semi, + JoinKind::Anti, + ] { + let output = if matches!(kind, JoinKind::Semi | JoinKind::Anti) { + side.clone() + } else { + schema(&[ + ("l_name", DataType::Utf8, true), + ("l_n", DataType::Int64, true), + ("l_v", DataType::Float64, true), + ("r_name", DataType::Utf8, true), + ("r_n", DataType::Int64, true), + ("r_v", DataType::Float64, true), + ]) + }; + let run = |predicate: &Predicate| { + let op = Operator::relational_join( + side.clone(), + side.clone(), + kind.clone(), + predicate, + output.clone(), + ) + .unwrap(); + let mut dag = PhysicalDAG::default(); + for (id, rows) in [(0, left_rows.clone()), (1, right_rows.clone())] { + let batches = rows + .chunks(4) + .map(|rows| Batch::try_new(side.clone(), rows.to_vec()).unwrap()) + .collect(); + dag.add( + id, + vec![], + Operator::source(side.clone(), batches).unwrap(), + Lifetime::None, + ) + .unwrap(); + } + dag.add(2, vec![0, 1], op, Lifetime::None).unwrap(); + collect(&dag, 2) + }; + let (fast, slow) = (run(&equi), run(&nested)); + assert_eq!(format!("{fast:?}"), format!("{slow:?}"), "{kind:?}"); + assert!(!slow.is_empty() || kind == JoinKind::Semi, "{kind:?}"); + } +}