use crate::core::{AbsoluteRow, PhysicalRowCount};
use crate::execution::matching::path::{PathStep, Sym};
use datafusion_common::{DataFusionError, Result};
use super::LaneScanProgram;
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionEdge;
fn invalid(message: &'static str) -> DataFusionError {
DataFusionError::Internal(format!("MATCH_RECOGNIZE {message}"))
}
fn exhausted(message: &'static str) -> DataFusionError {
DataFusionError::ResourcesExhausted(format!("MATCH_RECOGNIZE {message}"))
}
pub(crate) fn periodic_phase(start: u32, offset: u64, len: u32) -> Result<usize> {
if len == 0 || start >= len {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE lane cycle phase {start} is outside length {len}"
)));
}
if len == 1 {
return Ok(0);
}
let len = u64::from(len);
let phase = u64::from(start) + offset % len;
let phase = if phase >= len { phase - len } else { phase };
Ok(phase as usize)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LanePathBlock {
Edge(u32),
Cycle(u32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LanePathRun {
block: LanePathBlock,
start_phase: u32,
steps: PhysicalRowCount,
first_row: AbsoluteRow,
}
impl LanePathRun {
pub(crate) const EMPTY: Self = Self {
block: LanePathBlock::Edge(0),
start_phase: 0,
steps: PhysicalRowCount::ZERO,
first_row: AbsoluteRow::ZERO,
};
pub(crate) const fn steps(self) -> PhysicalRowCount {
self.steps
}
pub(crate) const fn first_row(self) -> AbsoluteRow {
self.first_row
}
pub(super) fn edge_and_period(
&self,
graph: &LaneScanProgram,
offset: u64,
) -> Result<(OrderedTransitionEdge, u64)> {
if offset >= self.steps.as_u64() {
return Err(invalid("lane cursor outside run"));
}
let (id, period) = match self.block {
LanePathBlock::Edge(id) => (id, 1),
LanePathBlock::Cycle(cycle) => {
let word = &graph.cycles[cycle as usize];
let phase = periodic_phase(self.start_phase, offset, word.len() as u32)?;
(word[phase], word.len() as u64)
}
};
Ok((graph.transitions.sealed_edge(id as usize), period))
}
pub(crate) fn repeated_edge(
edge_id: usize,
row: AbsoluteRow,
steps: PhysicalRowCount,
) -> Self {
debug_assert!(u32::try_from(edge_id).is_ok() && steps.as_u64() != 0);
Self {
block: LanePathBlock::Edge(edge_id as u32),
start_phase: 0,
steps,
first_row: row,
}
}
pub(crate) fn extend_repeated_edge(
&mut self,
edge_id: usize,
first: AbsoluteRow,
steps: PhysicalRowCount,
) -> Result<bool> {
if self.steps.as_u64() == 0 || self.block != LanePathBlock::Edge(edge_id as u32) {
return Ok(false);
}
let next = self
.first_row
.checked_add(self.steps)
.ok_or_else(|| exhausted("direct run exceeds row coordinates"))?;
if first != next || steps.as_u64() == 0 {
return Err(invalid("non-contiguous direct run"));
}
let total = self
.steps
.checked_add(steps)
.ok_or_else(|| exhausted("direct run exceeds u64"))?;
self.first_row
.checked_add(total)
.ok_or_else(|| exhausted("direct run exceeds row coordinates"))?;
self.steps = total;
Ok(true)
}
pub(crate) fn edge(edge_id: usize, row: AbsoluteRow) -> Self {
debug_assert!(u32::try_from(edge_id).is_ok());
Self {
block: LanePathBlock::Edge(edge_id as u32),
start_phase: 0,
steps: PhysicalRowCount::new(1),
first_row: row,
}
}
pub(crate) const fn cycle(cycle_id: u32, start_phase: u32, row: AbsoluteRow) -> Self {
Self::cycle_steps(cycle_id, start_phase, row, PhysicalRowCount::new(1))
}
pub(crate) const fn cycle_steps(
cycle_id: u32,
start_phase: u32,
row: AbsoluteRow,
steps: PhysicalRowCount,
) -> Self {
Self {
block: LanePathBlock::Cycle(cycle_id),
start_phase,
steps,
first_row: row,
}
}
pub(crate) fn try_extend_cycle(
&mut self,
program: &LaneScanProgram,
edge_id: usize,
row: AbsoluteRow,
steps: PhysicalRowCount,
) -> Result<bool> {
let LanePathBlock::Cycle(cycle_id) = self.block else {
return Ok(false);
};
let word = &program.cycles[cycle_id as usize];
if steps.as_u64() != 1 && word.len() != 1 {
return Ok(false);
}
let phase =
periodic_phase(self.start_phase, self.steps.as_u64(), word.len() as u32)?;
if word[phase] as usize != edge_id {
return Ok(false);
}
let expected_row = self
.first_row
.checked_add(self.steps)
.ok_or_else(|| exhausted("lane history row exceeds u64"))?;
if expected_row != row {
return Err(invalid("non-contiguous lane cycle"));
}
self.steps = self
.steps
.checked_add(steps)
.ok_or_else(|| exhausted("lane run exceeds u64"))?;
Ok(true)
}
}
pub(crate) struct LanePathCursor<'a> {
program: &'a LaneScanProgram,
runs: &'a [LanePathRun],
run_index: usize,
step_offset: u64,
}
#[derive(Clone, Copy, Default)]
pub(crate) struct LanePathPosition {
run_index: usize,
step_offset: u64,
}
impl<'a> LanePathCursor<'a> {
pub(crate) fn resume_at(&mut self, position: LanePathPosition) {
self.run_index = position.run_index;
self.step_offset = position.step_offset;
}
pub(crate) const fn position(&self) -> LanePathPosition {
LanePathPosition {
run_index: self.run_index,
step_offset: self.step_offset,
}
}
pub(crate) const fn new(
program: &'a LaneScanProgram,
runs: &'a [LanePathRun],
) -> Self {
Self {
program,
runs,
run_index: 0,
step_offset: 0,
}
}
pub(crate) fn try_next(&mut self) -> Result<Option<PathStep>> {
let Some(run) = self.runs.get(self.run_index) else {
return Ok(None);
};
let (edge, _) = run.edge_and_period(self.program, self.step_offset)?;
let row = run
.first_row
.checked_add(PhysicalRowCount::new(self.step_offset))
.ok_or_else(|| exhausted("lane path row exceeds u64"))?;
let step = PathStep {
row,
sym: Sym::from_index(edge.symbol_id.index()),
excluded: edge.excluded,
};
self.step_offset += 1;
if self.step_offset == run.steps.as_u64() {
self.run_index += 1;
self.step_offset = 0;
}
Ok(Some(step))
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::core::{
NormalizedPattern, Pattern, RepetitionQuantifier, Symbol, SymbolId,
};
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionTable;
use crate::execution::matching::row_loop::lane_scan::{LaneCapacity, graph};
use crate::nfa::CompiledAutomaton;
use std::sync::Arc;
pub(crate) fn repeated_pair_graph() -> LaneScanProgram {
let compiled = CompiledAutomaton::compile(
&NormalizedPattern::Ast(Pattern::Repetition(
Box::new(Pattern::Concat(vec![
Pattern::Symbol(Symbol::Named("A".into())),
Pattern::Symbol(Symbol::Named("B".into())),
])),
RepetitionQuantifier::OneOrMore,
)),
&["A".into(), "B".into()],
)
.unwrap();
let transitions = Arc::new(
OrderedTransitionTable::try_new(
&compiled,
&[
SymbolId::try_new(1, compiled.num_symbols()).unwrap(),
SymbolId::try_new(2, compiled.num_symbols()).unwrap(),
],
)
.unwrap(),
);
let layout = graph::analyze_graph(&compiled, &transitions)
.unwrap()
.unwrap();
assert_eq!(layout.cycle_words.len(), 1);
LaneScanProgram {
initial_registers: [0; crate::core::vm::MAX_REGISTERS],
register_words: 0,
navigation_layout: None,
navigation_words: 0,
payload_symbols: 0,
idempotent_last_symbols: 0,
suffix_reuse: None,
direct_linear: false,
state_meta: Box::new([]),
direct_edges: Box::new([]),
direct_payload_work: 0,
transitions,
closure_accepting: Arc::clone(compiled.unconditional_first_accepting_state()),
boundary_anchors: super::super::LaneBoundaryAnchors::None,
cycle_positions: layout.cycle_positions.into(),
cycles: layout.cycle_words.into(),
optimistic_history: false,
capacity: LaneCapacity {
live_lanes: 0,
path_runs_per_lane: 0,
encoded_program_bytes: 0,
source_payload_floor_bytes: 0,
scan_resource_bytes: 0,
},
}
}
#[test]
fn edge_runs_reject_empty_and_out_of_range_offsets() -> Result<()> {
let graph = repeated_pair_graph();
let edge = graph
.transitions
.sealed_range(graph.transitions.start_state())
.next()
.unwrap();
let mut empty = LanePathRun::EMPTY;
assert!(!empty.extend_repeated_edge(
0,
AbsoluteRow::ZERO,
PhysicalRowCount::new(1)
)?);
assert!(empty.edge_and_period(&graph, 0).is_err());
let mut run = LanePathRun::edge(edge, AbsoluteRow::new(7));
assert!(run.extend_repeated_edge(
edge,
AbsoluteRow::new(8),
PhysicalRowCount::new(2)
)?);
let runs = [run];
let mut cursor = LanePathCursor::new(&graph, &runs);
for row in 7..10 {
assert_eq!(cursor.try_next()?.unwrap().row, AbsoluteRow::new(row));
}
assert!(cursor.try_next()?.is_none());
assert!(run.edge_and_period(&graph, 3).is_err());
assert!(run.edge_and_period(&graph, u64::MAX).is_err());
Ok(())
}
#[test]
fn lane_history_rejects_gaps_before_selected_publication() {
use crate::execution::common::memory::new_unbounded_state_memory;
use crate::execution::matching::row_loop::lane_scan::{
CompactSelection, LaneState, state::LaneScanState,
};
let origin = AbsoluteRow::new(7);
let next = AbsoluteRow::new(8);
let gap = AbsoluteRow::new(9);
for disable_cycles in [false, true] {
let mut graph = repeated_pair_graph();
if disable_cycles {
graph.cycle_positions.fill(u64::MAX);
}
graph.capacity.live_lanes = 1;
graph.capacity.path_runs_per_lane = 3;
graph.capacity.scan_resource_bytes =
4 * (size_of::<LaneState>() + 3 * size_of::<LanePathRun>());
let graph = Arc::new(graph);
let start = graph.transitions.start_state();
let first = graph.transitions.sealed_range(start).next().unwrap();
let second_state = graph.transitions.sealed_edge(first).next_state_id;
let second = graph.transitions.sealed_range(second_state).next().unwrap();
let mut lane =
LaneScanState::try_new(Arc::clone(&graph), &new_unbounded_state_memory())
.unwrap();
lane.start_candidate(origin);
lane.prepare_transition(0, false).unwrap();
assert!(lane.apply_scratch_transition(start, first, next).is_err());
lane.apply_scratch_transition(start, first, origin).unwrap();
assert!(
lane.apply_scratch_transition(second_state, second, gap)
.is_err()
);
lane.apply_scratch_transition(second_state, second, next)
.unwrap();
let runs = [
LanePathRun::edge(first, origin),
LanePathRun::edge(second, next),
];
assert!(CompactSelection::try_new(&graph, &runs, origin, next, gap).is_ok());
assert!(CompactSelection::try_new(&graph, &runs, next, next, gap).is_err());
assert!(CompactSelection::try_new(&graph, &runs, origin, gap, gap).is_err());
assert!(
CompactSelection::try_new(&graph, &runs, origin, next, origin).is_err()
);
}
}
#[test]
fn cycle_phase_wraps_without_narrowing_large_offsets() {
for len in [1, 2, 3, 17, u32::MAX] {
for start in [0, len - 1] {
for offset in [
0,
1,
u64::from(len) - 1,
u64::from(len),
u64::from(len) + 1,
u64::MAX - 1,
u64::MAX,
] {
let expected =
(u128::from(start) + u128::from(offset)) % u128::from(len);
assert_eq!(
periodic_phase(start, offset, len).unwrap(),
expected as usize,
"start={start}, offset={offset}, len={len}"
);
}
}
}
for (start, len) in [(0, 0), (1, 1), (2, 2), (u32::MAX, u32::MAX)] {
assert!(periodic_phase(start, u64::MAX, len).is_err());
}
}
}