use std::collections::HashMap;
use std::sync::Arc;
use crate::core::{NormalizedPattern, SymbolId};
use datafusion_common::Result;
use super::PatternMatcher;
use super::symbols::BoolColumnProvider;
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use crate::nfa::{CompiledAutomaton, PatternOptimizer, SymbolStatus};
use datafusion_execution::memory_pool::MemoryReservation;
use crate::execution::matching::SymbolColumn;
const ABSENT_SYMBOL_CACHE_CAPACITY: usize = 16;
const PRESENCE_WORK_CHUNK: usize = 256;
pub(crate) struct AbsentSymbolScan {
column: usize,
row: usize,
rows: usize,
columns: usize,
absent: Vec<SymbolId>,
}
impl AbsentSymbolScan {
pub(crate) fn new(columns: &[SymbolColumn], rows: usize) -> Self {
Self {
column: 0,
row: 0,
rows,
columns: columns.len(),
absent: Vec::new(),
}
}
pub(crate) fn advance(
&mut self,
provider: &impl BoolColumnProvider,
columns: &[SymbolColumn],
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
if provider.num_rows() != self.rows || columns.len() != self.columns {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE absence scan input changed across suspension"
);
}
let mut work = 0;
while self.column < columns.len() && work < PRESENCE_WORK_CHUNK {
let column = &columns[self.column];
if self.rows <= PRESENCE_WORK_CHUNK {
if work != 0 && self.rows.max(1) > PRESENCE_WORK_CHUNK - work {
break;
}
if !provider.symbol_is_present(column.id, completed)? {
self.absent.push(column.id);
}
self.column += 1;
completed(1)?;
work += self.rows.max(1);
} else if self.row == self.rows {
self.absent.push(column.id);
self.column += 1;
self.row = 0;
completed(1)?;
work += 1;
} else {
let rows = (self.rows - self.row).min(PRESENCE_WORK_CHUNK - work);
let end = self.row + rows;
let present = provider.symbol_is_present_in_range(
column.id,
self.row..end,
completed,
)?;
self.row = end;
work += rows;
if present {
self.column += 1;
self.row = 0;
completed(1)?;
}
}
}
Ok(self.column == columns.len())
}
pub(crate) fn finish(self) -> Result<Vec<SymbolId>> {
if self.column != self.columns {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE published an incomplete absence scan"
);
}
Ok(self.absent)
}
}
fn normalize_absent_symbols(
normalized: &NormalizedPattern,
automaton: &CompiledAutomaton,
absent: &[SymbolId],
) -> Result<NormalizedPattern> {
let mut status = HashMap::with_capacity(absent.len());
for &symbol in absent {
let name = automaton
.id_to_symbol()
.get(symbol.index())
.and_then(Option::as_ref)
.ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"MATCH_RECOGNIZE absence fact has no stable user-symbol identity"
)
})?;
status.insert(name.clone(), SymbolStatus::False);
}
Ok(match normalized {
NormalizedPattern::Ast(pattern) => PatternOptimizer::new(&status)
.with_allow_pruning(true)
.optimize(pattern),
terminal => terminal.clone(),
})
}
struct CacheEntry {
key: Vec<SymbolId>,
value: Arc<ExecutablePatternVariant>,
}
pub(crate) struct AbsentSymbolCache {
entries: Vec<CacheEntry>,
capacity: usize,
}
impl AbsentSymbolCache {
pub(crate) fn new() -> Self {
Self::with_capacity(ABSENT_SYMBOL_CACHE_CAPACITY)
}
pub(crate) fn with_capacity(capacity: usize) -> Self {
Self {
entries: Vec::new(),
capacity,
}
}
pub(crate) fn get(&self, key: &[SymbolId]) -> Option<Arc<ExecutablePatternVariant>> {
self.entries
.iter()
.find_map(|entry| (entry.key == key).then(|| Arc::clone(&entry.value)))
}
pub(crate) fn insert(
&mut self,
key: Vec<SymbolId>,
value: Arc<ExecutablePatternVariant>,
) {
if self.capacity == 0 {
return;
}
let replacement = CacheEntry { key, value };
if let Some(existing) = self
.entries
.iter_mut()
.find(|entry| entry.key == replacement.key)
{
*existing = replacement;
} else {
if self.entries.len() == self.capacity {
self.entries.remove(0);
}
self.entries.push(replacement);
}
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.entries.len()
}
}
pub(crate) enum PrunedPatternPreparation {
Scanning {
scan: AbsentSymbolScan,
memory: MemoryReservation,
},
PendingCompile {
absent_symbols: Vec<SymbolId>,
memory: MemoryReservation,
normalized: NormalizedPattern,
},
Ready(Arc<ExecutablePatternVariant>),
}
impl PrunedPatternPreparation {
pub(crate) fn advance(
self,
matcher: &mut PatternMatcher,
provider: &impl BoolColumnProvider,
completed: &mut impl FnMut(usize, &PatternMatcher) -> Result<()>,
) -> Result<Self> {
match self {
Self::Scanning { mut scan, memory } => {
if !scan.advance(
provider,
matcher.absence_symbol_columns(),
&mut |units| completed(units, matcher),
)? {
return Ok(Self::Scanning { scan, memory });
}
let absent_symbols = scan.finish()?;
matcher.prepare_absence_variant(absent_symbols, memory)
}
Self::PendingCompile {
absent_symbols,
memory,
normalized,
} => {
let variant = matcher.compile_pruned_variant(
&normalized,
&memory,
&mut |units| completed(units, matcher),
)?;
matcher
.services
.absent_symbol_cache
.insert(absent_symbols, Arc::clone(&variant));
Ok(Self::Ready(variant))
}
ready @ Self::Ready(_) => Ok(ready),
}
}
}
impl PatternMatcher {
#[inline]
pub(crate) fn should_prune_absent_symbols(
&self,
final_flush: bool,
start_row: usize,
read_end_row: usize,
rows_in_collection: usize,
) -> bool {
final_flush
&& ((start_row == 0 && read_end_row == rows_in_collection)
|| read_end_row.saturating_sub(start_row)
>= crate::execution::common::progress::COARSE_WORK_BATCH_SIZE)
&& self.program.can_skip_candidate_evaluation()
&& matches!(self.program.normalized_pattern(), NormalizedPattern::Ast(_))
&& !self.program.config().runtime_absent_symbol_pruning_disabled
}
#[cfg(test)]
pub(crate) fn absent_static_symbols(
&self,
provider: &impl BoolColumnProvider,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<Vec<SymbolId>> {
let columns = self.absence_symbol_columns();
let mut scan = AbsentSymbolScan::new(columns, provider.num_rows());
while !scan.advance(provider, columns, completed)? {}
scan.finish()
}
fn absence_symbol_columns(&self) -> &[SymbolColumn] {
self.program
.base_variant()
.active_symbol_columns()
.columns()
}
pub(crate) fn prepare_absent_symbol_pruning(
&self,
rows: usize,
memory: &MemoryReservation,
) -> PrunedPatternPreparation {
PrunedPatternPreparation::Scanning {
scan: AbsentSymbolScan::new(self.absence_symbol_columns(), rows),
memory: memory.new_empty(),
}
}
fn prepare_absence_variant(
&mut self,
absent_symbols: Vec<SymbolId>,
memory: MemoryReservation,
) -> Result<PrunedPatternPreparation> {
if absent_symbols.is_empty() {
return Ok(PrunedPatternPreparation::Ready(Arc::clone(
self.program.base_variant(),
)));
}
if let Some(cached) = self.services.absent_symbol_cache.get(&absent_symbols) {
return Ok(PrunedPatternPreparation::Ready(cached));
}
let normalized = normalize_absent_symbols(
self.program.normalized_pattern(),
self.automaton(),
&absent_symbols,
)?;
if &normalized == self.program.normalized_pattern() {
drop(normalized);
let variant = Arc::clone(self.program.base_variant());
self.services
.absent_symbol_cache
.insert(absent_symbols, Arc::clone(&variant));
return Ok(PrunedPatternPreparation::Ready(variant));
}
Ok(PrunedPatternPreparation::PendingCompile {
absent_symbols,
memory,
normalized,
})
}
fn compile_pruned_variant(
&self,
normalized: &NormalizedPattern,
memory: &MemoryReservation,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<Arc<ExecutablePatternVariant>> {
let limits = self.program.config().pattern_compile_limits;
let declared = self.program.base_variant().automaton().id_to_symbol();
let mut symbols = Vec::with_capacity(declared.len().saturating_sub(1));
for name in declared.iter().skip(1).flatten() {
symbols.push(name.clone());
}
let automaton = Arc::new(CompiledAutomaton::compile_with_limits(
normalized, &symbols, limits,
)?);
drop(symbols);
completed(automaton.nfa().state_count().max(1))?;
let columns = Arc::new(super::SymbolTable::try_transition_live(
&automaton,
self.program
.base_variant()
.active_symbol_columns()
.columns(),
)?);
let variant = ExecutablePatternVariant::try_new(
self.program.prepared.as_ref(),
normalized,
automaton,
columns,
self.program.config().compact_paths_disabled,
)?
.with_runtime_memory(memory.new_empty())?;
completed(1)?;
Ok(variant)
}
#[cfg(test)]
pub(crate) fn compile_variant_for_test(
&self,
normalized: NormalizedPattern,
) -> Result<Arc<ExecutablePatternVariant>> {
let memory = super::row_loop::state_growth::new_unbounded_state_memory();
self.compile_pruned_variant(&normalized, &memory, &mut |_| Ok(()))
}
#[cfg(test)]
pub(crate) fn prune_absent_symbols(
&mut self,
provider: &impl BoolColumnProvider,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<Arc<ExecutablePatternVariant>> {
let memory = super::row_loop::state_growth::new_unbounded_state_memory();
let mut preparation =
self.prepare_absent_symbol_pruning(provider.num_rows(), &memory);
loop {
preparation =
preparation.advance(self, provider, &mut |units, _| completed(units))?;
if let PrunedPatternPreparation::Ready(variant) = preparation {
return Ok(variant);
}
}
}
}
#[cfg(test)]
mod tests;