use crate::core::{AbsoluteRow, PhysicalRowCount};
use crate::execution::matching::row_loop::lane_scan::{
ClassifierDemand, CompactSelection, LaneScanProgram, LaneSelectedRuns,
SymbolCaptures, path::LanePathRun,
};
use arrayvec::ArrayVec;
use datafusion_common::{DataFusionError, Result};
use datafusion_execution::memory_pool::MemoryReservation;
struct Accepted {
prefix_len: usize,
prefix_tail: LanePathRun,
terminal: Option<LanePathRun>,
}
#[derive(Default)]
pub(crate) struct DirectHistory {
captures: Option<SymbolCaptures>,
extent_only: bool,
#[allow(dead_code)] memory: Option<MemoryReservation>,
runs: ArrayVec<LanePathRun, { LaneSelectedRuns::MAX_ATOMIC_RUNS }>,
accepted: Option<Accepted>,
}
impl DirectHistory {
pub(crate) fn configure(
&mut self,
demand: ClassifierDemand,
memory: &MemoryReservation,
) -> Result<()> {
let mask = match demand {
ClassifierDemand::Symbols(mask) | ClassifierDemand::AllWithCaptures(mask) => {
mask
}
ClassifierDemand::All => 0,
};
if mask != 0 && self.captures.as_ref().is_none_or(|c| c.mask() != mask) {
let mut reservation = memory.new_empty();
self.captures = Some(SymbolCaptures::try_new(mask, &mut reservation)?);
self.memory = Some(reservation);
}
self.extent_only = matches!(demand, ClassifierDemand::Symbols(_));
Ok(())
}
pub(crate) fn captures_mut(&mut self) -> Option<&mut SymbolCaptures> {
self.captures.as_mut()
}
pub(crate) fn tracks_runs(&self) -> bool {
!self.extent_only
}
pub(crate) fn observe(
&mut self,
graph: &LaneScanProgram,
edge_id: usize,
first: usize,
count: usize,
has_winner: bool,
accepting: bool,
) {
if let Some(captures) = &mut self.captures {
let bit = graph
.transitions
.sealed_edge(edge_id)
.symbol_id
.packed_membership_bit()
.expect("packed direct symbol");
captures.observe(
bit,
AbsoluteRow::new(first as u64),
AbsoluteRow::new((first + count - 1) as u64),
count as u64,
has_winner,
accepting,
);
}
}
#[inline]
pub(crate) fn runs(&self) -> &[LanePathRun] {
&self.runs
}
#[inline]
pub(crate) fn is_full(&self) -> bool {
self.runs.is_full()
}
pub(crate) fn clear(&mut self) {
self.runs.clear();
self.accepted = None;
if let Some(captures) = &mut self.captures {
captures.reset();
}
}
pub(crate) fn push(
&mut self,
graph: &LaneScanProgram,
edge_id: usize,
row: AbsoluteRow,
) -> Result<bool> {
self.push_run(graph, edge_id, row, PhysicalRowCount::new(1))
}
pub(crate) fn push_run(
&mut self,
graph: &LaneScanProgram,
edge_id: usize,
row: AbsoluteRow,
step: PhysicalRowCount,
) -> Result<bool> {
if self.extent_only {
return Ok(true);
}
if row.checked_add(step).is_none() {
return Err(DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE direct history exceeds row coordinates".into(),
));
}
if let Some(tail) = self.runs.last_mut() {
if tail.extend_repeated_edge(edge_id, row, step)?
|| tail.try_extend_cycle(graph, edge_id, row, step)?
{
return Ok(true);
}
if tail.first_row().checked_add(tail.steps()) != Some(row) {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE non-contiguous direct history"
);
}
}
if self.runs.is_full() {
return Ok(false);
}
let edge = graph.transitions.sealed_edge(edge_id);
let run = match graph.cycle_position(edge.source_state_id) {
Some((id, phase))
if (step.as_u64() == 1 || graph.cycles[id as usize].len() == 1)
&& graph.cycles[id as usize][phase as usize] as usize == edge_id =>
{
LanePathRun::cycle_steps(id, phase, row, step)
}
_ => LanePathRun::repeated_edge(edge_id, row, step),
};
self.runs.push(run);
Ok(true)
}
pub(crate) fn accept(&mut self) {
self.accepted = self.runs.last().map(|&tail| Accepted {
prefix_len: self.runs.len(),
prefix_tail: tail,
terminal: None,
});
}
pub(crate) fn accept_alternative(
&mut self,
graph: &LaneScanProgram,
edge_id: usize,
row: AbsoluteRow,
) -> Result<bool> {
debug_assert!(edge_id < graph.transitions.edge_count());
if row.checked_add(PhysicalRowCount::new(1)).is_none() {
return Err(DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE direct history exceeds row coordinates".into(),
));
}
if !self.extent_only {
let tail = self.runs.last().copied();
if let Some(tail) = tail
&& tail.first_row().checked_add(tail.steps()) != Some(row)
{
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE non-contiguous terminal alternative"
);
}
if self.runs.is_full() {
return Ok(false);
}
self.accepted = Some(Accepted {
prefix_len: self.runs.len(),
prefix_tail: tail.unwrap_or(LanePathRun::EMPTY),
terminal: Some(LanePathRun::edge(edge_id, row)),
});
}
if let Some(captures) = &mut self.captures {
captures.accept_alternative(
graph
.transitions
.sealed_edge(edge_id)
.symbol_id
.packed_membership_bit()
.expect("packed direct symbol"),
row,
);
}
Ok(true)
}
pub(crate) fn select<'a>(
&'a mut self,
graph: &'a LaneScanProgram,
start: AbsoluteRow,
end: AbsoluteRow,
acceptance: AbsoluteRow,
) -> Result<CompactSelection<'a>> {
if self.extent_only {
return match &self.captures {
Some(captures) => {
CompactSelection::from_captures(start, end, acceptance, captures)
}
None => CompactSelection::from_extent(start, end, acceptance),
};
}
let accepted = self.accepted.as_ref().ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"MATCH_RECOGNIZE direct history has no accepted prefix"
)
})?;
self.runs.truncate(accepted.prefix_len);
if let Some(tail) = self.runs.last_mut() {
*tail = accepted.prefix_tail;
}
if let Some(terminal) = accepted.terminal {
self.runs.push(terminal);
}
CompactSelection::try_new_with_captures(
graph,
&self.runs,
self.captures.as_ref(),
start,
end,
acceptance,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::matching::row_loop::lane_scan::path::tests::repeated_pair_graph;
#[test]
fn publication_restores_the_accepted_tail_and_discards_later_runs() {
let graph = repeated_pair_graph();
let word = &graph.cycles[0];
assert_eq!(word.len(), 2);
let mut history = DirectHistory::default();
let row = AbsoluteRow::new;
for offset in 0..3 {
assert!(
history
.push(&graph, word[offset % 2] as usize, row(10 + offset as u64))
.unwrap()
);
}
history.accept();
assert!(history.push(&graph, word[1] as usize, row(13)).unwrap());
let other = (0..graph.transitions.edge_count())
.find(|id| !word.contains(&(*id as u32)))
.unwrap();
assert!(history.push(&graph, other, row(14)).unwrap());
assert_eq!(history.runs.len(), 2);
assert_eq!(history.runs[0].steps().as_u64(), 4);
let winner = history.select(&graph, row(10), row(12), row(13)).unwrap();
assert_eq!(winner.expected_steps.as_u64(), 3);
let selected = winner.history().unwrap();
assert_eq!(selected.runs.len(), 1);
for offset in 0..3 {
let edge = graph.transitions.sealed_edge(word[offset % 2] as usize);
let (actual, period) = selected.edge_and_period(0, offset as u64).unwrap();
assert_eq!(period, 2);
assert_eq!(actual.symbol_id, edge.symbol_id);
assert_eq!(actual.next_state_id, edge.next_state_id);
assert_eq!(actual.excluded, edge.excluded);
}
history.clear();
assert!(history.select(&graph, row(10), row(12), row(13)).is_err());
}
#[test]
fn terminal_sibling_survives_preferred_cycle_extension_from_the_same_row() {
let graph = repeated_pair_graph();
let word = &graph.cycles[0];
let terminal = (0..graph.transitions.edge_count())
.find(|id| !word.contains(&(*id as u32)))
.unwrap();
let row = AbsoluteRow::new;
for prefix in [0, 3] {
let mut history = DirectHistory::default();
for i in 0..prefix {
assert!(
history
.push(&graph, word[i % 2] as usize, row(i as u64))
.unwrap()
);
}
let before = history.runs.clone();
assert!(
history
.accept_alternative(&graph, terminal, row(prefix as u64))
.unwrap()
);
assert_eq!(history.runs, before);
for i in prefix..prefix + 3 {
assert!(
history
.push(&graph, word[i % 2] as usize, row(i as u64))
.unwrap()
);
}
let selection = history
.select(&graph, row(0), row(prefix as u64), row(prefix as u64 + 1))
.unwrap();
let selected = selection.history().unwrap();
let (tail, earlier) = selected.runs.split_last().unwrap();
assert_eq!(earlier, before.as_slice());
assert_eq!(*tail, LanePathRun::edge(terminal, row(prefix as u64)));
}
}
#[test]
fn full_trace_can_extend_its_tail_but_never_partially_appends() {
let mut graph = repeated_pair_graph();
graph.cycle_positions.fill(u64::MAX);
let word = &graph.cycles[0];
let mut history = DirectHistory::default();
let row = AbsoluteRow::new;
let limit = LaneSelectedRuns::MAX_ATOMIC_RUNS;
for i in 0..limit {
assert!(
history
.push(&graph, word[i % 2] as usize, row(i as u64))
.unwrap()
);
}
let tail = word[(limit - 1) % 2] as usize;
let next = word[limit % 2] as usize;
assert!(history.push(&graph, tail, row(limit as u64)).unwrap());
history.accept();
let before = history.runs.clone();
assert!(!history.push(&graph, next, row(limit as u64 + 1)).unwrap());
assert_eq!(history.runs, before);
assert!(
!history
.accept_alternative(&graph, next, row(limit as u64 + 1))
.unwrap()
);
assert_eq!(history.runs.last().unwrap().steps().as_u64(), 2);
let winner = history
.select(&graph, row(0), row(limit as u64), row(limit as u64 + 1))
.unwrap();
assert_eq!(winner.expected_steps.as_u64(), limit as u64 + 1);
}
#[test]
fn noncontiguous_and_overflowing_rows_leave_the_winner_intact() {
let graph = repeated_pair_graph();
let word = &graph.cycles[0];
let mut history = DirectHistory::default();
let row = AbsoluteRow::new;
let end = u64::MAX - 1;
assert!(history.push(&graph, word[0] as usize, row(end)).unwrap());
history.accept();
let before = history.runs.clone();
assert!(
history
.push(&graph, word[1] as usize, row(end - 2))
.is_err()
);
assert!(
history
.push(&graph, word[0] as usize, row(end - 2))
.is_err()
);
assert!(
history
.push(&graph, word[1] as usize, row(u64::MAX))
.is_err()
);
assert_eq!(history.runs, before);
assert!(
history
.select(&graph, row(end - 1), row(end), row(end))
.is_err()
);
assert!(
history
.select(&graph, row(end), row(end), row(end - 1))
.is_err()
);
let winner = history
.select(&graph, row(end), row(end), row(u64::MAX))
.unwrap();
assert_eq!(winner.expected_steps.as_u64(), 1);
}
}