use super::fallible_vec::{filled, reserved};
use crate::core::SymbolId;
use crate::execution::matching::{ResolvedBoolColumn, SymbolColumn};
use crate::nfa::{AnchorEnvironment, CompiledAutomaton};
use datafusion_common::{DataFusionError, Result};
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct StaticStartWindow {
first: Option<Box<[StartCondition]>>,
second: Option<Box<[StartCondition]>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StartCondition {
StaticSymbol(SymbolId),
NecessaryAnd(Box<[ResolvedBoolColumn]>),
}
impl StaticStartWindow {
pub(crate) fn retained_size_bytes(&self) -> Result<usize> {
let mut total = Some(size_of::<Self>() + 2 * size_of::<usize>());
for conditions in self.first.iter().chain(&self.second) {
total = total.and_then(|n| n.checked_add(size_of_val(conditions.as_ref())));
for condition in conditions.iter() {
if let StartCondition::NecessaryAnd(columns) = condition {
total =
total.and_then(|n| n.checked_add(size_of_val(columns.as_ref())));
}
}
}
total.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE retained start-symbol plan exceeds usize".into(),
)
})
}
fn build_conditions<'a>(
symbol_ids: &[SymbolId],
has_static_column: &[bool],
necessary_columns: &impl Fn(SymbolId) -> &'a [ResolvedBoolColumn],
) -> Result<Option<Box<[StartCondition]>>> {
if symbol_ids.is_empty() {
return Ok(None);
}
let mut conditions = Vec::new();
conditions
.try_reserve_exact(symbol_ids.len())
.map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE start-symbol conditions could not reserve {} entries: {error}",
symbol_ids.len()
))
})?;
for &symbol_id in symbol_ids {
if has_static_column[symbol_id.index()] {
conditions.push(StartCondition::StaticSymbol(symbol_id));
} else {
let necessary = necessary_columns(symbol_id);
if necessary.is_empty() {
return Ok(None);
}
let mut copied = reserved(necessary.len(), "program entries")?;
copied.extend_from_slice(necessary);
conditions.push(StartCondition::NecessaryAnd(copied.into_boxed_slice()));
}
}
Ok(Some(conditions.into_boxed_slice()))
}
pub(crate) fn try_new_with_conditions<'a>(
compiled: &CompiledAutomaton,
symbol_columns: &[SymbolColumn],
necessary_columns: impl Fn(SymbolId) -> &'a [ResolvedBoolColumn],
can_cross: impl Fn(SymbolId) -> bool,
) -> Result<Self> {
let symbol_slots = compiled.num_symbols();
let mut has_static_column = filled(symbol_slots, false, "program entries")?;
for column in symbol_columns {
let dense_index = column.id.index();
let Some(slot) = has_static_column.get_mut(dense_index) else {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE start-symbol column {} is outside the compiled automaton's {symbol_slots}-slot table",
column.id
)));
};
*slot = true;
}
if compiled.min_match_rows() == 0 {
return Ok(Self::default());
}
let nfa = compiled.nfa();
let start = nfa.start_state();
let anchored = compiled.has_anchors();
let sources = if anchored {
[
Some(
compiled
.anchor_dispatch_closure(AnchorEnvironment::PhysicalStart, start),
),
(!compiled.has_mandatory_start_anchor_prefix()).then(|| {
compiled.anchor_dispatch_closure(
AnchorEnvironment::PhysicalInterior,
start,
)
}),
]
} else {
[Some(nfa.state(start).unconditional_dispatch()), None]
};
let accepts_empty = if anchored {
compiled
.anchor_first_accepting_state(AnchorEnvironment::PhysicalStart, start)
.is_some()
|| (!compiled.has_mandatory_start_anchor_prefix()
&& compiled
.anchor_first_accepting_state(
AnchorEnvironment::PhysicalInterior,
start,
)
.is_some())
} else {
compiled.unconditional_first_accepting_state()[start.index()].is_some()
};
if accepts_empty {
return Ok(Self::default());
}
let mut seen_sources = filled(nfa.state_count(), false, "start-window sources")?;
let mut seen_symbols = filled(symbol_slots, false, "start-window symbols")?;
let mut symbols = reserved(symbol_slots, "start-window symbols")?;
for group in sources.into_iter().flatten() {
collect_symbols(
compiled,
group,
&mut seen_sources,
&mut seen_symbols,
&mut symbols,
);
}
let mut window = Self {
first: Self::build_conditions(
&symbols,
&has_static_column,
&necessary_columns,
)?,
..Self::default()
};
if window.first.is_none() || anchored || compiled.min_match_rows() < 2 {
return Ok(window);
}
if !symbols
.iter()
.all(|id| has_static_column[id.index()] && can_cross(*id))
{
return Ok(window);
}
seen_sources.fill(false);
seen_symbols.fill(false);
symbols.clear();
for &source in nfa.state(start).unconditional_dispatch() {
for (_, targets) in nfa.state(source).transition_rows() {
for &target in targets {
if compiled.unconditional_first_accepting_state()[target.index()]
.is_some()
{
return Ok(window);
}
collect_symbols(
compiled,
nfa.state(target).unconditional_dispatch(),
&mut seen_sources,
&mut seen_symbols,
&mut symbols,
);
}
}
}
window.second =
Self::build_conditions(&symbols, &has_static_column, &necessary_columns)?;
Ok(window)
}
#[inline]
pub(crate) fn enabled_conditions(&self) -> Option<&[StartCondition]> {
self.first.as_ref().map(AsRef::as_ref)
}
#[inline]
pub(crate) fn enabled_successor_conditions(&self) -> Option<&[StartCondition]> {
self.second.as_ref().map(AsRef::as_ref)
}
}
fn collect_symbols(
compiled: &CompiledAutomaton,
sources: &[crate::nfa::AutomatonStateId],
seen_sources: &mut [bool],
seen_symbols: &mut [bool],
symbols: &mut Vec<SymbolId>,
) {
for &source in sources {
if std::mem::replace(&mut seen_sources[source.index()], true) {
continue;
}
for (symbol, targets) in compiled.nfa().state(source).transition_rows() {
if !targets.is_empty()
&& !std::mem::replace(&mut seen_symbols[symbol.index()], true)
{
symbols.push(symbol);
}
}
}
}