use super::{LaneScanProgram, SymbolFacts, path::LanePathRun};
use crate::core::{AbsoluteRow, PhysicalRowCount, SymbolId};
use crate::execution::matching::ResolvedAfterMatchSkip;
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionEdge;
use datafusion_common::{DataFusionError, Result};
mod captures;
pub(crate) use captures::{ClassifierDemand, SymbolCaptures};
pub(crate) struct LaneSelectedRuns<'a> {
graph: &'a LaneScanProgram,
pub(crate) runs: &'a [LanePathRun],
}
pub(crate) struct CompactSelection<'a> {
pub(crate) runs: Option<LaneSelectedRuns<'a>>,
captures: Option<&'a SymbolCaptures>,
pub(crate) start: AbsoluteRow,
pub(crate) end: AbsoluteRow,
pub(crate) acceptance: AbsoluteRow,
pub(crate) expected_steps: PhysicalRowCount,
}
impl<'a> CompactSelection<'a> {
pub(crate) fn try_new(
graph: &'a LaneScanProgram,
runs: &'a [LanePathRun],
start: AbsoluteRow,
end: AbsoluteRow,
acceptance: AbsoluteRow,
) -> Result<Self> {
Self::try_new_with_captures(graph, runs, None, start, end, acceptance)
}
pub(crate) fn try_new_with_captures(
graph: &'a LaneScanProgram,
runs: &'a [LanePathRun],
captures: Option<&'a SymbolCaptures>,
start: AbsoluteRow,
end: AbsoluteRow,
acceptance: AbsoluteRow,
) -> Result<Self> {
let mut selection = Self::checked_extent(start, end, acceptance, captures)?;
if runs.first().map(|run| run.first_row()) != Some(start)
|| runs
.last()
.and_then(|run| run.first_row().checked_add(run.steps()))
!= end.checked_add(PhysicalRowCount::new(1))
{
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE compact selected runs disagree with the selected extent"
);
}
selection.runs = Some(LaneSelectedRuns { graph, runs });
Ok(selection)
}
#[inline]
pub(crate) fn from_extent(
start: AbsoluteRow,
end: AbsoluteRow,
acceptance: AbsoluteRow,
) -> Result<Self> {
Self::checked_extent(start, end, acceptance, None)
}
#[inline]
pub(in crate::execution::matching) fn from_captures(
start: AbsoluteRow,
end: AbsoluteRow,
acceptance: AbsoluteRow,
captures: &'a SymbolCaptures,
) -> Result<Self> {
Self::checked_extent(start, end, acceptance, Some(captures))
}
#[cfg(test)]
pub(crate) fn with_captures(mut self, captures: &'a SymbolCaptures) -> Self {
self.captures = Some(captures);
self
}
#[inline]
fn checked_extent(
start: AbsoluteRow,
end: AbsoluteRow,
acceptance: AbsoluteRow,
captures: Option<&'a SymbolCaptures>,
) -> Result<Self> {
let after_end = end.as_u64().checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact path end exceeds u64".into(),
)
})?;
let expected_steps = after_end
.checked_sub(start.as_u64())
.filter(|&length| length != 0 && end <= acceptance)
.map(PhysicalRowCount::new)
.ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE compact match has invalid bounds".into(),
)
})?;
Ok(Self {
start,
end,
acceptance,
expected_steps,
runs: None,
captures,
})
}
pub(crate) fn symbol_facts(&self, symbol: Option<SymbolId>) -> Option<SymbolFacts> {
match symbol {
Some(id) => self.captures?.at_winner(id),
None => Some(SymbolFacts {
first: self.start,
last: self.end,
count: self.expected_steps.as_u64(),
}),
}
}
pub(crate) fn history(&self) -> Result<&LaneSelectedRuns<'a>> {
self.runs.as_ref().ok_or_else(|| datafusion_common::internal_datafusion_err!(
"MATCH_RECOGNIZE selected output requires an unretained classifier history"
))
}
pub(crate) fn can_skip_atomically(
&self,
skip: &ResolvedAfterMatchSkip,
) -> Result<bool> {
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
let symbol = match skip {
ResolvedAfterMatchSkip::ToFirst { symbol_id, .. }
| ResolvedAfterMatchSkip::ToLast { symbol_id, .. } => *symbol_id,
_ => return Ok(true),
};
if self.symbol_facts(Some(symbol)).is_some() {
return Ok(true);
}
let selected = self.history()?;
let mut remaining = COARSE_WORK_BATCH_SIZE as u64;
for (index, run) in selected.runs.iter().enumerate() {
let (_, period) = selected.edge_and_period(index, 0)?;
let Some(rest) = remaining.checked_sub(period.min(run.steps().as_u64()))
else {
return Ok(false);
};
remaining = rest;
}
Ok(true)
}
pub(crate) fn skip_target_row(
&self,
skip: &ResolvedAfterMatchSkip,
) -> Result<(Option<AbsoluteRow>, usize)> {
let (symbol_id, last) = match skip {
ResolvedAfterMatchSkip::PastLastRow | ResolvedAfterMatchSkip::ToNextRow => {
return Ok((None, 0));
}
ResolvedAfterMatchSkip::ToFirst { symbol_id, .. } => (*symbol_id, false),
ResolvedAfterMatchSkip::ToLast { symbol_id, .. } => (*symbol_id, true),
};
if let Some(facts) = self.symbol_facts(Some(symbol_id)) {
let target =
(facts.count != 0).then_some(if last { facts.last } else { facts.first });
return Ok((target, 1));
}
let selected = self.history()?;
let mut checked = 0usize;
for run_position in 0..selected.runs.len() {
let index = if last {
selected.runs.len() - 1 - run_position
} else {
run_position
};
let run = selected.runs[index];
let steps = run.steps().as_u64();
let mut word_position = 0u64;
loop {
let offset = if last {
steps.checked_sub(word_position + 1).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE selected lane run is empty".into(),
)
})?
} else {
word_position
};
let (edge, period) = selected.edge_and_period(index, offset)?;
checked += 1;
if edge.symbol_id == symbol_id {
let row = run
.first_row()
.checked_add(PhysicalRowCount::new(offset))
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE skip target row exceeds u64".into(),
)
})?;
return Ok((Some(row), checked));
}
word_position += 1;
if word_position == period.min(steps) {
break;
}
}
}
Ok((None, checked))
}
}
impl<'a> LaneSelectedRuns<'a> {
pub(crate) const MAX_ATOMIC_RUNS: usize = 64;
pub(crate) fn edge_and_period(
&self,
run_index: usize,
offset: u64,
) -> Result<(OrderedTransitionEdge, u64)> {
self.run(run_index)?.edge_and_period(self.graph, offset)
}
fn run(&self, run_index: usize) -> Result<&LanePathRun> {
self.runs.get(run_index).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE selected lane run index is out of bounds".into(),
)
})
}
}