use super::LaneState;
use super::ir::LaneScanProgram;
use super::path::LanePathCursor;
use super::path::LanePathRun;
use crate::core::AbsoluteRow;
use crate::core::PhysicalRowCount;
use crate::execution::matching::graph::fallible_vec::filled;
use crate::execution::matching::path::compact_path_node;
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use crate::execution::matching::selection::AcceptingCandidate;
use crate::execution::matching::selection::BestMatch;
use crate::nfa::AutomatonStateId;
use datafusion_common::DataFusionError;
use datafusion_common::Result;
use datafusion_execution::memory_pool::MemoryReservation;
use std::sync::Arc;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum DirectScan {
Ready,
Running,
Disabled,
}
#[cfg(test)]
mod tests;
#[derive(Debug)]
pub(crate) struct LaneCapacityMiss {
detail: &'static str,
}
impl std::fmt::Display for LaneCapacityMiss {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "MATCH_RECOGNIZE {}", self.detail)
}
}
impl std::error::Error for LaneCapacityMiss {}
pub(crate) fn is_lane_capacity_miss(error: &DataFusionError) -> bool {
matches!(error, DataFusionError::External(error) if error.is::<LaneCapacityMiss>())
}
fn capacity_error(detail: &'static str) -> DataFusionError {
DataFusionError::External(Box::new(LaneCapacityMiss { detail }))
}
pub(crate) struct LaneScanState {
pub(crate) program: Arc<LaneScanProgram>,
pub(super) direct: DirectScan,
registers: Box<[u64]>,
navigation: Box<[u64]>,
register_words: usize,
navigation_words: usize,
pub(crate) lanes: Box<[LaneState]>,
pub(crate) histories: Box<[LanePathRun]>,
_memory: MemoryReservation,
runtime_memory: Option<Arc<MemoryReservation>>,
pub(crate) candidate_start: Option<AbsoluteRow>,
active_bank: usize,
staging_slot: usize,
incumbent_slot: usize,
pub(crate) active_len: usize,
pub(crate) next_len: usize,
pub(crate) incumbent: Option<AcceptingCandidate>,
}
#[derive(Clone, Copy)]
pub(crate) struct LaneView<'a> {
pub(crate) state: LaneState,
pub(crate) registers: &'a [u64],
pub(crate) navigation: &'a [u64],
pub(crate) history: &'a [LanePathRun],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LaneSuccessorAction {
Discard,
Append,
}
#[derive(Clone, Copy)]
pub(crate) struct LanePublication {
action: LaneSuccessorAction,
incumbent: Option<AcceptingCandidate>,
pub(crate) row_complete: bool,
pub(crate) work: usize,
}
fn invalid() -> DataFusionError {
DataFusionError::Internal("MATCH_RECOGNIZE invalid lane continuation".into())
}
fn exhausted(message: &'static str) -> DataFusionError {
DataFusionError::ResourcesExhausted(format!("MATCH_RECOGNIZE {message}"))
}
impl LaneScanState {
pub(crate) fn is_for(&self, program: &Arc<LaneScanProgram>) -> bool {
Arc::ptr_eq(&self.program, program)
}
pub(crate) fn retain_variant_memory(&mut self, variant: &ExecutablePatternVariant) {
debug_assert!(
variant
.lane_scan_program()
.is_some_and(|program| self.is_for(program))
);
if self.runtime_memory.is_none() {
self.runtime_memory = variant.runtime_memory();
}
}
pub(crate) fn discard_candidate(&mut self) {
self.candidate_start = None;
self.active_len = 0;
self.next_len = 0;
self.incumbent = None;
}
pub(crate) const fn candidate_is_live(&self) -> bool {
self.candidate_start.is_some()
}
pub(crate) const fn is_at_row_boundary(&self) -> bool {
self.next_len == 0
}
pub(crate) const fn selection_is_open(&self) -> bool {
self.active_len != 0 || self.next_len != 0
}
pub(crate) fn scratch_registers_mut(&mut self) -> &mut [u64] {
let slot = self.scratch_slot();
let words = self.register_words;
&mut self.registers[slot * words..(slot + 1) * words]
}
pub(crate) fn scratch_navigation_mut(&mut self) -> &mut [u64] {
let slot = self.scratch_slot();
let words = self.navigation_words;
&mut self.navigation[slot * words..(slot + 1) * words]
}
pub(crate) fn scratch_payload_mut(&mut self) -> (&mut [u64], &mut [u64]) {
let slot = self.scratch_slot();
let reg_words = self.register_words;
let nav_words = self.navigation_words;
(
&mut self.registers[slot * reg_words..(slot + 1) * reg_words],
&mut self.navigation[slot * nav_words..(slot + 1) * nav_words],
)
}
pub(crate) fn seed_from_direct(
&mut self,
match_start: AbsoluteRow,
state_id: AutomatonStateId,
runs: &[LanePathRun],
registers: &[u64],
navigation: &[u64],
) -> Option<usize> {
if runs.len() > self.program.capacity.path_runs_per_lane {
return None;
}
let history_runs = u32::try_from(runs.len()).ok()?;
self.reset_candidate(match_start);
self.lanes[0] = LaneState {
state_id,
history_runs,
};
if !runs.is_empty() {
let dst = self.history_range(0).start;
self.histories[dst..dst + runs.len()].copy_from_slice(runs);
}
self.direct = DirectScan::Disabled;
let reg_words = self.register_words;
if reg_words != 0 {
self.registers[..reg_words].copy_from_slice(®isters[..reg_words]);
}
let nav_words = self.navigation_words;
if nav_words != 0 {
self.navigation[..nav_words].copy_from_slice(&navigation[..nav_words]);
}
Some(runs.len() + reg_words + nav_words)
}
fn copy_payload(&mut self, source: usize, destination: usize) {
if self.register_words != 0 {
self.registers.copy_within(
source * self.register_words..(source + 1) * self.register_words,
destination * self.register_words,
);
}
if self.navigation_words != 0 {
self.navigation.copy_within(
source * self.navigation_words..(source + 1) * self.navigation_words,
destination * self.navigation_words,
);
}
}
fn payload_copy_work(&self) -> usize {
self.register_words + self.navigation_words
}
pub(crate) fn try_new(
program: Arc<LaneScanProgram>,
state_memory: &MemoryReservation,
) -> Result<Self> {
let capacity = program.capacity;
let (
lane_slots,
register_slots,
navigation_slots,
history_slots,
scan_resource_bytes,
) = super::compiler::resource_layout_with_navigation(
capacity.live_lanes,
capacity.path_runs_per_lane,
program.register_words,
program.navigation_words,
)
.ok_or_else(|| exhausted("lane storage layout exceeds capacity"))?;
debug_assert_eq!(scan_resource_bytes, capacity.scan_resource_bytes);
let memory = state_memory.new_empty();
memory
.try_resize(scan_resource_bytes)
.map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE lane scan could not reserve {scan_resource_bytes} bytes: {error}"
))
})?;
let lanes = filled(
lane_slots,
LaneState {
state_id: program.transitions.start_state(),
history_runs: 0,
},
"lane slots",
)?
.into_boxed_slice();
let registers = filled(register_slots, 0, "lane registers")?.into_boxed_slice();
let navigation =
filled(navigation_slots, 0, "lane navigation")?.into_boxed_slice();
let histories = filled(history_slots, LanePathRun::EMPTY, "lane history slots")?
.into_boxed_slice();
Ok(Self {
register_words: program.register_words,
navigation_words: program.navigation_words,
program,
lanes,
direct: DirectScan::Disabled,
registers,
navigation,
histories,
_memory: memory,
runtime_memory: None,
candidate_start: None,
active_bank: 0,
staging_slot: lane_slots - 2,
incumbent_slot: lane_slots - 1,
active_len: 0,
next_len: 0,
incumbent: None,
})
}
fn reset_candidate(&mut self, match_start: AbsoluteRow) {
self.candidate_start = Some(match_start);
self.active_bank = 0;
self.active_len = 1;
self.next_len = 0;
self.incumbent = None;
self.incumbent_slot = self.lanes.len() - 1;
}
pub(crate) fn start_candidate(&mut self, match_start: AbsoluteRow) -> usize {
self.reset_candidate(match_start);
self.lanes[0] = LaneState {
state_id: self.program.transitions.start_state(),
history_runs: 0,
};
self.direct = if self.program.direct_linear {
DirectScan::Ready
} else {
DirectScan::Disabled
};
self.registers[..self.register_words]
.copy_from_slice(&self.program.initial_registers[..self.register_words]);
self.navigation[..self.navigation_words].fill(0);
self.payload_copy_work()
}
pub(crate) const fn candidate_start(&self) -> Option<AbsoluteRow> {
self.candidate_start
}
pub(crate) const fn incumbent(&self) -> Option<AcceptingCandidate> {
self.incumbent
}
pub(crate) fn selected_runs(&self) -> Result<super::CompactSelection<'_>> {
let winner = self.incumbent.ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"selected Lane lost its incumbent"
)
})?;
super::CompactSelection::try_new(
&self.program,
self.view(self.incumbent_slot).history,
winner.best_match.match_start_row,
winner.end_row,
winner.best_match.row,
)
}
pub(crate) fn incumbent_path(
&self,
) -> Option<(LanePathCursor<'_>, PhysicalRowCount)> {
let incumbent = self.incumbent?;
let lane = self.incumbent_view()?;
let steps = incumbent
.end_row
.checked_offset_from(incumbent.best_match.match_start_row)?
.checked_add(PhysicalRowCount::new(1))?;
Some((LanePathCursor::new(&self.program, lane.history), steps))
}
pub(crate) const fn successor_len(&self) -> usize {
self.next_len
}
pub(crate) const fn active_len(&self) -> usize {
self.active_len
}
fn view(&self, slot: usize) -> LaneView<'_> {
let state = self.lanes[slot];
LaneView {
state,
registers: &self.registers
[slot * self.register_words..(slot + 1) * self.register_words],
navigation: &self.navigation
[slot * self.navigation_words..(slot + 1) * self.navigation_words],
history: self.history(slot, state),
}
}
#[cfg(test)]
pub(crate) fn active(&self, index: usize) -> Option<LaneView<'_>> {
(index < self.active_len).then(|| self.view(self.active_slot(index)))
}
pub(crate) fn active_state(&self, index: usize) -> Option<LaneState> {
(index < self.active_len).then(|| self.lanes[self.active_slot(index)])
}
pub(crate) fn scratch(&self) -> LaneView<'_> {
self.view(self.scratch_slot())
}
pub(crate) fn successor(&self, index: usize) -> Option<LaneView<'_>> {
(index < self.next_len).then(|| self.view(self.successor_slot(index)))
}
pub(crate) fn successor_state(&self, index: usize) -> Option<LaneState> {
(index < self.next_len).then(|| self.lanes[self.successor_slot(index)])
}
pub(crate) fn incumbent_view(&self) -> Option<LaneView<'_>> {
self.incumbent.map(|_| self.view(self.incumbent_slot))
}
pub(crate) fn prepare_transition(
&mut self,
source_index: usize,
stage_in_next: bool,
) -> Result<usize> {
self.staging_slot =
if stage_in_next && self.next_len < self.program.capacity.live_lanes {
self.successor_base() + self.next_len
} else {
self.lanes.len() - 2
};
let source = self.active_slot(source_index);
let work = self.slot_copy_work(source)?;
self.copy_slot(source, self.scratch_slot());
Ok(work)
}
pub(crate) fn take_single_active(&mut self) {
debug_assert_eq!((self.active_len, self.next_len), (1, 0));
self.staging_slot = self.active_slot(0);
self.active_bank ^= 1;
self.active_len = 0;
debug_assert_eq!(self.staging_slot, self.successor_base());
}
pub(crate) fn bind_direct_payload(&mut self, speculative: bool) -> usize {
debug_assert_eq!((self.active_len, self.next_len), (1, 0));
let active = self.active_slot(0);
if speculative {
self.staging_slot = self.lanes.len() - 2;
self.copy_payload(active, self.staging_slot);
self.payload_copy_work()
} else {
self.staging_slot = active;
0
}
}
pub(crate) fn advance_direct_edge(
&mut self,
edge_id: usize,
row: AbsoluteRow,
governor: &mut crate::execution::common::work::WorkGovernor,
is_aborted: impl FnOnce() -> bool,
) -> Result<()> {
let active = self.active_slot(0);
let edge = self.program.transitions.sealed_edge(edge_id);
let winner = self.program.closure_accepting[edge.next_state_id.index()];
let next_range = self.program.transitions.sealed_range(edge.next_state_id);
let terminal = next_range.is_empty()
|| (winner.is_some()
&& self
.program
.transitions
.sealed_edge(next_range.start)
.after_accept);
let reserve = self.incumbent_slot;
let copy_winner = winner.is_some() && !terminal;
let first = if copy_winner && self.incumbent.is_some() {
(self.lanes[reserve].history_runs as usize).saturating_sub(1)
} else {
0
};
let mut work = 1;
if self.staging_slot != active {
work += self.payload_copy_work();
}
if copy_winner {
work += self.lanes[active].history_runs as usize + 1 - first
+ self.payload_copy_work();
}
governor.record_completed(work, is_aborted)?;
self.advance_slot(active, edge.source_state_id, edge_id, row)?;
if self.staging_slot != active {
self.copy_payload(self.staging_slot, active);
}
if let Some(state) = winner {
let lane = self.lanes[active];
let receipt = self.acceptance_receipt(
lane,
state,
row.checked_add(PhysicalRowCount::new(1))
.ok_or_else(invalid)?,
row,
)?;
if terminal {
debug_assert_eq!(self.next_len, 0);
self.incumbent_slot = active;
} else {
let end = lane.history_runs as usize;
let from = self.history_range(active).start;
let to = self.history_range(reserve).start;
self.histories
.copy_within(from + first..from + end, to + first);
self.copy_payload(active, reserve);
self.lanes[reserve] = lane;
}
self.incumbent = Some(receipt);
}
if terminal {
self.finish_row();
}
Ok(())
}
pub(crate) fn apply_scratch_transition(
&mut self,
source_state_id: AutomatonStateId,
edge_id: usize,
row: AbsoluteRow,
) -> Result<()> {
self.advance_slot(self.scratch_slot(), source_state_id, edge_id, row)
}
pub(crate) fn advance_single_active(
&mut self,
source: AutomatonStateId,
edge_id: usize,
row: AbsoluteRow,
) -> Result<()> {
debug_assert_eq!((self.active_len, self.next_len), (1, 0));
self.advance_slot(self.active_slot(0), source, edge_id, row)
}
fn advance_slot(
&mut self,
slot: usize,
source_state_id: AutomatonStateId,
edge_id: usize,
row: AbsoluteRow,
) -> Result<()> {
row.checked_offset_from(self.candidate_start.ok_or_else(invalid)?)
.and_then(|steps| steps.as_u64().checked_add(1))
.ok_or_else(|| exhausted("lane history exceeds u64"))?;
let mut lane = self.lanes[slot];
let runs = lane.history_runs as usize;
let range = self.history_range(slot);
let edge = self.program.transitions.sealed_edge(edge_id);
let cycle = self
.program
.cycle_position(source_state_id)
.filter(|(id, phase)| {
let len = self.program.cycles[*id as usize].len() as u32;
let next_phase = if *phase == len - 1 { 0 } else { *phase + 1 };
self.program.cycle_position(edge.next_state_id) == Some((*id, next_phase))
});
let append = if let Some((cycle_id, phase)) = cycle {
if runs != 0
&& self.histories[range.start + runs - 1].try_extend_cycle(
&self.program,
edge_id,
row,
PhysicalRowCount::new(1),
)?
{
None
} else {
Some(LanePathRun::cycle(cycle_id, phase, row))
}
} else if self.program.optimistic_history {
let step = PhysicalRowCount::new(1);
if runs > 0
&& self.histories[range.start + runs - 1]
.extend_repeated_edge(edge_id, row, step)?
{
None
} else {
Some(LanePathRun::repeated_edge(edge_id, row, step))
}
} else {
Some(LanePathRun::edge(edge_id, row))
};
if let Some(run) = append {
if runs >= self.program.capacity.path_runs_per_lane {
return Err(capacity_error("lane history exceeds its storage capacity"));
}
let expected = if runs == 0 {
self.candidate_start.ok_or_else(invalid)?
} else {
let last = self.histories[range.start + runs - 1];
last.first_row()
.checked_add(last.steps())
.ok_or_else(|| exhausted("lane history row exceeds u64"))?
};
if row != expected {
return Err(invalid());
}
self.histories[range.start + runs] = run;
lane.history_runs += 1;
}
lane.state_id = edge.next_state_id;
self.lanes[slot] = lane;
Ok(())
}
pub(crate) fn plan_publication(
&self,
action: LaneSuccessorAction,
acceptance: Option<(AutomatonStateId, AbsoluteRow)>,
end_row: AbsoluteRow,
) -> Result<LanePublication> {
if action == LaneSuccessorAction::Append
&& self.next_len >= self.program.capacity.live_lanes
{
return Err(capacity_error(
"lane successor exceeds its storage capacity",
));
}
let scratch = self.lanes[self.scratch_slot()];
let incumbent = acceptance
.map(|(state_id, row)| {
self.acceptance_receipt(scratch, state_id, row, end_row)
})
.transpose()?;
let successor_copy = match action {
LaneSuccessorAction::Discard => false,
LaneSuccessorAction::Append => {
self.scratch_slot() != self.successor_base() + self.next_len
}
};
let copies = usize::from(successor_copy) + usize::from(incumbent.is_some());
let copy_width = self.slot_copy_work(self.scratch_slot())?;
let work = copies
.checked_mul(copy_width)
.and_then(|work| work.checked_add(1))
.ok_or_else(|| exhausted("lane publication work exceeds usize"))?;
Ok(LanePublication {
action,
incumbent,
row_complete: acceptance.is_some(),
work,
})
}
pub(crate) fn publish_scratch(&mut self, publication: LanePublication) {
if publication.action == LaneSuccessorAction::Append {
let destination = self.successor_slot(self.next_len);
self.next_len += 1;
if destination != self.scratch_slot() {
self.copy_slot(self.scratch_slot(), destination);
}
}
if let Some(incumbent) = publication.incumbent {
self.copy_slot(self.scratch_slot(), self.incumbent_slot);
self.incumbent = Some(incumbent);
}
}
pub(crate) fn finish_row(&mut self) {
self.active_bank ^= 1;
self.active_len = self.next_len;
self.next_len = 0;
}
fn acceptance_receipt(
&self,
lane: LaneState,
state_id: AutomatonStateId,
position: AbsoluteRow,
end_row: AbsoluteRow,
) -> Result<AcceptingCandidate> {
let match_start = self.candidate_start.ok_or_else(invalid)?;
end_row
.checked_offset_from(match_start)
.ok_or_else(|| exhausted("lane path end precedes its start"))?;
let closure = self.program.closure_accepting[lane.state_id.index()];
if closure != Some(state_id)
|| end_row.checked_add(PhysicalRowCount::new(1)) != Some(position)
{
return Err(invalid());
}
Ok(AcceptingCandidate {
best_match: BestMatch {
path_end: compact_path_node(),
state_id,
row: position,
match_start_row: match_start,
},
end_row,
})
}
fn active_slot(&self, index: usize) -> usize {
self.active_bank * self.program.capacity.live_lanes + index
}
fn successor_slot(&self, index: usize) -> usize {
self.successor_base() + index
}
fn successor_base(&self) -> usize {
(self.active_bank ^ 1) * self.program.capacity.live_lanes
}
pub(crate) fn scratch_slot(&self) -> usize {
self.staging_slot
}
pub(crate) fn history_range(&self, slot: usize) -> std::ops::Range<usize> {
let start = slot * self.program.capacity.path_runs_per_lane;
start..start + self.program.capacity.path_runs_per_lane
}
fn slot_copy_work(&self, slot: usize) -> Result<usize> {
(self.lanes[slot].history_runs as usize)
.checked_add(self.payload_copy_work())
.and_then(|width| width.checked_add(1))
.ok_or_else(|| exhausted("lane slot copy work exceeds usize"))
}
fn history(&self, slot: usize, lane: LaneState) -> &[LanePathRun] {
let range = self.history_range(slot);
&self.histories[range.start..range.start + lane.history_runs as usize]
}
fn copy_slot(&mut self, source: usize, destination: usize) {
let lane = self.lanes[source];
let history = self.history_range(source);
let runs = lane.history_runs as usize;
self.copy_payload(source, destination);
if runs != 0 {
self.histories.copy_within(
history.start..history.start + runs,
self.history_range(destination).start,
);
}
self.lanes[destination] = lane;
}
}