use crate::config::YieldPolicy;
use crate::core::AbsoluteRow;
use crate::core::SymbolId;
use crate::execution::common::progress::ComputeStep;
use crate::execution::deferred::CandidateHistory;
use crate::execution::matching::ExecutableUserSymbolProgram;
use crate::execution::matching::PatternMatcher;
use crate::execution::matching::dedup::DedupArena;
use crate::execution::matching::epsilon::EpsilonClosureScratch;
use crate::execution::matching::graph::path_nodes::PathNodeArena;
use crate::execution::matching::path::PathNode;
use crate::execution::matching::path::PathNodeIndex;
use crate::execution::matching::path::PathStep;
use crate::execution::matching::path::Sym;
use crate::execution::matching::row_loop::aggregate_engine::AggregateEngine;
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use crate::execution::matching::row_loop::policies::AnchorPolicy;
use crate::execution::matching::row_loop::predicate_decision::TransitionDecision;
use crate::execution::matching::row_loop::state::AcceptingCandidate;
use crate::execution::matching::row_loop::state::ActiveContainerGeneration;
use crate::execution::matching::row_loop::state::ActiveResumeIdentity;
use crate::execution::matching::row_loop::state::BestMatch;
use crate::execution::matching::row_loop::state::EpsilonSource;
use crate::execution::matching::row_loop::state::TransitionLoopState;
use crate::execution::matching::row_loop::state::WorkGovernor;
use crate::execution::matching::row_loop::transition_kernel::FinalizeTransitionRequest;
use crate::execution::matching::row_loop::transition_kernel::PendingHistory;
use crate::execution::matching::row_loop::transition_kernel::PendingTransition;
use crate::execution::matching::row_loop::transition_kernel::TransitionCompletion;
use crate::execution::matching::row_loop::transition_kernel::TransitionKernel;
use crate::execution::matching::row_loop::transition_kernel::absolute_transition_row;
use crate::execution::matching::row_loop::types::ActiveThread;
use crate::execution::matching::row_loop::vm_executor;
use crate::nfa::AutomatonStateId;
use crate::nfa::CompiledAutomaton;
use crate::nfa::CompiledStateRef;
use datafusion_common::DataFusionError;
use datafusion_common::Result;
pub(super) struct TransitionScratch<'a> {
pub(super) traversal: &'a mut EpsilonClosureScratch,
pub(super) arena: DedupArena<'a>,
pub(super) node_arena: &'a mut PathNodeArena,
pub(super) loops: &'a mut TransitionLoopState,
pub(super) governor: &'a mut WorkGovernor,
pub(super) pending_transition: &'a mut Option<PendingTransition>,
pub(super) yield_policy: YieldPolicy,
}
pub(super) struct TransitionOutputs<'a> {
pub(super) history: &'a mut Option<Box<CandidateHistory>>,
pub(super) partition_end_row: usize,
pub(super) incumbent: &'a mut Option<AcceptingCandidate>,
}
pub(super) struct TransitionContext<'a, 'state> {
pub(super) matcher: &'a PatternMatcher,
pub(super) program: &'a ExecutablePatternVariant,
pub(super) partition_len: usize,
pub(super) pre_checks: &'a [bool],
pub(super) or_passes: &'a [bool],
pub(super) matched_symbols: &'a [SymbolId],
pub(super) scratch: TransitionScratch<'a>,
pub(super) outputs: TransitionOutputs<'a>,
pub(super) agg_engine: AggregateEngine<'a, 'state>,
pub(super) matched_bitmap: u64,
}
#[inline]
pub(in crate::execution::matching::row_loop::scan) fn run<
'a,
'state,
AP: AnchorPolicy,
>(
ctx: &mut TransitionContext<'a, 'state>,
active_states: &mut [ActiveThread],
active_generation: ActiveContainerGeneration,
anchor_policy: &mut AP,
) -> Result<ComputeStep> {
TransitionLoopRunner::new(ctx, active_states, active_generation, anchor_policy)?.run()
}
struct TransitionLoopRunner<'ctx, 'a, 'state, AP> {
ctx: &'ctx mut TransitionContext<'a, 'state>,
active_states: &'ctx mut [ActiveThread],
active_generation: ActiveContainerGeneration,
anchor_policy: &'ctx mut AP,
}
pub(crate) fn state_has_enabled_symbol(
compiled: &CompiledAutomaton,
state: CompiledStateRef<'_>,
bitmap: u64,
symbols: &[SymbolId],
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
if state.transition_bitmap() & bitmap != 0 {
return Ok(true);
}
if compiled.num_symbols() <= 64 {
return Ok(false);
}
for &symbol in symbols.iter().filter(|symbol| symbol.index() >= 64) {
let exists = !state.transitions(symbol).is_empty();
completed(1)?;
if exists {
return Ok(true);
}
}
Ok(false)
}
impl<'ctx, 'a, 'state, AP: AnchorPolicy> TransitionLoopRunner<'ctx, 'a, 'state, AP> {
fn new(
ctx: &'ctx mut TransitionContext<'a, 'state>,
active_states: &'ctx mut [ActiveThread],
active_generation: ActiveContainerGeneration,
anchor_policy: &'ctx mut AP,
) -> Result<Self> {
let loops = &*ctx.scratch.loops;
if loops.active_idx > active_states.len()
|| (loops.active_idx == active_states.len()
&& !loops.is_clean_unbound_active_cursor())
{
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE transition resumed with an out-of-bounds active cursor {} for {} active states",
loops.active_idx,
active_states.len()
);
}
match loops.epsilon_source() {
EpsilonSource::Anchored(bound)
if Some(bound) != anchor_policy.anchor_environment() =>
{
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE anchored epsilon environment changed across resume"
);
}
EpsilonSource::Precomputed
if anchor_policy.anchor_environment().is_some() =>
{
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE anchored transition resumed with an unconditional epsilon source"
);
}
_ => loops.validate_epsilon_scratch_generation(
ctx.scratch.traversal.tmp_generation,
)?,
}
Ok(Self {
ctx,
active_states,
active_generation,
anchor_policy,
})
}
fn run(mut self) -> Result<ComputeStep> {
if let Some(pending) = self.ctx.scratch.pending_transition.as_ref() {
let active_idx = pending.active_idx;
let source = pending.source;
let disposition = pending.completion.disposition;
let active = self.active_states.get(active_idx).ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"MATCH_RECOGNIZE pending transition lost its source"
)
})?;
let moved = disposition == TransitionDisposition::ConsumeSource;
if active_idx != self.ctx.scratch.loops.active_idx
|| active.state_id() != source.state_id
|| active.match_start_row() != source.match_start_row
|| moved != active.is_consumed()
|| (!moved && active.path() != source.path)
{
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE pending transition source changed"
);
}
let identity = ActiveResumeIdentity::new(
active_idx,
self.active_generation,
source.state_id,
source.path,
);
self.ctx
.scratch
.loops
.bind_or_validate_active_identity(identity)?;
let pending = self
.ctx
.scratch
.pending_transition
.take()
.expect("transition resumption requires its owned successor");
let Some(completion) = self.ctx.advance_pending_transition(
&mut self.active_states[active_idx],
pending,
)?
else {
return Ok(ComputeStep::Yield);
};
match completion.step() {
TransitionStep::RowComplete => {
self.ctx.scratch.loops.advance_active_state();
self.ctx.scratch.loops.active_idx = self.active_states.len();
return Ok(if self.checkpoint(3)? {
ComputeStep::Yield
} else {
ComputeStep::Complete
});
}
TransitionStep::SourceComplete => {
self.ctx.scratch.loops.advance_active_state();
self.record_completed_work(3)?;
}
TransitionStep::Skipped | TransitionStep::Finalized => {
self.ctx.scratch.loops.advance_next_idx();
self.record_completed_work(1)?;
}
TransitionStep::Pending => {
unreachable!("completed transition returned pending")
}
}
if self.take_yield_if_due() {
return Ok(ComputeStep::Yield);
}
}
self.advance()
}
fn epsilon_closure_len_for_active(
&mut self,
active_state_id: AutomatonStateId,
) -> Result<usize> {
let len = if let Some(environment) = self.anchor_policy.anchor_environment() {
match self.ctx.scratch.loops.epsilon_source() {
EpsilonSource::Unbound => self
.ctx
.scratch
.loops
.mark_epsilon_ready(EpsilonSource::Anchored(environment)),
EpsilonSource::Anchored(bound) if bound == environment => {}
EpsilonSource::Anchored(_) => {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE anchored epsilon environment changed across resume"
);
}
EpsilonSource::Precomputed | EpsilonSource::Scratch { .. } => {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE anchored transition resumed with the wrong epsilon source"
);
}
}
self.ctx
.program
.automaton()
.anchor_dispatch_closure(environment, active_state_id)
.len()
} else {
let needs_possessive_closure =
self.ctx.matcher.program.match_aware_symbols().is_empty()
&& !self.ctx.matched_symbols.is_empty()
&& self.ctx.program.has_possessive_controls();
if needs_possessive_closure {
match self.ctx.scratch.loops.epsilon_source() {
EpsilonSource::Scratch { .. } => {
self.ctx.scratch.loops.validate_epsilon_scratch_generation(
self.ctx.scratch.traversal.tmp_generation,
)?;
}
EpsilonSource::Precomputed => {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE possessive transition cannot resume a precomputed epsilon source"
);
}
EpsilonSource::Anchored(_) => {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE possessive transition cannot resume an anchored epsilon source"
);
}
EpsilonSource::Unbound => {
let matcher = self.ctx.matcher;
let governor = &mut *self.ctx.scratch.governor;
let automaton = self.ctx.program.automaton();
let traversal = &mut *self.ctx.scratch.traversal;
traversal.compute(
automaton,
active_state_id,
self.ctx.matched_bitmap,
self.ctx.matched_symbols,
&mut |units| {
governor.record_completed(units, || matcher.is_aborted())
},
)?;
self.ctx.scratch.loops.mark_epsilon_ready(
EpsilonSource::Scratch {
generation: traversal.tmp_generation,
},
);
}
}
self.ctx.scratch.traversal.tmp.len()
} else {
match self.ctx.scratch.loops.epsilon_source() {
EpsilonSource::Unbound => self
.ctx
.scratch
.loops
.mark_epsilon_ready(EpsilonSource::Precomputed),
EpsilonSource::Precomputed => {}
EpsilonSource::Anchored(_) | EpsilonSource::Scratch { .. } => {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE ordinary transition cannot resume a scratch epsilon source"
);
}
}
self.ctx
.program
.automaton()
.nfa()
.state(active_state_id)
.unconditional_dispatch()
.len()
}
};
Ok(len)
}
#[inline]
fn current_epsilon_state_id(
&self,
active_state_id: AutomatonStateId,
) -> Result<AutomatonStateId> {
match self.ctx.scratch.loops.epsilon_source() {
EpsilonSource::Precomputed => Ok(self
.ctx
.program
.automaton()
.nfa()
.state(active_state_id)
.unconditional_dispatch()[self.ctx.scratch.loops.eps_idx]),
EpsilonSource::Anchored(environment) => Ok(self
.ctx
.program
.automaton()
.anchor_dispatch_closure(environment, active_state_id)
[self.ctx.scratch.loops.eps_idx]),
EpsilonSource::Scratch { .. } => {
Ok(self.ctx.scratch.traversal.tmp[self.ctx.scratch.loops.eps_idx])
}
EpsilonSource::Unbound => datafusion_common::internal_err!(
"MATCH_RECOGNIZE transition has no epsilon source"
),
}
}
#[inline]
fn record_completed_work(&mut self, units: usize) -> Result<()> {
let matcher = self.ctx.matcher;
self.ctx
.scratch
.governor
.record_completed(units, || matcher.is_aborted())
}
#[inline]
fn take_yield_if_due(&mut self) -> bool {
self.ctx
.scratch
.governor
.take_yield_if_due_hot(self.ctx.scratch.yield_policy)
}
#[inline]
fn source_has_unpublished_acceptance(
&self,
active_idx: usize,
current_match_sequence_number: i64,
) -> bool {
if current_match_sequence_number != 1 {
return false;
}
let source_state_id = self.active_states[active_idx].state_id();
if let Some(environment) = self.anchor_policy.anchor_environment() {
self.ctx
.program
.automaton()
.anchor_first_accepting_state(environment, source_state_id)
.is_some()
} else {
self.ctx
.program
.automaton()
.unconditional_first_accepting_state()[source_state_id.index()]
.is_some()
}
}
fn bind_active(&mut self, index: usize) -> Result<AutomatonStateId> {
let active = self.active_states.get(index).ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"MATCH_RECOGNIZE active state cursor {index} exceeds active state length {}",
self.active_states.len()
)
})?;
let identity = ActiveResumeIdentity::new(
index,
self.active_generation,
active.state_id(),
active.path(),
);
self.ctx
.scratch
.loops
.bind_or_validate_active_identity(identity)?;
Ok(active.state_id())
}
fn has_primary(&mut self, state: AutomatonStateId) -> Result<bool> {
let matcher = self.ctx.matcher;
let compiled = self.ctx.program.automaton();
let governor = &mut *self.ctx.scratch.governor;
state_has_enabled_symbol(
compiled,
compiled.nfa().state(state),
self.ctx.matched_bitmap,
self.ctx.matched_symbols,
&mut |units| governor.record_completed(units, || matcher.is_aborted()),
)
}
fn has_extra(&mut self, state: AutomatonStateId) -> Result<bool> {
let matcher = self.ctx.matcher;
let compiled = self.ctx.program.automaton();
let governor = &mut *self.ctx.scratch.governor;
state_has_enabled_symbol(
compiled,
compiled.nfa().state(state),
matcher.program.match_aware_bitmap(),
matcher.program.match_aware_symbols(),
&mut |units| governor.record_completed(units, || matcher.is_aborted()),
)
}
fn apply(
&mut self,
active_idx: usize,
dispatch: AutomatonStateId,
symbol: SymbolId,
target: AutomatonStateId,
may_consume_source: bool,
) -> Result<TransitionStep> {
let Some(user_program) =
self.ctx.program.symbol_programs()[symbol.index()].user()
else {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE numeric transition resolved to an Empty executable program: nfa_state_id={}, symbol_id={}",
dispatch,
symbol
);
};
let active = &self.active_states[active_idx];
let current_match_sequence_number =
match self.ctx.scratch.loops.cached_active_match_sequence()? {
Some(value) => value,
None => {
let value =
if self.ctx.program.path_representation().uses_compact_paths() {
resolve_compact_match_sequence_number(
absolute_transition_row(
self.ctx.agg_engine.current_row,
self.ctx.agg_engine.partition_start_row,
self.ctx.partition_len,
self.ctx.agg_engine.global_row_offset,
)?,
active.match_start_row(),
)?
} else {
resolve_active_match_sequence_number(
active.state_id(),
active.path(),
self.ctx.scratch.node_arena,
)?
};
self.ctx
.scratch
.loops
.publish_active_match_sequence(value)?;
value
}
};
let disposition = if may_consume_source
&& !user_program.evaluator().may_read_history()
&& !self.source_has_unpublished_acceptance(
active_idx,
current_match_sequence_number,
) {
TransitionDisposition::ConsumeSource
} else {
TransitionDisposition::Fork
};
self.ctx.step_transition(
&mut self.active_states[active_idx],
dispatch,
symbol,
target,
disposition,
current_match_sequence_number,
user_program,
self.anchor_policy,
)
}
fn checkpoint(&mut self, units: usize) -> Result<bool> {
self.record_completed_work(units)?;
Ok(self.take_yield_if_due())
}
#[inline]
fn source_accept_info(
&self,
active_state_id: AutomatonStateId,
) -> Option<(usize, AutomatonStateId)> {
let compiled = self.ctx.program.automaton();
match self.ctx.scratch.loops.epsilon_source() {
EpsilonSource::Precomputed => compiled
.accepting_preference_rank(active_state_id, None)
.zip(
compiled.unconditional_first_accepting_state()
[active_state_id.index()],
),
EpsilonSource::Anchored(environment) => compiled
.accepting_preference_rank(active_state_id, Some(environment))
.zip(compiled.anchor_first_accepting_state(environment, active_state_id)),
EpsilonSource::Scratch { .. } => self.ctx.scratch.traversal.first_accepting,
EpsilonSource::Unbound => None,
}
}
fn publish_source_acceptance(
&mut self,
active_idx: usize,
accepting_state: AutomatonStateId,
) -> Result<()> {
if self.ctx.program.path_representation().uses_compact_paths() {
return Ok(());
}
let active = &self.active_states[active_idx];
if active.is_consumed() {
return Ok(());
}
let absolute_row = absolute_transition_row(
self.ctx.agg_engine.current_row,
self.ctx.agg_engine.partition_start_row,
self.ctx.partition_len,
self.ctx.agg_engine.global_row_offset,
)?;
if let Some(path) = active.path()
&& let Some(current) = self.ctx.outputs.incumbent.as_mut()
&& current.best_match.path_end == path
{
current.best_match.state_id = accepting_state;
} else {
let (candidate_node_idx, end_row) = if let Some(idx) = active.path() {
(idx, self.ctx.scratch.node_arena[idx as usize].step.row)
} else {
let empty_step = PathStep {
row: absolute_row,
sym: Sym::Empty,
excluded: false,
};
(
self.ctx.scratch.node_arena.allocate(empty_step, None)?,
absolute_row,
)
};
*self.ctx.outputs.incumbent = Some(AcceptingCandidate {
best_match: BestMatch {
path_end: candidate_node_idx,
state_id: accepting_state,
row: absolute_row,
match_start_row: active.match_start_row(),
},
end_row,
});
}
Ok(())
}
fn advance(&mut self) -> Result<ComputeStep> {
let is_virtual_row = self.ctx.agg_engine.current_row >= self.ctx.partition_len;
'sources: while self.ctx.scratch.loops.active_idx < self.active_states.len() {
let active_idx = self.ctx.scratch.loops.active_idx;
let source = self.bind_active(active_idx)?;
let dispatch_len = self.epsilon_closure_len_for_active(source)?;
let accept_info = self.source_accept_info(source);
if is_virtual_row {
if let Some((_, accepting_state)) = accept_info {
self.record_completed_work(1)?;
self.publish_source_acceptance(active_idx, accepting_state)?;
self.ctx.scratch.loops.advance_active_state();
self.ctx.scratch.loops.active_idx = self.active_states.len();
return Ok(ComputeStep::Complete);
}
self.ctx.scratch.loops.advance_active_state();
if self.checkpoint(1)? {
return Ok(ComputeStep::Yield);
}
continue 'sources;
}
while self.ctx.scratch.loops.eps_idx <= dispatch_len {
if let Some((accept_offset, accepting_state)) = accept_info
&& self.ctx.scratch.loops.eps_idx == accept_offset
{
self.record_completed_work(1)?;
self.publish_source_acceptance(active_idx, accepting_state)?;
self.ctx.scratch.loops.advance_active_state();
self.ctx.scratch.loops.active_idx = self.active_states.len();
return Ok(ComputeStep::Complete);
}
if self.ctx.scratch.loops.eps_idx == dispatch_len {
break;
}
let dispatch = self.current_epsilon_state_id(source)?;
let primary = self.has_primary(dispatch)?;
let extra = !self.ctx.matcher.program.match_aware_symbols().is_empty()
&& self.has_extra(dispatch)?;
if primary || extra {
loop {
let match_aware = !(primary
&& self.ctx.scratch.loops.sym_idx
< self.ctx.matched_symbols.len());
let symbol = if match_aware {
if !extra
|| self.ctx.scratch.loops.match_aware_sym_idx
>= self
.ctx
.matcher
.program
.match_aware_symbols()
.len()
{
break;
}
self.ctx.matcher.program.match_aware_symbols()
[self.ctx.scratch.loops.match_aware_sym_idx]
} else {
self.ctx.matched_symbols[self.ctx.scratch.loops.sym_idx]
};
let target_len = self
.ctx
.program
.automaton()
.nfa()
.state(dispatch)
.transitions(symbol)
.len();
if target_len == 0
|| (match_aware && !self.ctx.pre_checks[symbol.index()])
{
if match_aware {
self.ctx.scratch.loops.advance_match_aware_symbol();
} else {
self.ctx.scratch.loops.advance_regular_symbol();
}
if self.checkpoint(1)? {
return Ok(ComputeStep::Yield);
}
continue;
}
while self.ctx.scratch.loops.next_idx < target_len {
let (active_idx, eps_idx, sym_idx, next_idx) = {
let loops = &*self.ctx.scratch.loops;
(
loops.active_idx,
loops.eps_idx,
loops.sym_idx,
loops.next_idx,
)
};
let target = self
.ctx
.program
.automaton()
.nfa()
.state(dispatch)
.transitions(symbol)[next_idx];
let may_consume_source = !match_aware
&& !extra
&& eps_idx + 1 == dispatch_len
&& sym_idx + 1 == self.ctx.matched_symbols.len()
&& next_idx + 1 == target_len
&& (accept_info.is_none()
|| active_idx + 1 == self.active_states.len());
match self.apply(
active_idx,
dispatch,
symbol,
target,
may_consume_source,
)? {
TransitionStep::Pending => return Ok(ComputeStep::Yield),
TransitionStep::RowComplete => {
self.ctx.scratch.loops.advance_active_state();
self.ctx.scratch.loops.active_idx =
self.active_states.len();
return Ok(if self.checkpoint(3)? {
ComputeStep::Yield
} else {
ComputeStep::Complete
});
}
TransitionStep::SourceComplete => {
self.ctx.scratch.loops.advance_active_state();
if self.checkpoint(3)? {
return Ok(ComputeStep::Yield);
}
continue 'sources;
}
TransitionStep::Skipped | TransitionStep::Finalized => {}
}
self.ctx.scratch.loops.advance_next_idx();
if self.checkpoint(1)? {
return Ok(ComputeStep::Yield);
}
}
if match_aware {
self.ctx.scratch.loops.advance_match_aware_symbol();
self.record_completed_work(1)?;
} else {
self.ctx.scratch.loops.advance_regular_symbol();
}
}
}
self.ctx.scratch.loops.advance_epsilon_state();
if self.checkpoint(1)? {
return Ok(ComputeStep::Yield);
}
}
self.ctx.scratch.loops.advance_active_state();
if self.checkpoint(1)? {
return Ok(ComputeStep::Yield);
}
}
Ok(ComputeStep::Complete)
}
}
fn restore_or_discard_transition_state(
active: &mut ActiveThread,
mut state: ActiveThread,
source: TransitionSource,
disposition: TransitionDisposition,
) {
source.restore_identity(&mut state);
match disposition {
TransitionDisposition::Fork => {}
TransitionDisposition::ConsumeSource => *active = state,
}
}
pub(super) fn resolve_active_match_sequence_number(
active_state_id: AutomatonStateId,
path_idx: Option<PathNodeIndex>,
node_arena: &[PathNode],
) -> Result<i64> {
let Some(path_idx) = path_idx else {
return Ok(1);
};
let error = |reason| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE predicate active state {active_state_id} path identity {path_idx} \
{reason}; retained arena cardinality {}",
node_arena.len()
))
};
let index = usize::try_from(path_idx).map_err(|_| error("cannot address usize"))?;
let node = node_arena.get(index).ok_or_else(|| error("is missing"))?;
Ok(i64::from(node.depth) + 2)
}
pub(super) fn resolve_compact_match_sequence_number(
current_row: AbsoluteRow,
match_start_row: AbsoluteRow,
) -> Result<i64> {
let offset = current_row.checked_offset_from(match_start_row).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE compact transition row {current_row} precedes match start {match_start_row}"
))
})?;
offset
.as_u64()
.checked_add(1)
.and_then(|value| i64::try_from(value).ok())
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact match sequence is too large to represent as i64"
.to_string(),
)
})
}
impl<'a, 'state> TransitionContext<'a, 'state> {
#[allow(clippy::too_many_arguments)]
fn step_transition<AP: AnchorPolicy>(
&mut self,
active: &mut ActiveThread,
nfa_state_id: AutomatonStateId,
symbol_id: SymbolId,
next_state_id: AutomatonStateId,
disposition: TransitionDisposition,
sequence: i64,
user_program: &ExecutableUserSymbolProgram,
anchor_policy: &mut AP,
) -> Result<TransitionStep> {
let current_row = self.agg_engine.current_row;
let partition_len = self.partition_len;
if current_row >= partition_len {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE numeric transition requested at virtual end or beyond the physical partition: \
row={current_row}, partition_len={partition_len}, nfa_state_id={nfa_state_id}, symbol_id={symbol_id}, \
next_state_id={next_state_id}"
);
}
let or_pass = self.or_passes[symbol_id.index()];
let excluded = self
.program
.automaton()
.nfa()
.state(nfa_state_id)
.is_excluded();
let cache_probe = self.agg_engine.probe_predicate_cache(
user_program,
symbol_id,
active.match_start_row(),
excluded,
);
if cache_probe.cached_decision() == Some(TransitionDecision::Reject) {
log::trace!(
target: "datafusion_match_recognize::execution::matching::predicate_cache",
event = "cached_transition_reject",
current_row = self.agg_engine.current_row,
active_state_id = active.state_id().index(),
symbol_id:% = symbol_id,
match_start_row:% = active.match_start_row();
"row {}: active_state={} symbol_id={} match_start={} - cached false, skipping",
self.agg_engine.current_row,
active.state_id(),
symbol_id,
active.match_start_row()
);
return Ok(TransitionStep::Skipped);
}
crate::execution::matching::state_set::preflight_next_state_insert(
next_state_id,
&mut self.scratch.arena,
)?;
let source = TransitionSource::capture(active);
let evaluate = |ctx: &mut TransitionContext<'a, 'state>,
candidate: &mut ActiveThread| {
let matcher = ctx.matcher;
let governor = &mut *ctx.scratch.governor;
vm_executor::execute_transition_vm_ops(
&mut ctx.agg_engine,
matcher,
ctx.scratch.arena.memory,
candidate,
user_program,
&mut |units| governor.record_completed(units, || matcher.is_aborted()),
)?;
let evaluation = &mut ctx.agg_engine.state.evaluation;
evaluation.current_match_sequence_number = sequence;
evaluation.current_excluded = excluded;
ctx.agg_engine.evaluate_transition(
candidate,
source.match_start_row,
symbol_id,
user_program,
ctx.partition_len,
excluded,
or_pass,
cache_probe,
&mut |units| governor.record_completed(units, || matcher.is_aborted()),
)
};
let mut next = if disposition == TransitionDisposition::Fork {
active.clone_fork()
} else {
active.take_transition_state()
};
let (next_state, outcome) = match evaluate(self, &mut next) {
Ok(accepted) if accepted != TransitionDecision::Reject => (next, accepted),
result => {
restore_or_discard_transition_state(active, next, source, disposition);
result?;
return Ok(TransitionStep::Skipped);
}
};
let needs_history = outcome == TransitionDecision::CheckHistory;
let mut kernel = TransitionKernel {
compiled: self.program.automaton(),
path_representation: self.program.path_representation(),
node_arena: self.scratch.node_arena,
incumbent: self.outputs.incumbent,
};
let request = FinalizeTransitionRequest {
nfa_state_id,
sym_id: symbol_id,
next_state_id,
needs_history,
current_row: self.agg_engine.current_row,
partition_start_row: self.agg_engine.partition_start_row,
partition_len: self.partition_len,
global_row_offset: self.agg_engine.global_row_offset,
current_match_number: self.agg_engine.next_match_number,
source,
disposition,
};
let mut pending = kernel
.begin_transition(self.matcher, next_state, request, anchor_policy)
.map_err(|boxed| {
let (error, state) = *boxed;
restore_or_discard_transition_state(active, state, source, disposition);
error
})?;
pending.active_idx = self.scratch.loops.active_idx;
debug_assert!(self.scratch.pending_transition.is_none());
Ok(self
.advance_pending_transition(active, pending)?
.map_or(TransitionStep::Pending, TransitionCompletion::step))
}
fn advance_pending_transition(
&mut self,
active: &mut ActiveThread,
mut pending: PendingTransition,
) -> Result<Option<TransitionCompletion>> {
loop {
let node = pending.candidate.as_ref().and_then(|state| state.path());
let progress = if let Some(check) = pending.history.as_mut() {
self.advance_history(node, check)
.map(|verdict| match verdict {
Some(false) => TransitionStep::Skipped,
Some(true) => {
pending.history = None;
TransitionStep::Pending
}
None => TransitionStep::Pending,
})
} else {
let mut kernel = TransitionKernel {
compiled: self.program.automaton(),
path_representation: self.program.path_representation(),
node_arena: self.scratch.node_arena,
incumbent: self.outputs.incumbent,
};
kernel
.advance_transition(
self.matcher,
&mut pending,
&mut self.scratch.arena,
self.scratch.governor,
)
.map(|done| {
if done {
pending.completion.step()
} else {
TransitionStep::Pending
}
})
};
match progress {
Ok(
TransitionStep::Finalized
| TransitionStep::SourceComplete
| TransitionStep::RowComplete,
) => {
return Ok(Some(pending.completion));
}
Ok(TransitionStep::Pending) => {}
Ok(TransitionStep::Skipped) | Err(_) => {
let mut completion = pending.completion;
let source = pending.source;
if let (Some(history), Some(node)) =
(self.outputs.history.as_mut(), node)
{
history.discard(node);
}
let proposed =
pending.abort(self.scratch.node_arena, self.outputs.incumbent);
restore_or_discard_transition_state(
active,
proposed,
source,
completion.disposition,
);
progress?;
completion.accepted = false;
return Ok(Some(completion));
}
}
if self
.scratch
.governor
.take_yield_if_due_hot(self.scratch.yield_policy)
{
*self.scratch.pending_transition = Some(pending);
return Ok(None);
}
}
}
fn advance_history(
&mut self,
node: Option<PathNodeIndex>,
check: &mut PendingHistory,
) -> Result<Option<bool>> {
let node = node.ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"History predicate requires a labelled candidate path"
)
})?;
let history = match &mut *self.outputs.history {
Some(history) => history,
slot @ None => slot.insert(Box::new(
self.matcher
.program
.new_candidate_history(self.scratch.arena.memory)?,
)),
};
if !check.started {
history.begin(node, check.symbol, check.match_number)?;
if let Some(metrics) = &self.matcher.services.metrics {
metrics.deferred_requests.add(1);
metrics.route_evaluator_deferred.add(1);
}
check.started = true;
}
let head = self.agg_engine.global_row_offset;
let end = head
.checked_add(self.outputs.partition_end_row)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"History partition end exceeds usize".into(),
)
})?;
history.advance(
self.agg_engine.input_buffer,
self.scratch.node_arena,
head,
end,
&mut |units| {
self.scratch
.governor
.record_completed(units, || self.matcher.is_aborted())
},
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TransitionDisposition {
Fork,
ConsumeSource,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct TransitionSource {
pub(crate) state_id: AutomatonStateId,
pub(crate) path: Option<PathNodeIndex>,
pub(crate) match_start_row: AbsoluteRow,
pub(crate) deferred_history_fingerprint: u64,
}
impl TransitionSource {
pub(crate) fn capture(state: &ActiveThread) -> Self {
Self {
state_id: state.state_id(),
path: state.path(),
match_start_row: state.match_start_row(),
deferred_history_fingerprint: state.inner().deferred_history_fingerprint,
}
}
pub(crate) fn restore_identity(self, state: &mut ActiveThread) {
state.set_state_id(self.state_id);
state.set_path(self.path);
state.inner_mut().deferred_history_fingerprint =
self.deferred_history_fingerprint;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TransitionStep {
Skipped,
Finalized,
SourceComplete,
RowComplete,
Pending,
}
#[cfg(test)]
mod symbol_presence_tests {
use super::state_has_enabled_symbol;
use crate::config::DEFAULT_CANCELLATION_POLL_INTERVAL as POLL_INTERVAL;
use crate::core::{NormalizedPattern, Pattern, Symbol};
use crate::execution::matching::row_loop::state::WorkGovernor;
use crate::nfa::CompiledAutomaton;
#[test]
fn long_symbol_presence_scans_cancel_and_retry() {
let symbol_count = u64::BITS as usize - 1 + POLL_INTERVAL;
let matched_bitmap = u64::MAX << 1;
let symbols = (0..symbol_count)
.map(|index| format!("S{index}"))
.collect::<Vec<_>>();
let source = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named(
symbols
.last()
.expect("test_case should have symbols")
.clone(),
)));
let compiled = CompiledAutomaton::compile(&source, &symbols)
.expect("long symbol-scan pattern should compile");
let matched_symbols = compiled
.symbols_iter()
.map(|(id, _)| id)
.collect::<Vec<_>>();
let nfa_state = compiled.nfa().state(compiled.nfa().start_state());
let mut row_governor = WorkGovernor::default();
let error = state_has_enabled_symbol(
&compiled,
nfa_state,
matched_bitmap,
&matched_symbols,
&mut |units| row_governor.record_completed(units, || true),
)
.expect_err("long matched-symbol scan must observe cancellation");
assert!(error.to_string().contains("cancelled"), "{error}");
assert_eq!(row_governor.work_since_yield_for_test(), POLL_INTERVAL);
assert!(
state_has_enabled_symbol(
&compiled,
nfa_state,
matched_bitmap,
&matched_symbols,
&mut |units| row_governor.record_completed(units, || false),
)
.expect("matched-symbol scan should retry from local state")
);
assert_eq!(row_governor.work_since_yield_for_test(), 2 * POLL_INTERVAL);
}
}
#[cfg(test)]
mod tests {
use super::{
FinalizeTransitionRequest, TransitionKernel,
resolve_active_match_sequence_number, resolve_compact_match_sequence_number,
restore_or_discard_transition_state,
};
use super::{TransitionDisposition, TransitionSource};
use crate::config::MatchRecognizeConfig;
use crate::core::{AbsoluteRow, NormalizedPattern, Pattern, Symbol, SymbolId};
use crate::execution::common::memory::new_unbounded_state_memory;
use crate::execution::matching::DefineCachePolicy;
use crate::execution::matching::dedup::{DedupArena, OverflowIndex};
use crate::execution::matching::graph::path_nodes::PathNodeArena;
use crate::execution::matching::path::{PathStep, Sym};
use crate::execution::matching::row_loop::policies::IgnoreAnchors;
use crate::execution::matching::row_loop::predicate_decision::{
PredicateCacheProbe, TransitionDecision,
};
use crate::execution::matching::row_loop::state::WorkGovernor;
use crate::execution::matching::row_loop::transition_utils::allocate_path_node;
use crate::execution::matching::row_loop::types::ActiveNFAState;
use crate::execution::matching::row_loop::types::{
AccountedCowSlice, AccumulatorSet, ActiveThread, SharedNavigationFrame,
};
use crate::execution::matching::{PatternMatcher, build_test_matcher};
use crate::nfa::{AutomatonStateId, CompiledAutomaton};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::DataFusionError;
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
use std::cell::Cell;
use std::sync::Arc;
#[test]
fn predicate_cache_probe_respects_eligibility_and_records_hits_and_misses() {
use DefineCachePolicy::{Disabled as Off, MatchStart as Start};
use PredicateCacheProbe::{Disabled, Hit, Miss};
use TransitionDecision::Reject;
for (policy, registers_only, cached, expected, lookups) in [
(Off, false, Some(Reject), Disabled, 0),
(Start, true, Some(Reject), Disabled, 0),
(Start, false, Some(Reject), Hit(Reject), 1),
(Start, false, None, Miss, 1),
] {
let calls = Cell::new(0);
let actual = PredicateCacheProbe::probe(policy, registers_only, || {
calls.set(calls.get() + 1);
cached
});
assert_eq!(actual, expected);
assert_eq!(calls.get(), lookups);
}
}
fn state_with_owned_accumulators() -> ActiveThread {
let mut state = ActiveThread::new(
ActiveNFAState {
state_id: crate::execution::test_support::test_automaton_state_id(0),
path: None,
match_start_row: AbsoluteRow::ZERO,
registers: [0; 16],
deferred_history_fingerprint: 0,
},
Some(
AccumulatorSet::try_new(vec![None], &new_unbounded_state_memory())
.unwrap(),
),
None,
None,
None,
);
state.navigation = Some(SharedNavigationFrame(
AccountedCowSlice::try_from_slice(&[7], &new_unbounded_state_memory())
.unwrap(),
));
state
}
#[test]
fn consumed_transition_restores_source_identity_and_ownership() {
let mut active = state_with_owned_accumulators();
let source_state_id = crate::execution::test_support::test_automaton_state_id(7);
active.set_state_id(source_state_id);
active.set_path(Some(11));
active.inner_mut().match_start_row = AbsoluteRow::new(13);
active.inner_mut().deferred_history_fingerprint = 17;
let source = TransitionSource {
state_id: source_state_id,
path: Some(11),
match_start_row: AbsoluteRow::new(13),
deferred_history_fingerprint: 17,
};
let mut attempted = active.take_transition_state();
attempted
.set_state_id(crate::execution::test_support::test_automaton_state_id(9));
attempted.set_path(None);
attempted.inner_mut().deferred_history_fingerprint = 23;
restore_or_discard_transition_state(
&mut active,
attempted,
source,
TransitionDisposition::ConsumeSource,
);
assert_eq!(active.state_id(), source_state_id);
assert_eq!(active.path(), Some(11));
assert_eq!(active.match_start_row(), AbsoluteRow::new(13));
assert_eq!(active.inner().deferred_history_fingerprint, 17);
assert!(active.take_accumulators().is_some());
assert_eq!(active.navigation_words(), &[7]);
}
#[test]
fn valid_active_match_sequence_number_mappings() {
let mut arena = Vec::new();
let step = PathStep {
row: AbsoluteRow::ZERO,
sym: Sym::Empty,
excluded: false,
};
let root = allocate_path_node(step, None, &mut arena).unwrap();
let child = allocate_path_node(step, Some(root), &mut arena).unwrap();
assert_eq!(
resolve_active_match_sequence_number(
crate::execution::test_support::test_automaton_state_id(7),
None,
&[],
)
.unwrap(),
1
);
assert_eq!(
resolve_active_match_sequence_number(
crate::execution::test_support::test_automaton_state_id(7),
Some(child),
&arena,
)
.unwrap(),
3
);
assert_eq!(
resolve_compact_match_sequence_number(
AbsoluteRow::new(12),
AbsoluteRow::new(10),
)
.unwrap(),
3
);
assert!(matches!(
resolve_compact_match_sequence_number(
AbsoluteRow::new(9),
AbsoluteRow::new(10),
)
.unwrap_err(),
DataFusionError::Internal(_)
));
assert!(matches!(
resolve_compact_match_sequence_number(
AbsoluteRow::new(i64::MAX as u64),
AbsoluteRow::ZERO,
)
.unwrap_err(),
DataFusionError::ResourcesExhausted(_)
));
}
struct TransitionRollbackHarness {
compiled: Arc<CompiledAutomaton>,
matcher: PatternMatcher,
sym_id: SymbolId,
nfa_state_id: AutomatonStateId,
next_state_id: AutomatonStateId,
}
impl TransitionRollbackHarness {
fn new() -> Self {
let normalized_pattern = NormalizedPattern::Ast(Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
crate::core::RepetitionQuantifier::OneOrMore,
));
let compiled = Arc::new(
CompiledAutomaton::compile(&normalized_pattern, &["A".into()])
.expect("repeating pattern should compile"),
);
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
]));
let mut config = MatchRecognizeConfig::default();
config.diagnostics.disable_compact_paths = true;
let matcher = build_test_matcher(
Arc::clone(&schema),
normalized_pattern,
Arc::clone(&compiled),
&config,
|input| {
input.max_define_lookahead_rows = crate::core::NavigationOffset::ONE;
input.has_deferred_history_operations = true;
},
)
.expect("test matcher should build");
let sym_id = SymbolId::try_new(1, compiled.id_to_symbol().len())
.expect("symbol A should have a valid dense ID");
let (nfa_state_id, next_state_id) = compiled
.nfa()
.states()
.enumerate()
.find_map(|(state_id, state)| {
state
.transitions(sym_id)
.first()
.copied()
.map(|next_state_id| {
(
compiled
.nfa()
.state_id(state_id)
.expect("enumerated state belongs to the NFA"),
next_state_id,
)
})
})
.expect("single-symbol pattern should have one consuming transition");
assert!(!compiled.nfa().state(next_state_id).is_accepting());
assert!(
compiled.unconditional_first_accepting_state()[next_state_id.index()]
.is_some(),
"the transition destination must publish an accepting candidate before insertion"
);
Self {
compiled,
matcher,
sym_id,
nfa_state_id,
next_state_id,
}
}
}
#[test]
fn path_admission_and_finalization_errors_roll_back_owned_state() {
#[derive(Debug)]
enum FailureStage {
PathAdmission,
OverflowInsertion,
}
use FailureStage::*;
let TransitionRollbackHarness {
compiled,
matcher,
sym_id,
nfa_state_id,
next_state_id,
} = TransitionRollbackHarness::new();
assert!(
!matcher
.program
.base_variant()
.path_representation()
.uses_compact_paths()
);
for failure_stage in [PathAdmission, OverflowInsertion] {
let mut active = state_with_owned_accumulators();
active.set_state_id(nfa_state_id);
active.inner_mut().match_start_row = AbsoluteRow::new(1);
let source = TransitionSource {
state_id: nfa_state_id,
path: None,
match_start_row: active.match_start_row(),
deferred_history_fingerprint: 0,
};
let next_state = active.take_transition_state();
let navigation_words = next_state.navigation_words().to_vec();
assert!(active.navigation.is_none());
let mut destination = *next_state.inner();
destination.state_id = next_state_id;
destination.match_start_row = AbsoluteRow::ZERO;
let mut arena_next_active =
vec![ActiveThread::new(destination, None, None, None, None)];
let mut arena_primary_slots = vec![0; compiled.nfa().state_count()];
arena_primary_slots[next_state_id.index()] = 0;
let mut arena_flags = vec![0; compiled.nfa().state_count()];
arena_flags[next_state_id.index()] = 1;
let staged_before = (
format!("{arena_next_active:?}"),
arena_flags.clone(),
arena_primary_slots.clone(),
);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(0));
let mut overflow_reservation =
MemoryConsumer::new("transition-rollback-test").register(&pool);
let index_memory = new_unbounded_state_memory();
let mut overflow_index = OverflowIndex::new(&index_memory);
let path_memory = if matches!(failure_stage, PathAdmission) {
&overflow_reservation
} else {
&index_memory
};
let mut node_arena = PathNodeArena::new(path_memory);
let mut incumbent = None;
let mut governor = WorkGovernor::default();
let mut anchor_policy = IgnoreAnchors;
let (error, failed_state) = *TransitionKernel {
compiled: &compiled,
path_representation: matcher.program.base_variant().path_representation(),
node_arena: &mut node_arena,
incumbent: &mut incumbent,
}
.finalize_transition(
&matcher,
next_state,
FinalizeTransitionRequest {
nfa_state_id,
sym_id,
next_state_id,
needs_history: false,
current_row: 1,
partition_start_row: 0,
partition_len: 2,
global_row_offset: 0,
current_match_number: 1,
source,
disposition: TransitionDisposition::ConsumeSource,
},
&mut anchor_policy,
&mut DedupArena {
next_active: &mut arena_next_active,
next_primary_slot: &mut arena_primary_slots,
next_gen_flags: &mut arena_flags,
cur_row_gen: 1,
memory: &mut overflow_reservation,
overflow_index: &mut overflow_index,
},
&mut governor,
)
.expect_err(match failure_stage {
PathAdmission => "path admission must fail before publication",
OverflowInsertion => "overflow insertion must fail before publication",
});
restore_or_discard_transition_state(
&mut active,
failed_state,
source,
TransitionDisposition::ConsumeSource,
);
assert_eq!(
(
active.state_id(),
active.path(),
active.match_start_row(),
active.inner().deferred_history_fingerprint
),
(
source.state_id,
source.path,
source.match_start_row,
source.deferred_history_fingerprint
)
);
assert_eq!(active.navigation_words(), navigation_words);
assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
assert_eq!(
error.to_string().contains("path arena"),
matches!(failure_stage, PathAdmission)
);
assert!(node_arena.is_empty());
assert!(incumbent.is_none());
assert!(overflow_index.is_empty());
assert_eq!(
(
format!("{arena_next_active:?}"),
arena_flags,
arena_primary_slots
),
staged_before
);
assert_eq!(overflow_reservation.size(), 0);
assert_eq!(pool.reserved(), 0);
let restored = active.take_accumulators();
assert!(restored.is_some());
active.put_accumulators(restored);
}
}
}