use crate::core::AbsoluteRow;
use crate::core::PhysicalRowCount;
use crate::core::SymbolId;
use crate::execution::common::memory::try_reserve_accounted;
use crate::execution::common::progress::CoarseWorkBatch;
use crate::execution::matching::row_loop::lane_scan::path::LanePathCursor;
use crate::execution::matching::row_loop::lane_scan::path::LanePathPosition;
use crate::nfa::CompactPathShape;
use crate::nfa::CompactPrefixSuffixInfo;
use crate::nfa::CompiledAutomaton;
use datafusion::common::DataFusionError;
use datafusion::common::Result;
use datafusion::common::internal_err;
use datafusion::execution::memory_pool::MemoryReservation;
pub(crate) trait PathStepEquivalence {
fn equivalent_steps(&self, left: &PathStep, right: &PathStep) -> bool;
}
#[derive(Clone, Debug)]
pub(crate) enum PathRepresentation {
ArenaRequired,
ArenaForced,
CompactSingle(SymbolId),
CompactPrefixSuffix(CompactPrefixSuffixInfo),
}
impl PathRepresentation {
#[inline]
pub(crate) const fn uses_compact_paths(&self) -> bool {
matches!(self, Self::CompactSingle(_) | Self::CompactPrefixSuffix(_))
}
}
pub(crate) fn compact_path_shape_for_skip<'a>(
automaton: &'a CompiledAutomaton,
skip: &super::ResolvedAfterMatchSkip,
eligible: bool,
) -> Option<&'a CompactPathShape> {
if eligible
&& matches!(
skip,
super::ResolvedAfterMatchSkip::PastLastRow
| super::ResolvedAfterMatchSkip::ToNextRow
)
{
automaton.compact_path_shape()
} else {
None
}
}
pub(crate) fn select_path_representation(
automaton: &CompiledAutomaton,
skip: &super::ResolvedAfterMatchSkip,
eligible: bool,
disabled: bool,
) -> PathRepresentation {
match compact_path_shape_for_skip(automaton, skip, eligible) {
Some(_) if disabled => PathRepresentation::ArenaForced,
Some(CompactPathShape::Single(symbol)) => {
PathRepresentation::CompactSingle(*symbol)
}
Some(CompactPathShape::PrefixSuffix(shape)) => {
PathRepresentation::CompactPrefixSuffix(shape.clone())
}
None => PathRepresentation::ArenaRequired,
}
}
pub(crate) const MAX_USER_SYMBOLS: usize = u16::MAX as usize;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Sym {
Empty,
User(u16),
}
impl Sym {
pub(crate) const fn to_index(self) -> usize {
match self {
Self::Empty => 0,
Self::User(n) => 1 + n as usize,
}
}
pub(crate) const fn from_index(idx: usize) -> Self {
match idx {
0 => Self::Empty,
n if n <= MAX_USER_SYMBOLS => Self::User((n - 1) as u16),
_ => panic!("symbol index exceeds the supported dense symbol ID range"),
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) struct PathStep {
pub(crate) row: AbsoluteRow,
pub(crate) sym: Sym,
pub(crate) excluded: bool,
}
pub(crate) type PathNodeIndex = u32;
const COMPACT_PATH_NODE: PathNodeIndex = u32::MAX - 1;
#[inline]
pub(crate) const fn compact_path_node() -> PathNodeIndex {
COMPACT_PATH_NODE
}
#[inline]
pub(crate) const fn is_compact_path_node(index: PathNodeIndex) -> bool {
index == COMPACT_PATH_NODE
}
#[inline]
pub(crate) const fn is_reserved_path_node(index: PathNodeIndex) -> bool {
index >= COMPACT_PATH_NODE
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct PathNode {
pub(crate) step: PathStep,
pub(crate) prev: Option<PathNodeIndex>,
pub(crate) depth: u32,
}
fn path_symbol(symbol_id: SymbolId) -> Result<Sym> {
let symbol_id = symbol_id.index();
if !(1..=MAX_USER_SYMBOLS).contains(&symbol_id) {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE compact path symbol ID {symbol_id} is outside the valid user-symbol range"
)));
}
Ok(Sym::from_index(symbol_id))
}
fn path_row_count(start_row: AbsoluteRow, end_row: AbsoluteRow) -> Result<usize> {
let distance = end_row.checked_offset_from(start_row).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE compact path start {start_row} follows end {end_row}"
))
})?;
let row_count = distance.as_u64().checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact path row count exceeds u64".to_string(),
)
})?;
usize::try_from(row_count).map_err(|_| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE compact path row count {row_count} cannot be represented as usize"
))
})
}
pub(crate) fn checked_path_node(
arena: &[PathNode],
index: PathNodeIndex,
) -> Result<&PathNode> {
if is_reserved_path_node(index) {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE path node index {index} is reserved"
)));
}
let index = usize::try_from(index).map_err(|_| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE path node index {index} exceeds usize"
))
})?;
arena.get(index).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE path node index {index} is outside an arena of length {}",
arena.len()
))
})
}
pub(crate) struct ArenaPathCursor {
current: Option<PathNodeIndex>,
expected_depth: u32,
len: usize,
}
impl ArenaPathCursor {
pub(crate) fn try_new(arena: &[PathNode], current: PathNodeIndex) -> Result<Self> {
let first_depth = checked_path_node(arena, current)?.depth;
let chain_len = usize::try_from(first_depth)
.ok()
.and_then(|depth| depth.checked_add(1))
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE path depth {first_depth} exceeds usize"
))
})?;
if chain_len > arena.len() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE path depth {first_depth} cannot fit an arena of length {}",
arena.len()
)));
}
Ok(Self {
current: Some(current),
expected_depth: first_depth,
len: chain_len,
})
}
pub(crate) const fn len(&self) -> usize {
self.len
}
pub(crate) fn try_next(&mut self, arena: &[PathNode]) -> Result<Option<PathStep>> {
let Some(current_idx) = self.current else {
return Ok(None);
};
let expected_depth = self.expected_depth;
let node = checked_path_node(arena, current_idx)?;
if node.depth != expected_depth {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE path node {current_idx} has depth {}, expected {expected_depth}; the chain is malformed or cyclic",
node.depth
)));
}
match node.prev {
Some(prev) => {
if prev >= current_idx {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE path node {current_idx} points to non-older predecessor {prev}; the chain is malformed or cyclic"
)));
}
self.expected_depth = expected_depth.checked_sub(1).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE root path node {current_idx} has a predecessor; the chain is malformed or cyclic"
))
})?;
self.current = Some(prev);
}
None => {
if expected_depth != 0 {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE path node {current_idx} terminates at nonzero depth {expected_depth}"
)));
}
self.current = None;
}
}
Ok(Some(node.step))
}
}
pub(crate) struct CompactPathCursor {
start: AbsoluteRow,
len: usize,
offset: usize,
segment: usize,
segment_offset: usize,
middle_rows: usize,
}
impl CompactPathCursor {
pub(crate) fn try_single(start: AbsoluteRow, end: AbsoluteRow) -> Result<Self> {
let len = path_row_count(start, end)?;
Ok(Self {
start,
len,
offset: 0,
segment: 0,
segment_offset: 0,
middle_rows: len,
})
}
pub(crate) fn try_prefix_suffix(
shape: &CompactPrefixSuffixInfo,
start_row: AbsoluteRow,
end_row: AbsoluteRow,
) -> Result<Self> {
let mut cursor = Self::try_single(start_row, end_row)?;
let fixed_rows = shape
.prefix_rows()
.checked_add(shape.suffix_rows())
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact prefix/suffix row count overflow"
.to_string(),
)
})?;
let middle_rows = cursor.len.checked_sub(fixed_rows).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE compact prefix/suffix uses {fixed_rows} fixed rows for a {}-row match", cursor.len
))
})?;
if middle_rows < shape.middle_min_rows() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE compact prefix/suffix reconstructed {middle_rows} middle rows below its minimum {}",
shape.middle_min_rows()
)));
}
cursor.middle_rows = middle_rows;
Ok(cursor)
}
pub(crate) const fn len(&self) -> usize {
self.len
}
pub(crate) fn try_next(
&mut self,
prefix: &[(SymbolId, usize)],
middle: SymbolId,
suffix: &[(SymbolId, usize)],
) -> Result<Option<PathStep>> {
if self.offset == self.len {
return Ok(None);
}
loop {
let (symbol, count) = if self.segment < prefix.len() {
prefix[self.segment]
} else if self.segment == prefix.len() {
(middle, self.middle_rows)
} else {
*suffix.get(self.segment - prefix.len() - 1).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE compact path ended before its extent".into(),
)
})?
};
if self.segment_offset == count {
self.segment += 1;
self.segment_offset = 0;
continue;
}
let row = self
.start
.as_u64()
.checked_add(self.offset as u64)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact path row exceeds u64".into(),
)
})?;
let step = PathStep {
row: AbsoluteRow::new(row),
sym: path_symbol(symbol)?,
excluded: false,
};
self.offset += 1;
self.segment_offset += 1;
return Ok(Some(step));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{NormalizedPattern, Pattern, RepetitionQuantifier, Symbol};
fn prefix_suffix_shape(
prefix_rows: usize,
middle_min_rows: u32,
suffix_rows: usize,
) -> CompactPrefixSuffixInfo {
let symbol = |name: &str| Pattern::Symbol(Symbol::Named(name.into()));
let mut elements = vec![symbol("A"); prefix_rows];
elements.push(Pattern::Repetition(
Box::new(symbol("B")),
RepetitionQuantifier::AtLeast(middle_min_rows),
));
elements.extend(vec![symbol("C"); suffix_rows]);
let compiled = CompiledAutomaton::compile(
&NormalizedPattern::Ast(Pattern::Concat(elements)),
&["A".into(), "B".into(), "C".into()],
)
.unwrap();
let Some(CompactPathShape::PrefixSuffix(shape)) = compiled.compact_path_shape()
else {
panic!("expected compiled prefix/suffix metadata");
};
shape.clone()
}
fn symbol_id(index: usize) -> SymbolId {
SymbolId::try_new(index, index + 1).expect("test symbols are non-empty")
}
fn path_node(row: u64, prev: Option<PathNodeIndex>, depth: u32) -> PathNode {
PathNode {
step: PathStep {
row: AbsoluteRow::new(row),
sym: Sym::User(0),
excluded: false,
},
prev,
depth,
}
}
#[test]
fn arena_cursor_walks_from_tip_to_root_and_stays_exhausted() {
let arena = [path_node(10, None, 0), path_node(11, Some(0), 1)];
let mut cursor = ArenaPathCursor::try_new(&arena, 1).unwrap();
assert_eq!(cursor.len(), 2);
assert_eq!(cursor.try_next(&arena).unwrap(), Some(arena[1].step));
assert_eq!(cursor.try_next(&arena).unwrap(), Some(arena[0].step));
assert_eq!(cursor.try_next(&arena).unwrap(), None);
assert_eq!(cursor.try_next(&arena).unwrap(), None);
}
#[test]
fn arena_cursor_rejects_invalid_tips_and_malformed_chains() {
let root = path_node(10, None, 0);
for (arena, tip, diagnostic) in [
(vec![root], 1, "outside an arena"),
(vec![root], compact_path_node(), "reserved"),
(vec![root], u32::MAX, "reserved"),
(vec![path_node(10, Some(0), 0)], 0, "non-older predecessor"),
(
vec![path_node(10, Some(1), 1), root],
0,
"non-older predecessor",
),
(vec![path_node(10, None, 1), root], 0, "nonzero depth"),
(
vec![path_node(10, None, 1), path_node(11, Some(0), 1)],
1,
"expected 0",
),
(vec![path_node(10, None, 2), root], 0, "cannot fit an arena"),
] {
let result = (|| {
let mut cursor = ArenaPathCursor::try_new(&arena, tip)?;
while cursor.try_next(&arena)?.is_some() {}
Ok::<(), DataFusionError>(())
})();
let error = result.expect_err(diagnostic);
assert!(matches!(error, DataFusionError::Internal(_)), "{error}");
assert!(error.to_string().contains(diagnostic), "{error}");
}
}
#[test]
fn compact_cursor_preserves_wide_rows_and_maximum_symbol() {
let origin = AbsoluteRow::new(u64::from(u32::MAX) + 10_000);
let mut cursor =
CompactPathCursor::try_single(origin, AbsoluteRow::new(origin.as_u64() + 2))
.unwrap();
assert_eq!(cursor.len(), 3);
for offset in 0..3 {
let step = cursor
.try_next(&[], symbol_id(MAX_USER_SYMBOLS), &[])
.unwrap()
.unwrap();
assert_eq!(step.row, AbsoluteRow::new(origin.as_u64() + offset));
assert_eq!(step.sym.to_index(), MAX_USER_SYMBOLS);
}
assert_eq!(cursor.try_next(&[], symbol_id(1), &[]).unwrap(), None);
}
#[test]
fn compact_cursor_checks_extent_and_symbol_boundaries() {
let reversed =
CompactPathCursor::try_single(AbsoluteRow::new(10), AbsoluteRow::new(9))
.err()
.expect("reversed extent");
assert!(matches!(reversed, DataFusionError::Internal(_)));
let overflowing =
CompactPathCursor::try_single(AbsoluteRow::ZERO, AbsoluteRow::MAX)
.err()
.expect("inclusive row count exceeds u64");
assert!(matches!(
overflowing,
DataFusionError::ResourcesExhausted(_)
));
let mut cursor =
CompactPathCursor::try_single(AbsoluteRow::MAX, AbsoluteRow::MAX).unwrap();
assert_eq!(cursor.len(), 1);
let error = cursor
.try_next(&[], symbol_id(MAX_USER_SYMBOLS + 1), &[])
.expect_err("oversized symbols must return an error rather than panic");
assert!(matches!(error, DataFusionError::Internal(_)));
assert_eq!(
cursor
.try_next(&[], symbol_id(1), &[])
.unwrap()
.unwrap()
.row,
AbsoluteRow::MAX,
);
assert_eq!(cursor.try_next(&[], symbol_id(1), &[]).unwrap(), None);
}
#[test]
fn segmented_cursor_preserves_wide_rows_and_symbol_order() {
let shape = prefix_suffix_shape(1, 1, 1);
let origin = AbsoluteRow::new(u64::from(u32::MAX) + 20_000);
let mut cursor = CompactPathCursor::try_prefix_suffix(
&shape,
origin,
AbsoluteRow::new(origin.as_u64() + 3),
)
.unwrap();
assert_eq!(cursor.len(), 4);
for (offset, symbol) in [(0, 1), (1, 2), (2, 2), (3, 3)] {
let step = cursor
.try_next(shape.prefix(), shape.middle_symbol(), shape.suffix())
.unwrap()
.unwrap();
assert_eq!(step.row, AbsoluteRow::new(origin.as_u64() + offset));
assert_eq!(step.sym.to_index(), symbol);
}
assert_eq!(
cursor
.try_next(shape.prefix(), shape.middle_symbol(), shape.suffix())
.unwrap(),
None,
);
}
#[test]
fn segmented_cursor_requires_fixed_rows_and_compiled_middle_minimum() {
for (prefix, middle_min, suffix, last_row, expected) in [
(2, 1, 1, 11, None), (1, 2, 1, 12, None), (1, 2, 1, 13, Some(&[1, 2, 2, 3][..])), (1, 0, 1, 11, Some(&[1, 3][..])), ] {
let shape = prefix_suffix_shape(prefix, middle_min, suffix);
let result = CompactPathCursor::try_prefix_suffix(
&shape,
AbsoluteRow::new(10),
AbsoluteRow::new(last_row),
);
match result {
Ok(mut cursor) => {
let expected = expected.expect("invalid shape/extent must fail");
let mut symbols = Vec::new();
while let Some(step) = cursor
.try_next(shape.prefix(), shape.middle_symbol(), shape.suffix())
.unwrap()
{
symbols.push(step.sym.to_index());
}
assert_eq!(symbols, expected);
}
Err(error) => {
assert!(expected.is_none(), "{error}");
assert!(matches!(error, DataFusionError::Internal(_)));
}
}
}
}
}
enum SelectedStepCursor {
Arena(ArenaPathCursor),
Compact(CompactPathCursor),
Lane(LanePathPosition),
}
#[derive(Default)]
pub(crate) struct SelectedStepSources<'a> {
pub(crate) arena: &'a [PathNode],
pub(crate) shape: Option<&'a PathRepresentation>,
pub(crate) lane: Option<LanePathCursor<'a>>,
}
pub(crate) struct SelectedSteps {
cursor: SelectedStepCursor,
steps: Vec<PathStep>,
len: usize,
filled: usize,
complete: bool,
}
impl SelectedSteps {
fn new(cursor: SelectedStepCursor, len: usize) -> Self {
Self {
cursor,
steps: Vec::new(),
len,
filled: 0,
complete: false,
}
}
pub(crate) fn arena(nodes: &[PathNode], tip: PathNodeIndex) -> Result<Self> {
let cursor = ArenaPathCursor::try_new(nodes, tip)?;
let len = cursor.len();
Ok(Self::new(SelectedStepCursor::Arena(cursor), len))
}
pub(crate) fn compact(
shape: &PathRepresentation,
start: AbsoluteRow,
end: AbsoluteRow,
) -> Result<Self> {
let cursor = match shape {
PathRepresentation::CompactSingle(_) => {
CompactPathCursor::try_single(start, end)?
}
PathRepresentation::CompactPrefixSuffix(shape) => {
CompactPathCursor::try_prefix_suffix(shape, start, end)?
}
_ => {
return internal_err!(
"selected compact path lost its reconstruction shape"
);
}
};
let len = cursor.len();
Ok(Self::new(SelectedStepCursor::Compact(cursor), len))
}
pub(crate) fn lane(len: PhysicalRowCount) -> Result<Self> {
let len = usize::try_from(len.as_u64()).map_err(|_| {
DataFusionError::ResourcesExhausted("selected Lane path exceeds usize".into())
})?;
Ok(Self::new(
SelectedStepCursor::Lane(LanePathPosition::default()),
len,
))
}
pub(crate) fn empty_position(
&self,
arena: &[PathNode],
) -> Result<Option<AbsoluteRow>> {
let step = match &self.cursor {
SelectedStepCursor::Arena(cursor) if cursor.len == 1 => {
checked_path_node(arena, cursor.current.expect("unconsumed path"))?.step
}
_ => return Ok(None),
};
Ok(matches!(step.sym, Sym::Empty).then_some(step.row))
}
pub(crate) fn reserve(
&mut self,
mut reuse: Vec<PathStep>,
memory: &mut MemoryReservation,
) -> Result<()> {
if self.filled != 0 {
return internal_err!("cannot replace a partially initialized selected path");
}
reuse.clear();
try_reserve_accounted(&mut reuse, memory, self.len, "selected output path")?;
self.steps = reuse;
Ok(())
}
pub(crate) fn in_reverse(&self) -> bool {
matches!(self.cursor, SelectedStepCursor::Arena(_))
}
pub(crate) fn uses_lane(&self) -> bool {
matches!(self.cursor, SelectedStepCursor::Lane(_))
}
#[inline]
pub(crate) fn advance(
&mut self,
mut source: SelectedStepSources<'_>,
limit: usize,
observe: &mut impl FnMut(PathStep) -> Result<()>,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
if self.complete {
return Ok(true);
}
if self.steps.capacity() < self.len {
return internal_err!("selected output path was not reserved");
}
if let SelectedStepCursor::Lane(position) = &self.cursor {
source
.lane
.as_mut()
.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"selected Lane lost its cursor"
)
})?
.resume_at(*position);
}
let end = self.filled.saturating_add(limit).min(self.len);
let mut work = CoarseWorkBatch::new(completed);
while self.filled < end {
let step = match &mut self.cursor {
SelectedStepCursor::Arena(cursor) => cursor.try_next(source.arena)?,
SelectedStepCursor::Compact(cursor) => match source.shape {
Some(PathRepresentation::CompactSingle(symbol)) => {
cursor.try_next(&[], *symbol, &[])?
}
Some(PathRepresentation::CompactPrefixSuffix(shape)) => cursor
.try_next(
shape.prefix(),
shape.middle_symbol(),
shape.suffix(),
)?,
_ => {
return internal_err!(
"selected compact path lost its reconstruction shape"
);
}
},
SelectedStepCursor::Lane(_) => source
.lane
.as_mut()
.expect("cursor bound above")
.try_next()?,
}
.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"selected path ended before its declared length"
)
})?;
observe(step)?;
if self.in_reverse() {
self.steps.spare_capacity_mut()[self.len - self.filled - 1].write(step);
} else {
self.steps.push(step);
}
self.filled += 1;
work.complete_one()?;
}
work.finish()?;
if let SelectedStepCursor::Lane(position) = &mut self.cursor {
let cursor = source.lane.as_mut().expect("cursor bound above");
if self.filled == self.len && cursor.try_next()?.is_some() {
return internal_err!("selected Lane exceeds its declared path length");
}
*position = cursor.position();
}
self.complete = self.filled == self.len;
Ok(self.complete)
}
pub(crate) fn finish(mut self) -> Result<Vec<PathStep>> {
if !self.complete {
return internal_err!("published incomplete selected path");
}
if self.in_reverse() {
unsafe {
self.steps.set_len(self.len);
}
}
Ok(self.steps)
}
}