use crate::core::vm::NavigationSource;
use std::collections::{BTreeMap, HashMap};
use crate::planning::ManagedAggregateBackend;
use crate::planning::logical::LogicalMatchProgram;
use datafusion::common::DFSchema;
use crate::core::vm::{
AggregateKind, AggregateLayout, AggregateValueSource, MAX_NAV_SLOTS,
MAX_PREV_BUFFERS, MAX_REGISTERS, NavSlotInfo, NavigationLayout, NavigationLocation,
NavigationValueDomain, PrevBufferInfo, RegisterLayout, RegisterWriter, SlotInfo,
SlotValueType,
};
use crate::planning::logical::LogicalSymbolId;
use recipe::{NavigationRequestKind, RegisterAggregateRecipe};
mod recipe;
pub(crate) use recipe::{AggregateAssembly, build_aggregate_assemblies};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AssembledMatchVm {
pub(crate) register_writers: Vec<Vec<RegisterWriter>>,
pub(crate) register_layout: RegisterLayout,
}
impl AssembledMatchVm {
pub(crate) fn empty(symbol_count: usize, aggregate_count: usize) -> Self {
Self {
register_writers: vec![Vec::new(); symbol_count],
register_layout: RegisterLayout::empty_compact(aggregate_count),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum VmAssemblyDowngrade {
AmbiguousInputColumn {
column: String,
},
RegisterCapacity {
aggregate_id: usize,
used: usize,
required: usize,
capacity: usize,
},
NavigationCapacity {
nav_slots: usize,
prev_buffers: usize,
},
MissingAggregateValueSource {
aggregate_id: usize,
},
InvalidArtifacts {
detail: String,
},
}
pub(crate) fn assemble_match_vm_state(
program: &LogicalMatchProgram,
aggregates: &[AggregateAssembly],
input_schema: &DFSchema,
) -> Result<AssembledMatchVm, VmAssemblyDowngrade> {
debug_assert_eq!(program.managed_aggregates().len(), aggregates.len());
if !aggregates
.iter()
.any(|aggregate| aggregate.backend == ManagedAggregateBackend::Registers)
{
return Ok(AssembledMatchVm::empty(
program.symbols().len(),
aggregates.len(),
));
}
if let Some(column) = ambiguous_input_column(input_schema) {
return Err(VmAssemblyDowngrade::AmbiguousInputColumn { column });
}
let mut layouts = vec![AggregateLayout::default(); aggregates.len()];
let mut register_writers = vec![Vec::new(); program.symbols().len()];
let mut row_input_names = Vec::new();
let mut row_input_as_float = Vec::new();
let mut row_inputs = HashMap::new();
let mut statistical_states = HashMap::new();
let mut sum_avg_states = HashMap::<
(Option<LogicalSymbolId>, String, SlotValueType, i8, bool),
usize,
>::new();
let mut next_slot = 0;
let mut navigation_requests = Vec::new();
for (index, aggregate) in aggregates.iter().enumerate() {
if aggregate.backend != ManagedAggregateBackend::Registers {
continue;
}
let recipe = aggregate.recipe.register().ok_or(
VmAssemblyDowngrade::MissingAggregateValueSource {
aggregate_id: aggregate.logical.id().index(),
},
)?;
match recipe {
RegisterAggregateRecipe::LeadingFirst { column } => {
layouts[index].value_source = AggregateValueSource::CandidateStart {
column: column.clone(),
};
continue;
}
RegisterAggregateRecipe::Navigation(request) => {
navigation_requests.push(request);
continue;
}
_ => {}
}
let (value_type, scale, kind, input) = match recipe {
RegisterAggregateRecipe::Algebraic { kind, input, .. } => (
input.value_type,
input.scale,
*kind,
Some((&input.column, input.nullable, input.as_float)),
),
RegisterAggregateRecipe::Variance { input, .. } => (
SlotValueType::Float64,
0,
AggregateKind::Variance,
Some((&input.column, input.nullable, input.as_float)),
),
RegisterAggregateRecipe::NonNullCount { input } => (
SlotValueType::Int64,
0,
AggregateKind::Additive,
Some((&input.column, true, false)),
),
RegisterAggregateRecipe::RowCount => {
(SlotValueType::Int64, 0, AggregateKind::Additive, None)
}
_ => unreachable!("navigation projections were handled above"),
};
let input = input.map(|(column, nullable, as_float)| {
*row_inputs
.entry((column.to_ascii_lowercase(), as_float))
.or_insert_with(|| {
let index = row_input_names.len();
row_input_names.push(column.clone());
row_input_as_float.push(as_float);
(index, nullable)
})
});
let statistical_key = match recipe {
RegisterAggregateRecipe::Variance { input, .. } => Some((
aggregate.logical.symbol(),
input.column.to_ascii_lowercase(),
)),
_ => None,
};
let sum_avg_key = match recipe {
RegisterAggregateRecipe::Algebraic {
kind: AggregateKind::Additive,
track_nonnull: true,
input,
}
| RegisterAggregateRecipe::Algebraic {
kind: AggregateKind::Avg,
input,
..
} => Some((
aggregate.logical.symbol(),
input.column.to_ascii_lowercase(),
input.value_type,
input.scale,
input.as_float,
)),
_ => None,
};
let shared = statistical_key
.as_ref()
.and_then(|key| statistical_states.get(key).copied())
.or_else(|| {
sum_avg_key
.as_ref()
.and_then(|key| sum_avg_states.get(key).copied())
.map(|start| SlotInfo::with_kind(start, value_type, scale, kind))
});
let slot = shared
.unwrap_or_else(|| SlotInfo::with_kind(next_slot, value_type, scale, kind));
let nonnull_count_slot = matches!(
recipe,
RegisterAggregateRecipe::Algebraic {
track_nonnull: true,
..
}
)
.then_some(slot.start_slot + slot.slot_count);
if shared.is_none() {
let required = slot.slot_count + usize::from(nonnull_count_slot.is_some());
if next_slot + required > MAX_REGISTERS {
return Err(VmAssemblyDowngrade::RegisterCapacity {
aggregate_id: aggregate.logical.id().index(),
used: next_slot,
required,
capacity: MAX_REGISTERS,
});
}
next_slot += required;
if let Some(key) = statistical_key {
statistical_states.insert(key, slot);
}
if let Some(key) = sum_avg_key {
sum_avg_states.insert(key, slot.start_slot);
}
let writer = match recipe {
RegisterAggregateRecipe::RowCount
| RegisterAggregateRecipe::NonNullCount { .. } => RegisterWriter::Count {
aggregate: index,
input: input.map(|(index, _)| index),
},
_ => {
let (input, nullable) = input.expect("numeric recipes have an input");
RegisterWriter::Accumulate {
aggregate: index,
input,
nullable,
}
}
};
if let Some(owner) = aggregate.logical.symbol() {
register_writers[owner.index()].push(writer);
} else {
for writers in &mut register_writers {
writers.push(writer);
}
}
}
layouts[index] = AggregateLayout {
slot: Some(slot),
value_source: register_value_source(recipe, &slot),
nonnull_count_slot,
};
}
let mut layout = NavigationLayout::default();
let mut primitive_column_names = Vec::new();
let mut decimal128_column_names = Vec::new();
let mut locations = HashMap::<NavigationKey, usize>::new();
let mut max_last_depth =
HashMap::<(Option<LogicalSymbolId>, NavigationValueDomain, &str), usize>::new();
for request in &navigation_requests {
if let NavigationRequestKind::LastOffset { depth, .. } = &request.kind {
let col_key = match request.domain {
NavigationValueDomain::Classifier => "",
NavigationValueDomain::Primitive | NavigationValueDomain::Decimal128 => {
request.column.as_str()
}
};
let entry = max_last_depth
.entry((request.scope, request.domain, col_key))
.or_insert(0);
*entry = (*entry).max(*depth);
}
}
for request in navigation_requests {
let col_key = match request.domain {
NavigationValueDomain::Classifier => "",
NavigationValueDomain::Primitive | NavigationValueDomain::Decimal128 => {
request.column.as_str()
}
};
let (storage, default_value, buffer_max_depth) = match &request.kind {
NavigationRequestKind::First {
offset,
default_value,
} => (NavigationStorage::First(*offset), default_value.clone(), 0),
NavigationRequestKind::LastOffset { default_value, .. } => {
let max_depth = max_last_depth
.get(&(request.scope, request.domain, col_key))
.copied()
.unwrap_or(0);
if max_depth <= 1 {
(NavigationStorage::Last, default_value.clone(), max_depth)
} else {
(
NavigationStorage::PrevBuffer,
default_value.clone(),
max_depth,
)
}
}
};
let value_idx = match request.domain {
NavigationValueDomain::Classifier => 0,
NavigationValueDomain::Primitive | NavigationValueDomain::Decimal128 => {
let names = if request.domain == NavigationValueDomain::Primitive {
&mut primitive_column_names
} else {
&mut decimal128_column_names
};
names
.iter()
.position(|name| name == &request.column)
.unwrap_or_else(|| {
let index = names.len();
names.push(request.column.clone());
index
})
}
};
let key = NavigationKey {
scope: request.scope,
domain: request.domain,
value_idx,
storage,
};
let make_slot = |nav_slot| NavSlotInfo {
symbol_idx: request.scope.map(LogicalSymbolId::index),
nav_slot,
value_idx,
domain: request.domain,
};
let width = request.domain.storage_width();
let (used, capacity) = match storage {
NavigationStorage::First(_) | NavigationStorage::Last => {
(&mut layout.num_nav_slots, MAX_NAV_SLOTS)
}
NavigationStorage::PrevBuffer => {
(&mut layout.num_prev_buffers, MAX_PREV_BUFFERS)
}
};
let index = match locations.entry(key) {
std::collections::hash_map::Entry::Occupied(entry) => *entry.get(),
std::collections::hash_map::Entry::Vacant(entry) => {
let index = *used;
if index + width > capacity {
return Err(VmAssemblyDowngrade::NavigationCapacity {
nav_slots: layout.num_nav_slots,
prev_buffers: layout.num_prev_buffers,
});
}
*used += width;
entry.insert(index);
match storage {
NavigationStorage::First(offset) => {
let pos = layout.first_slots.len();
layout.first_slots.push(make_slot(index));
if offset > 0 || !layout.first_offsets.is_empty() {
layout.first_offsets.resize(pos, 0);
layout.first_offsets.push(offset);
}
}
NavigationStorage::Last => layout.last_slots.push(make_slot(index)),
NavigationStorage::PrevBuffer => {
layout.prev_buffer_slots.push(PrevBufferInfo {
symbol_idx: request.scope.map(LogicalSymbolId::index),
depth: buffer_max_depth,
buffer_idx: index,
value_idx,
domain: request.domain,
});
}
}
index
}
};
let location = match (storage, &request.kind) {
(NavigationStorage::First(_), _) => NavigationLocation::First(index),
(
NavigationStorage::Last,
NavigationRequestKind::LastOffset { depth: 1, .. },
) => {
if !layout.prev_slots.iter().any(|slot| slot.nav_slot == index) {
layout.prev_slots.push(make_slot(index));
}
NavigationLocation::Prev(index)
}
(NavigationStorage::Last, _) => NavigationLocation::Last(index),
(
NavigationStorage::PrevBuffer,
NavigationRequestKind::LastOffset { depth, .. },
) => NavigationLocation::PrevBuffer {
index,
depth: *depth,
},
(NavigationStorage::PrevBuffer, NavigationRequestKind::First { .. }) => {
unreachable!("FIRST navigation never uses PrevBuffer storage")
}
};
layouts[request.aggregate_id.index()].value_source =
AggregateValueSource::Navigation(NavigationSource {
location,
domain: request.domain,
default_value,
});
}
layout.prev_slots.sort_unstable_by_key(|slot| slot.nav_slot);
let register_layout = RegisterLayout::builder(next_slot, layouts)
.row_inputs(row_input_names, row_input_as_float)
.navigation_inputs(
primitive_column_names,
decimal128_column_names,
layout.has_navigation().then_some(layout),
)
.try_build()
.map_err(|detail| VmAssemblyDowngrade::InvalidArtifacts { detail })?;
Ok(AssembledMatchVm {
register_writers,
register_layout,
})
}
fn ambiguous_input_column(input_schema: &DFSchema) -> Option<String> {
let mut first_name_by_normalized: BTreeMap<String, String> = BTreeMap::new();
for field in input_schema.fields() {
let normalized = field.name().to_ascii_lowercase();
if let Some(first_name) = first_name_by_normalized.get(&normalized) {
return Some(first_name.clone());
}
first_name_by_normalized.insert(normalized, field.name().to_string());
}
None
}
fn register_value_source(
recipe: &RegisterAggregateRecipe,
si: &SlotInfo,
) -> AggregateValueSource {
use crate::core::vm::{AggregateKind, AggregateValueSource as AVS};
let slot = si.start_slot;
match recipe {
RegisterAggregateRecipe::Variance { projection, .. } => AVS::Variance {
state_slot: slot,
projection: *projection,
},
RegisterAggregateRecipe::Algebraic {
kind: AggregateKind::Avg,
..
} => avg_value_source(slot, si),
RegisterAggregateRecipe::Algebraic { input, .. }
if si.value_type == SlotValueType::RetainedRow =>
{
AVS::RetainedRow {
slot,
column: input.column.clone(),
}
}
RegisterAggregateRecipe::RowCount
| RegisterAggregateRecipe::NonNullCount { .. }
| RegisterAggregateRecipe::Algebraic { .. } => match si.value_type {
SlotValueType::Decimal128 => AVS::RegisterD128 { slot },
_ => AVS::Register { slot },
},
RegisterAggregateRecipe::Navigation(_)
| RegisterAggregateRecipe::LeadingFirst { .. } => AVS::AccumulatorOwned,
}
}
fn avg_value_source(slot: usize, si: &SlotInfo) -> AggregateValueSource {
use crate::core::vm::AggregateValueSource as AVS;
let count_slot = si.count_slot().unwrap();
match si.value_type {
SlotValueType::Decimal128 => {
let target_scale = 38i8.min(si.scale + 4);
let scale_diff = (target_scale - si.scale) as u32;
let scale_factor = 10u32.pow(scale_diff);
AVS::AvgDecimal128 {
sum_slot: slot,
count_slot,
scale_factor,
}
}
_ => AVS::Avg {
sum_slot: slot,
count_slot,
},
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum NavigationStorage {
First(usize),
Last,
PrevBuffer,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct NavigationKey {
scope: Option<LogicalSymbolId>,
domain: NavigationValueDomain,
value_idx: usize,
storage: NavigationStorage,
}
#[cfg(test)]
mod tests;