use crate::execution::matching::path::PathNodeIndex;
use crate::nfa::{AnchorEnvironment, AutomatonStateId};
use datafusion_common::{DataFusionError, Result};
pub(crate) use crate::execution::common::work::WorkGovernor;
pub(crate) use crate::execution::matching::selection::{AcceptingCandidate, BestMatch};
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct ActiveContainerGeneration(u64);
impl ActiveContainerGeneration {
#[cfg(test)]
pub(crate) const fn new(value: u64) -> Self {
Self(value)
}
pub(crate) const fn get(self) -> u64 {
self.0
}
pub(crate) const fn next(self) -> Self {
let next = self.0.wrapping_add(1);
Self(if next == 0 { 1 } else { next })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ActiveResumeIdentity {
pub(crate) active_idx: usize,
pub(crate) container_generation: ActiveContainerGeneration,
pub(crate) state_id: AutomatonStateId,
pub(crate) path: Option<PathNodeIndex>,
}
impl ActiveResumeIdentity {
pub(crate) const fn new(
active_idx: usize,
container_generation: ActiveContainerGeneration,
state_id: AutomatonStateId,
path: Option<PathNodeIndex>,
) -> Self {
Self {
active_idx,
container_generation,
state_id,
path,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ActiveCursorBinding {
identity: ActiveResumeIdentity,
match_sequence: Option<i64>,
}
impl ActiveCursorBinding {
fn new(identity: ActiveResumeIdentity) -> Self {
Self {
identity,
match_sequence: None,
}
}
}
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EpsilonSource {
#[default]
Unbound,
Precomputed,
Anchored(AnchorEnvironment),
Scratch {
generation: u32,
},
}
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub(crate) struct TransitionLoopState {
pub active_idx: usize,
pub eps_idx: usize,
pub sym_idx: usize,
pub next_idx: usize,
pub(crate) epsilon_source: EpsilonSource,
pub match_aware_sym_idx: usize,
pub(crate) active_cursor: Option<ActiveCursorBinding>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SymbolsReadyFrame {
define_cache_generation: u32,
matched_bitmap: u64,
}
impl SymbolsReadyFrame {
pub(crate) const fn define_cache_generation(&self) -> u32 {
self.define_cache_generation
}
pub(crate) const fn matched_bitmap(&self) -> u64 {
self.matched_bitmap
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TransitionFrame {
symbols: SymbolsReadyFrame,
active_generation: ActiveContainerGeneration,
loops: TransitionLoopState,
}
impl TransitionFrame {
pub(crate) const fn symbols(&self) -> SymbolsReadyFrame {
self.symbols
}
#[cfg(test)]
pub(crate) const fn active_generation(&self) -> ActiveContainerGeneration {
self.active_generation
}
#[cfg(test)]
pub(crate) const fn loops(&self) -> &TransitionLoopState {
&self.loops
}
pub(crate) fn loops_mut(&mut self) -> &mut TransitionLoopState {
&mut self.loops
}
pub(crate) fn validate_active_generation(
&self,
current: ActiveContainerGeneration,
) -> Result<()> {
if self.active_generation.get() == 0 {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE transition frame has an unbound active generation"
);
}
if self.active_generation != current {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE transition frame generation {:?} does not match active container {:?}",
self.active_generation,
current
);
}
Ok(())
}
pub(crate) fn validate_define_cache_generation(&self, current: u32) -> Result<()> {
if self.symbols.define_cache_generation != current {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE transition frame cache generation {} does not match prepared cache generation {current}",
self.symbols.define_cache_generation
);
}
Ok(())
}
}
#[derive(Debug, Default)]
pub(crate) enum ResumeFrame {
#[default]
StartRow,
Transitions(TransitionFrame),
}
impl ResumeFrame {
pub(crate) const fn name(&self) -> &'static str {
match self {
Self::StartRow => "StartRow",
Self::Transitions(_) => "Transitions",
}
}
pub(crate) const fn is_start_row(&self) -> bool {
matches!(self, Self::StartRow)
}
#[cfg(test)]
pub(crate) const fn is_transitions(&self) -> bool {
matches!(self, Self::Transitions(_))
}
pub(crate) const fn is_row_in_progress(&self) -> bool {
matches!(self, Self::Transitions(_))
}
#[cfg(test)]
pub(crate) const fn transition(&self) -> Option<&TransitionFrame> {
match self {
Self::Transitions(frame) => Some(frame),
Self::StartRow => None,
}
}
pub(crate) fn transition_mut(&mut self) -> Option<&mut TransitionFrame> {
match self {
Self::Transitions(frame) => Some(frame),
Self::StartRow => None,
}
}
pub(crate) fn begin_transitions(
&mut self,
define_cache_generation: u32,
matched_bitmap: u64,
active_generation: ActiveContainerGeneration,
) -> Result<()> {
if define_cache_generation == 0 {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE cannot publish transitions with an unbound cache generation"
);
}
if active_generation.get() == 0 {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE cannot begin transitions with an unbound active generation"
);
}
if !matches!(self, Self::StartRow) {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE cannot begin transitions from resume phase {}",
self.name()
);
}
*self = Self::Transitions(TransitionFrame {
symbols: SymbolsReadyFrame {
define_cache_generation,
matched_bitmap,
},
active_generation,
loops: TransitionLoopState::default(),
});
Ok(())
}
pub(crate) fn finish_row(&mut self) -> Result<()> {
if !matches!(self, Self::Transitions(_)) {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE cannot finish a row from resume phase {}",
self.name()
);
}
*self = Self::StartRow;
Ok(())
}
}
impl TransitionLoopState {
#[inline]
pub(crate) fn mark_epsilon_ready(&mut self, source: EpsilonSource) {
debug_assert!(!matches!(source, EpsilonSource::Unbound));
debug_assert!(!matches!(source, EpsilonSource::Scratch { generation: 0 }));
self.epsilon_source = source;
self.eps_idx = 0;
}
pub(crate) const fn epsilon_source(&self) -> EpsilonSource {
self.epsilon_source
}
pub(crate) fn validate_epsilon_scratch_generation(&self, current: u32) -> Result<()> {
let EpsilonSource::Scratch { generation } = self.epsilon_source else {
return Ok(());
};
if generation == 0 {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE epsilon scratch source has an unbound generation"
);
}
if generation != current {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE epsilon scratch generation {generation} does not match current generation {current}"
);
}
Ok(())
}
#[inline]
pub fn advance_next_idx(&mut self) {
self.next_idx += 1;
}
#[inline]
pub fn advance_regular_symbol(&mut self) {
self.sym_idx += 1;
self.next_idx = 0;
}
#[inline]
pub fn advance_match_aware_symbol(&mut self) {
self.match_aware_sym_idx += 1;
self.next_idx = 0;
}
#[inline]
pub fn advance_epsilon_state(&mut self) {
self.reset_inner_transition_cursors();
self.eps_idx += 1;
}
#[inline]
pub fn advance_active_state(&mut self) {
self.reset_inner_transition_cursors();
self.eps_idx = 0;
self.epsilon_source = EpsilonSource::Unbound;
self.active_idx += 1;
self.active_cursor = None;
}
#[inline]
fn reset_inner_transition_cursors(&mut self) {
self.sym_idx = 0;
self.next_idx = 0;
self.match_aware_sym_idx = 0;
}
pub(crate) fn bind_or_validate_active_identity(
&mut self,
expected: ActiveResumeIdentity,
) -> Result<()> {
match self.active_identity() {
None => {
self.active_cursor = Some(ActiveCursorBinding::new(expected));
Ok(())
}
Some(bound) if bound == expected => Ok(()),
Some(bound) => datafusion_common::internal_err!(
"MATCH_RECOGNIZE active cursor identity mismatch: bound {:?}, current {:?}",
bound,
expected
),
}
}
pub(crate) const fn active_identity(&self) -> Option<ActiveResumeIdentity> {
match self.active_cursor {
Some(cursor) => Some(cursor.identity),
None => None,
}
}
pub(crate) fn cached_active_match_sequence(&self) -> Result<Option<i64>> {
let cursor = self.active_cursor.as_ref().ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE cannot read match-sequence metadata for an unbound active cursor"
.to_string(),
)
})?;
Ok(cursor.match_sequence)
}
pub(crate) fn publish_active_match_sequence(&mut self, value: i64) -> Result<()> {
let cursor = self.active_cursor.as_mut().ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE cannot publish match-sequence metadata for an unbound active cursor"
.to_string(),
)
})?;
match cursor.match_sequence {
None => {
cursor.match_sequence = Some(value);
Ok(())
}
Some(cached) if cached == value => Ok(()),
Some(cached) => datafusion_common::internal_err!(
"MATCH_RECOGNIZE active match-sequence cache conflict for {:?}: cached value {}, new value {}",
cursor.identity,
cached,
value
),
}
}
pub(crate) const fn is_clean_unbound_active_cursor(&self) -> bool {
self.active_cursor.is_none()
&& self.eps_idx == 0
&& self.sym_idx == 0
&& self.next_idx == 0
&& matches!(self.epsilon_source, EpsilonSource::Unbound)
&& self.match_aware_sym_idx == 0
}
}
#[derive(Default, Debug)]
pub(crate) struct ScanState {
pub current_row: usize,
pub(crate) resume: ResumeFrame,
pub(crate) incumbent: Option<AcceptingCandidate>,
pub governor: WorkGovernor,
}
impl ScanState {
pub fn reset(&mut self, start_row: usize) {
self.current_row = start_row;
self.resume = ResumeFrame::StartRow;
self.incumbent = None;
}
}