Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions crates/executor/src/operators/group_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -35,6 +36,11 @@ struct ColumnParts {
first_values: Vec<Value>,
/// 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<u32>)>,
}

impl ColumnParts {
Expand Down Expand Up @@ -212,37 +218,31 @@ impl GroupTable {
.downcast_ref::<StringArray>()
.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<Option<u32>> = if dense {
vec![None; texts.len()]
} else {
Vec::new()
};
let mut map_of_entry: HashMap<u32, u32> = 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<u8>| -> Result<u32, Error> {
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 {
Expand All @@ -256,6 +256,8 @@ impl GroupTable {
}
})
.collect();
parts.entry_parts = Some(entry_parts);
return result;
}
let any = array.as_any();
macro_rules! primitive {
Expand Down
243 changes: 214 additions & 29 deletions crates/executor/src/operators/joins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,36 @@ async fn relational_join(
let (mut out_left, mut out_right): (Vec<Option<u32>>, Vec<Option<u32>>) =
(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<bool> = if *kind == JoinKind::Cross {
vec![true; right.num_rows()]
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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<Item = u32>,
right_matched: &mut [bool],
out_left: &mut Vec<Option<u32>>,
out_right: &mut Vec<Option<u32>>,
) {
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<Vec<(usize, usize)>> {
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<u8>, Vec<u32>>,
left_keys: Vec<Option<Vec<u8>>>,
}

impl EquiIndex {
fn new(
left: &Batch,
right: &Batch,
keys: &[(usize, usize)],
left_schema: &SchemaRef,
right_schema: &SchemaRef,
) -> Result<Self, Error> {
let row_keys = |batch: &Batch,
schema: &SchemaRef,
columns: Vec<usize>|
-> Result<Vec<Option<Vec<u8>>>, Error> {
let decoded: Vec<Vec<Value>> = 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<u8>, Vec<u32>> = 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.
Expand Down
Loading