#[cfg(test)]
use std::cell::Cell;
use std::ops::Range;
use std::sync::Arc;
#[cfg(test)]
use crate::core::NavigationOffsets;
use crate::core::{
AbsoluteRow, EmptyMatchesMode, MAX_VALID_MATCH_SEQUENCE_NUMBER, NavigationOffset,
RowsPerMatch,
};
use crate::execution::common::coordinates::{
absolute_row_from_usize, absolute_row_to_usize, checked_match_number,
};
use crate::execution::common::progress::CoarseWorkBatch;
use crate::execution::matching::path::{PathStep, Sym};
use crate::execution::matching::row_loop::lane_scan::CompactSelection;
use crate::execution::matching::{
ExecutableOutputFinalizer, ExecutableOutputPlan, ExecutableRowStreamPlan,
};
use crate::nfa::CompiledAutomaton;
use crate::planning::logical::MetadataEndpoint;
use datafusion::common::{DataFusionError, Result, internal_err};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::execution::storage) struct ValidatedEmissionExtent {
pub(in crate::execution::storage) partition_start: usize,
pub(in crate::execution::storage) partition_end: usize,
global_offset: usize,
collection_rows: usize,
pub(in crate::execution::storage) input_end: usize,
pub(in crate::execution::storage) partition_start_abs: AbsoluteRow,
pub(in crate::execution::storage) partition_end_abs: AbsoluteRow,
pub(in crate::execution::storage) input_end_abs: AbsoluteRow,
}
#[cfg(test)]
#[derive(Clone, Copy, Default)]
struct SelectedPathCheckCounters<'a> {
paths: Option<&'a Cell<usize>>,
steps: Option<&'a Cell<usize>>,
}
pub(in crate::execution::storage) fn validate_emission_extent(
partition: &Range<usize>,
global_offset: usize,
collection_rows: usize,
) -> Result<ValidatedEmissionExtent> {
if partition.start > partition.end {
return internal_err!(
"MATCH_RECOGNIZE emission partition has reversed bounds {}..{}",
partition.start,
partition.end
);
}
let input_end = global_offset.checked_add(collection_rows).ok_or_else(|| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE emission source end overflows for origin {global_offset} and {collection_rows} rows"
))
})?;
if partition.start > input_end {
return internal_err!(
"MATCH_RECOGNIZE emission partition starts at {} after available input end {input_end}",
partition.start
);
}
Ok(ValidatedEmissionExtent {
partition_start: partition.start,
partition_end: partition.end,
global_offset,
collection_rows,
input_end,
partition_start_abs: absolute_row_from_usize(partition.start, "partition start")?,
partition_end_abs: absolute_row_from_usize(partition.end, "partition end")?,
input_end_abs: absolute_row_from_usize(input_end, "input end")?,
})
}
pub(super) fn checked_sequence_successor(sequence: i64) -> Result<i64> {
let next = sequence.checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE match sequence number overflow".to_string(),
)
})?;
if next > MAX_VALID_MATCH_SEQUENCE_NUMBER {
return Err(DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE match sequence number {next} exceeds the valid matched-row metadata range"
)));
}
Ok(next)
}
pub(in crate::execution::storage) fn next_buffer_sequence_number(
offset: NavigationOffset,
relative_row: usize,
) -> Result<i64> {
if relative_row >= offset.as_usize() {
return internal_err!(
"MATCH_RECOGNIZE NEXT sequence contract has relative row {relative_row} outside non-zero offset {}",
offset.as_usize()
);
}
Ok(i64::MAX - (offset.as_usize() - relative_row) as i64)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::execution::storage) struct PhysicalPathBounds {
pub(in crate::execution::storage) first: AbsoluteRow,
pub(in crate::execution::storage) last: AbsoluteRow,
}
#[derive(Debug, Clone, Copy)]
pub(in crate::execution::storage) struct ValidatedPathFacts {
pub(in crate::execution::storage) will_emit_physical_row: bool,
pub(in crate::execution::storage) physical_bounds: PhysicalPathBounds,
pub(in crate::execution::storage) path_len: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::execution::storage) enum MatchRowPhase {
Previous,
Path,
Next,
Done,
}
pub(in crate::execution::storage) struct MatchRowProgress {
phase: MatchRowPhase,
previous: Range<usize>,
path_index: usize,
path_end: usize,
sequence_number: i64,
last_emitted_row: Option<usize>,
next: Range<usize>,
next_start: usize,
global_offset: usize,
match_number: i64,
emitted_any_row: bool,
}
impl MatchRowProgress {
pub(in crate::execution::storage) fn retain_first_path_row(&mut self) {
self.path_end = self.path_end.min(1);
}
pub(in crate::execution::storage) fn phase(&self) -> MatchRowPhase {
self.phase
}
pub(in crate::execution::storage) fn emitted_any_row(&self) -> bool {
self.emitted_any_row
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SelectedPathFillOrder {
Forward,
Reverse,
}
#[derive(Debug)]
pub(crate) struct CheckedSelectedPath {
steps: Vec<PathStep>,
emission_extent: ValidatedEmissionExtent,
facts: ValidatedPathFacts,
}
impl CheckedSelectedPath {
pub(crate) fn steps(&self) -> &[PathStep] {
&self.steps
}
pub(crate) fn semantic_start(&self) -> AbsoluteRow {
self.steps
.first()
.expect("checked selected path is nonempty")
.row
}
pub(crate) fn semantic_end(&self) -> AbsoluteRow {
self.steps
.last()
.expect("checked selected path is nonempty")
.row
}
pub(crate) fn is_empty(&self) -> bool {
self.steps
.first()
.expect("checked selected path is nonempty")
.sym
== Sym::Empty
}
pub(crate) fn next_cursor(
&self,
skip: &crate::execution::matching::ResolvedAfterMatchSkip,
start: AbsoluteRow,
target: Option<AbsoluteRow>,
) -> Result<crate::execution::matching::NextMatchCursor> {
skip.plan_selected_cursor(start, self.semantic_end(), self.is_empty(), target)
}
pub(crate) fn into_steps(self) -> Vec<PathStep> {
self.steps
}
pub(in crate::execution::storage) fn validated_facts(
&self,
emission_extent: ValidatedEmissionExtent,
) -> Result<ValidatedPathFacts> {
if emission_extent != self.emission_extent {
return internal_err!(
"MATCH_RECOGNIZE checked selected path emission extent changed from partition {}..{}, origin {}, rows {} to partition {}..{}, origin {}, rows {} before output",
self.emission_extent.partition_start,
self.emission_extent.partition_end,
self.emission_extent.global_offset,
self.emission_extent.collection_rows,
emission_extent.partition_start,
emission_extent.partition_end,
emission_extent.global_offset,
emission_extent.collection_rows
);
}
Ok(self.facts)
}
}
pub(crate) struct SelectedPathValidator<'a> {
classifier_names: &'a [Option<String>],
emit_sequence_numbers: bool,
omit_empty_matches: bool,
physical_end_abs: AbsoluteRow,
emission_extent: ValidatedEmissionExtent,
fill_order: SelectedPathFillOrder,
progress: SelectedPathValidation,
#[cfg(test)]
checked_paths: Option<&'a Cell<usize>>,
#[cfg(test)]
checked_steps: Option<&'a Cell<usize>>,
}
#[derive(Default)]
pub(crate) struct SelectedPathValidation {
previous_observed_row: Option<AbsoluteRow>,
observed_steps: usize,
will_emit_physical_row: bool,
physical_bounds: Option<PhysicalPathBounds>,
}
impl<'a> SelectedPathValidator<'a> {
pub(crate) fn with_progress(mut self, progress: SelectedPathValidation) -> Self {
self.progress = progress;
self
}
pub(crate) fn into_progress(self) -> SelectedPathValidation {
self.progress
}
fn new(
automaton: &'a CompiledAutomaton,
empty_matches_mode: &'a EmptyMatchesMode,
emit_sequence_numbers: bool,
emission_extent: ValidatedEmissionExtent,
fill_order: SelectedPathFillOrder,
#[cfg(test)] checks: SelectedPathCheckCounters<'a>,
) -> Self {
let physical_end_abs = emission_extent
.partition_end_abs
.min(emission_extent.input_end_abs);
Self {
classifier_names: automaton.id_to_symbol(),
emit_sequence_numbers,
omit_empty_matches: matches!(empty_matches_mode, EmptyMatchesMode::Omit),
physical_end_abs,
emission_extent,
fill_order,
progress: SelectedPathValidation::default(),
#[cfg(test)]
checked_paths: checks.paths,
#[cfg(test)]
checked_steps: checks.steps,
}
}
#[cfg(test)]
pub(crate) fn try_new(
automaton: &'a CompiledAutomaton,
empty_matches_mode: &'a EmptyMatchesMode,
emit_sequence_numbers: bool,
partition: &Range<usize>,
global_offset: usize,
collection_rows: usize,
fill_order: SelectedPathFillOrder,
) -> Result<Self> {
let extent = validate_emission_extent(partition, global_offset, collection_rows)?;
Ok(Self::new(
automaton,
empty_matches_mode,
emit_sequence_numbers,
extent,
fill_order,
SelectedPathCheckCounters::default(),
))
}
#[inline]
pub(crate) fn observe(&mut self, step: PathStep) -> Result<()> {
let out_of_order = self.progress.previous_observed_row.is_some_and(|previous| {
match self.fill_order {
SelectedPathFillOrder::Forward => step.row < previous,
SelectedPathFillOrder::Reverse => step.row > previous,
}
});
if out_of_order {
return internal_err!(
"MATCH_RECOGNIZE selected path rows are not monotonic at absolute row {}",
step.row
);
}
self.progress.previous_observed_row = Some(step.row);
let is_empty = step.sym == Sym::Empty;
let is_physical = step.row >= self.emission_extent.partition_start_abs
&& step.row < self.physical_end_abs;
if !is_empty {
lookup_classifier(self.classifier_names, step.sym)?;
if !is_physical {
return internal_err!(
"MATCH_RECOGNIZE selected path has named symbol id {} at non-physical absolute row {} outside {}..{}",
step.sym.to_index(),
step.row,
self.emission_extent.partition_start_abs,
self.physical_end_abs
);
}
} else if !is_physical {
return internal_err!(
"MATCH_RECOGNIZE selected path has an empty control step at invalid absolute row {}",
step.row
);
}
if self.emit_sequence_numbers {
checked_sequence_successor(self.progress.observed_steps as i64)?;
}
self.progress.observed_steps =
self.progress.observed_steps.checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE selected path observation count exceeds usize"
.to_string(),
)
})?;
match &mut self.progress.physical_bounds {
Some(bounds) => match self.fill_order {
SelectedPathFillOrder::Forward => bounds.last = step.row,
SelectedPathFillOrder::Reverse => bounds.first = step.row,
},
None => {
self.progress.physical_bounds = Some(PhysicalPathBounds {
first: step.row,
last: step.row,
});
}
}
if !(self.omit_empty_matches && is_empty) {
self.progress.will_emit_physical_row = true;
}
#[cfg(test)]
if let Some(checked_steps) = self.checked_steps {
checked_steps.set(checked_steps.get() + 1);
}
Ok(())
}
pub(crate) fn finish(
self,
steps: Vec<PathStep>,
candidate_start: AbsoluteRow,
candidate_end: AbsoluteRow,
acceptance_position: AbsoluteRow,
) -> Result<CheckedSelectedPath> {
let facts = self.finish_facts(steps.len())?;
let first = *steps.first().expect("selected path was checked nonempty");
let last = *steps.last().expect("selected path was checked nonempty");
if candidate_start > candidate_end {
return internal_err!(
"MATCH_RECOGNIZE selected NFA candidate starts at {} after end {}",
candidate_start,
candidate_end
);
}
if candidate_end > acceptance_position {
return internal_err!(
"MATCH_RECOGNIZE selected NFA candidate ends at {} after acceptance position {}",
candidate_end,
acceptance_position
);
}
if last.row != candidate_end {
return internal_err!(
"MATCH_RECOGNIZE selected NFA path ends at {}, candidate ends at {}",
last.row,
candidate_end
);
}
let is_empty = first.sym == Sym::Empty;
if is_empty && (steps.len() != 1 || candidate_end != acceptance_position) {
return internal_err!(
"MATCH_RECOGNIZE selected empty NFA path disagrees with its candidate extent"
);
}
if !is_empty && first.row != candidate_start {
return internal_err!(
"MATCH_RECOGNIZE selected NFA path starts at {}, candidate starts at {}",
first.row,
candidate_start
);
}
#[cfg(test)]
if let Some(checked_paths) = self.checked_paths {
checked_paths.set(checked_paths.get() + 1);
}
Ok(CheckedSelectedPath {
steps,
emission_extent: self.emission_extent,
facts,
})
}
fn finish_facts(&self, path_len: usize) -> Result<ValidatedPathFacts> {
if path_len == 0 {
return internal_err!(
"MATCH_RECOGNIZE selected match has an empty path contract"
);
}
if self.progress.observed_steps != path_len {
return internal_err!(
"MATCH_RECOGNIZE selected path observer checked {} steps for a {path_len}-step path",
self.progress.observed_steps
);
}
let physical_bounds = self
.progress
.physical_bounds
.expect("non-empty observed path records physical bounds");
Ok(ValidatedPathFacts {
will_emit_physical_row: self.progress.will_emit_physical_row,
physical_bounds,
path_len,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::execution::storage) struct EncodedClassifier<'a> {
pub(in crate::execution::storage) symbol: Sym,
pub(in crate::execution::storage) name: &'a str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::execution::storage) struct EncodedOutputRow<'a> {
pub(super) row_ref: AbsoluteRow,
pub(super) source_floor: usize,
pub(super) classifier: Option<EncodedClassifier<'a>>,
pub(super) match_number: i64,
pub(in crate::execution::storage) sequence_number: i64,
pub(super) excluded: bool,
pub(in crate::execution::storage) matched_physical_row: Option<AbsoluteRow>,
}
impl EncodedOutputRow<'_> {
pub(in crate::execution::storage) const fn classifier_symbol(self) -> Option<Sym> {
match self.classifier {
Some(classifier) => Some(classifier.symbol),
None => None,
}
}
pub(super) const fn reservation_context(self) -> &'static str {
if self.matched_physical_row.is_some() {
"matched row"
} else {
"physical row"
}
}
}
pub(in crate::execution::storage) struct MatchRowsEncoder {
automaton: Arc<CompiledAutomaton>,
stream: Arc<ExecutableRowStreamPlan>,
emit_sequence_numbers: bool,
#[cfg(test)]
checked_selected_paths: Cell<usize>,
#[cfg(test)]
checked_selected_steps: Cell<usize>,
}
impl MatchRowsEncoder {
pub(in crate::execution::storage) fn supports_compact_output(&self) -> bool {
!self.stream.emits_navigation_buffer_rows()
}
pub(in crate::execution::storage) fn emits_all_selected_rows(&self) -> bool {
matches!(
self.stream.rows_per_match(),
RowsPerMatch::AllRows(EmptyMatchesMode::Omit | EmptyMatchesMode::Show)
)
}
pub(in crate::execution::storage) fn validate_compact_match(
&self,
match_id: u64,
selected: &CompactSelection<'_>,
(readable_start, readable_end): (usize, usize),
) -> Result<(i64, usize)> {
let first = absolute_row_to_usize(selected.start, "compact match start")?;
let last = absolute_row_to_usize(selected.end, "compact match end")?;
let steps = usize::try_from(selected.expected_steps.as_u64()).map_err(|_| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact path length exceeds usize".into(),
)
})?;
if steps == 0 || first < readable_start || last >= readable_end {
return internal_err!(
"MATCH_RECOGNIZE compact selected path has invalid physical bounds"
);
}
if self.emit_sequence_numbers
&& steps as u64 > MAX_VALID_MATCH_SEQUENCE_NUMBER as u64
{
return Err(DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact match sequence exceeds metadata range".into(),
));
}
Ok((checked_match_number(match_id)?, steps))
}
pub(in crate::execution::storage) fn compact_summary_representative(
&self,
selected: &CompactSelection<'_>,
match_number: i64,
needs_classifier: bool,
) -> Result<EncodedOutputRow<'_>> {
let (classifier, excluded) = if needs_classifier {
let (edge, _) = selected.history()?.edge_and_period(0, 0)?;
(Some(Sym::from_index(edge.symbol_id.index())), edge.excluded)
} else {
(None, false)
};
self.matched_row(
selected.start,
absolute_row_to_usize(selected.start, "compact representative")?,
match_number,
i64::from(self.emit_sequence_numbers),
classifier,
excluded,
)
}
pub(in crate::execution::storage) fn new(
automaton: Arc<CompiledAutomaton>,
plan: &ExecutableOutputPlan,
) -> Self {
let stream = Arc::clone(plan.stream());
let emit_sequence_numbers = stream.has_sequence_number()
|| matches!(plan.finalizer(), ExecutableOutputFinalizer::DirectCounts { summaries }
if summaries.iter().any(|s| matches!(s.metadata(), Some(MetadataEndpoint::Sequence { .. }))));
Self {
automaton,
stream,
emit_sequence_numbers,
#[cfg(test)]
checked_selected_paths: Cell::new(0),
#[cfg(test)]
checked_selected_steps: Cell::new(0),
}
}
pub(in crate::execution::storage) fn max_next_offset(&self) -> NavigationOffset {
self.stream.navigation_offsets().next()
}
pub(in crate::execution::storage) fn tracks_unmatched_rows(&self) -> bool {
matches!(
self.stream.empty_matches_mode(),
EmptyMatchesMode::WithUnmatched
)
}
#[cfg(test)]
pub(crate) fn selected_path_validator(
&self,
partition: &Range<usize>,
global_offset: usize,
collection_rows: usize,
fill_order: SelectedPathFillOrder,
) -> Result<SelectedPathValidator<'_>> {
self.selected_path_validator_for_automaton(
&self.automaton,
partition,
global_offset,
collection_rows,
fill_order,
)
}
pub(crate) fn selected_path_validator_for_automaton<'a>(
&'a self,
automaton: &'a CompiledAutomaton,
partition: &Range<usize>,
global_offset: usize,
collection_rows: usize,
fill_order: SelectedPathFillOrder,
) -> Result<SelectedPathValidator<'a>> {
if automaton.num_symbols() != self.automaton.num_symbols() {
return datafusion::common::internal_err!(
"selected runtime graph changed the output symbol domain"
);
}
let extent = validate_emission_extent(partition, global_offset, collection_rows)?;
Ok(SelectedPathValidator::new(
automaton,
self.stream.empty_matches_mode(),
self.emit_sequence_numbers,
extent,
fill_order,
#[cfg(test)]
SelectedPathCheckCounters {
paths: Some(&self.checked_selected_paths),
steps: Some(&self.checked_selected_steps),
},
))
}
#[cfg(test)]
pub(in crate::execution::storage) fn path_validation_observation(
&self,
) -> (usize, usize) {
(
self.checked_selected_paths.get(),
self.checked_selected_steps.get(),
)
}
pub(in crate::execution::storage) fn begin_match_rows(
&self,
extent: ValidatedEmissionExtent,
facts: ValidatedPathFacts,
match_number: i64,
include_halo: bool,
) -> Result<MatchRowProgress> {
let bounds = facts.physical_bounds;
let first = absolute_row_to_usize(bounds.first, "first matched path row")?;
let last = absolute_row_to_usize(bounds.last, "last matched path row")?;
let include_halo = include_halo && self.stream.emits_navigation_buffer_rows();
let offsets = self.stream.navigation_offsets();
let previous_start = first
.saturating_sub(offsets.previous().as_usize())
.max(extent.partition_start)
.max(extent.global_offset)
.min(first);
let next_start = last.checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE NEXT buffer start overflow".into(),
)
})?;
let available = extent
.partition_end
.min(extent.input_end)
.saturating_sub(next_start);
let next_end = next_start + offsets.next().as_usize().min(available);
Ok(MatchRowProgress {
phase: if include_halo && previous_start < first {
MatchRowPhase::Previous
} else {
MatchRowPhase::Path
},
previous: previous_start..first,
path_index: 0,
path_end: facts.path_len,
sequence_number: 0,
last_emitted_row: None,
next: next_start..if include_halo { next_end } else { next_start },
next_start,
global_offset: extent.global_offset,
match_number,
emitted_any_row: false,
})
}
pub(in crate::execution::storage) fn encode_match_chunk<'a>(
&'a self,
progress: &mut MatchRowProgress,
path: &[PathStep],
step_limit: usize,
emit: &mut impl FnMut(EncodedOutputRow<'a>, &mut CoarseWorkBatch<'_>) -> Result<()>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
debug_assert!(step_limit > 0);
match progress.phase {
MatchRowPhase::Previous => {
self.encode_previous_rows(progress, step_limit, emit, completed)
}
MatchRowPhase::Path => {
self.encode_path_rows(progress, path, step_limit, emit, completed)
}
MatchRowPhase::Next => {
self.encode_next_rows(progress, step_limit, emit, completed)
}
MatchRowPhase::Done => {
internal_err!("MATCH_RECOGNIZE completed row encoding resumed")
}
}
}
fn encode_previous_rows<'a>(
&'a self,
progress: &mut MatchRowProgress,
step_limit: usize,
emit: &mut impl FnMut(EncodedOutputRow<'a>, &mut CoarseWorkBatch<'_>) -> Result<()>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
let mut work = CoarseWorkBatch::new(completed);
let first = progress.previous.end;
for row_idx in progress.previous.by_ref().take(step_limit) {
let distance = first.checked_sub(row_idx).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE PREV buffer distance underflow".to_string(),
)
})?;
let distance = i64::try_from(distance).map_err(|_| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE PREV distance {distance} cannot be represented as Int64 metadata"
))
})?;
let sequence_number = distance.checked_neg().ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE PREV sequence-number negation overflow".to_string(),
)
})?;
let row = self.buffer_row(row_idx, progress.match_number, sequence_number)?;
emit(row, &mut work)?;
work.complete_one()?;
}
work.finish()?;
if progress.previous.is_empty() {
progress.phase = MatchRowPhase::Path;
}
Ok(())
}
fn encode_path_rows<'a>(
&'a self,
progress: &mut MatchRowProgress,
path: &[PathStep],
step_limit: usize,
emit: &mut impl FnMut(EncodedOutputRow<'a>, &mut CoarseWorkBatch<'_>) -> Result<()>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
let omit_empty_matches =
matches!(self.stream.empty_matches_mode(), EmptyMatchesMode::Omit);
let global_offset = progress.global_offset;
let match_number = progress.match_number;
let mut work = CoarseWorkBatch::new(completed);
let chunk_end = progress
.path_index
.saturating_add(step_limit)
.min(progress.path_end);
for step in &path[progress.path_index..chunk_end] {
progress.path_index += 1;
let step_row = absolute_row_to_usize(step.row, "matched path row")?;
let is_empty_symbol = step.sym.to_index() == Sym::Empty.to_index();
if self.emit_sequence_numbers {
progress.sequence_number =
checked_sequence_successor(progress.sequence_number)?;
}
if omit_empty_matches && is_empty_symbol {
work.complete_one()?;
continue;
}
if progress.last_emitted_row == Some(step_row) && !is_empty_symbol {
work.complete_one()?;
continue;
}
log::debug!(
target: "datafusion_match_recognize::execution::storage::output",
event = "emit_match_row",
match_number,
row:% = step.row,
global_offset;
"emit match row: match_number={}, row={}, global_offset={}",
match_number,
step.row,
global_offset
);
let row = self.matched_row(
step.row,
step_row,
match_number,
progress.sequence_number,
(!is_empty_symbol).then_some(step.sym),
step.excluded,
)?;
emit(row, &mut work)?;
work.complete_one()?;
progress.emitted_any_row = true;
progress.last_emitted_row = Some(step_row);
}
work.finish()?;
if progress.path_index == progress.path_end {
progress.phase = if progress.next.is_empty() {
MatchRowPhase::Done
} else {
MatchRowPhase::Next
};
}
Ok(())
}
pub(in crate::execution::storage) fn empty_row(
&self,
match_number: i64,
position: usize,
partition: Range<usize>,
) -> Result<Option<EncodedOutputRow<'_>>> {
if !self.stream.emits_virtual_empty_match() {
return Ok(None);
}
if position < partition.start || position >= partition.end {
return internal_err!(
"MATCH_RECOGNIZE empty match position {position} is outside partition {}..{}",
partition.start,
partition.end
);
}
let sequence_number = i64::from(self.emit_sequence_numbers);
self.matched_row(
absolute_row_from_usize(position, "empty match representative")?,
position,
match_number,
sequence_number,
None,
false,
)
.map(Some)
}
fn encode_next_rows<'a>(
&'a self,
progress: &mut MatchRowProgress,
step_limit: usize,
emit: &mut impl FnMut(EncodedOutputRow<'a>, &mut CoarseWorkBatch<'_>) -> Result<()>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
let mut work = CoarseWorkBatch::new(completed);
for row_idx in progress.next.by_ref().take(step_limit) {
if row_idx >= progress.global_offset {
let sequence_number = next_buffer_sequence_number(
self.stream.navigation_offsets().next(),
row_idx - progress.next_start,
)?;
let row =
self.buffer_row(row_idx, progress.match_number, sequence_number)?;
emit(row, &mut work)?;
}
work.complete_one()?;
}
work.finish()?;
if progress.next.is_empty() {
progress.phase = MatchRowPhase::Done;
}
Ok(())
}
#[inline(always)]
fn matched_row<'a>(
&'a self,
absolute_row: AbsoluteRow,
source_floor: usize,
match_number: i64,
sequence_number: i64,
classifier: Option<Sym>,
excluded: bool,
) -> Result<EncodedOutputRow<'a>> {
Ok(EncodedOutputRow {
row_ref: absolute_row,
source_floor,
classifier: classifier
.map(|symbol| self.classifier(symbol))
.transpose()?,
match_number,
sequence_number,
excluded,
matched_physical_row: Some(absolute_row),
})
}
fn buffer_row(
&self,
row_idx: usize,
match_number: i64,
sequence_number: i64,
) -> Result<EncodedOutputRow<'_>> {
Ok(EncodedOutputRow {
row_ref: absolute_row_from_usize(row_idx, "pending output row")?,
source_floor: row_idx,
classifier: None,
match_number,
sequence_number,
excluded: false,
matched_physical_row: None,
})
}
#[inline]
pub(in crate::execution::storage) fn classifier(
&self,
symbol: Sym,
) -> Result<EncodedClassifier<'_>> {
lookup_classifier(self.automaton.id_to_symbol(), symbol)
}
}
#[inline]
fn lookup_classifier(
names: &[Option<String>],
symbol: Sym,
) -> Result<EncodedClassifier<'_>> {
let name = names
.get(symbol.to_index())
.and_then(Option::as_deref)
.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE selected path references unknown classifier symbol ID {}",
symbol.to_index()
))
})?;
Ok(EncodedClassifier { symbol, name })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{
MatchMetadataColumn, MatchRecognizeOutputSpec, NormalizedPattern, Pattern,
RowsPerMatch, Symbol,
};
use crate::execution::matching::ExecutableOutputPlan;
use datafusion::arrow::datatypes::Schema;
fn encoder(
navigation_offsets: NavigationOffsets,
end_anchor: bool,
) -> MatchRowsEncoder {
let mut pattern = Pattern::Symbol(Symbol::Named("A".into()));
if end_anchor {
pattern = Pattern::Concat(vec![pattern, Pattern::Symbol(Symbol::End)]);
}
let pattern = NormalizedPattern::Ast(pattern);
let compiled =
Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()]).unwrap());
let output_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
Vec::new(),
vec![MatchMetadataColumn::MatchSequenceNumber],
Vec::new(),
navigation_offsets,
);
let resolved_output = ExecutableOutputPlan::try_rows(
&Schema::empty(),
output_spec,
Arc::from([]),
RowsPerMatch::AllRows(EmptyMatchesMode::Show),
compiled.as_ref(),
)
.unwrap();
MatchRowsEncoder::new(compiled, &resolved_output)
}
#[test]
fn encoding_chunks_bound_halos_and_non_emitting_path_steps() {
let encoder = encoder(NavigationOffsets::try_from_raw(300, 300).unwrap(), true);
let extent = validate_emission_extent(&(0..1200), 0, 1500).unwrap();
let path = (300..900)
.flat_map(|row| {
let step = PathStep {
row: AbsoluteRow::new(row),
sym: Sym::from_index(1),
excluded: true,
};
[step, step]
})
.collect::<Vec<_>>();
for (fill_order, step_limit) in [
(SelectedPathFillOrder::Forward, 1),
(SelectedPathFillOrder::Reverse, 256),
(SelectedPathFillOrder::Forward, 8192),
] {
let mut validator = encoder
.selected_path_validator(&(0..1200), 0, 1500, fill_order)
.unwrap();
for index in 0..path.len() {
let index = match fill_order {
SelectedPathFillOrder::Forward => index,
SelectedPathFillOrder::Reverse => path.len() - 1 - index,
};
validator.observe(path[index]).unwrap();
}
let checked = validator
.finish(
path.clone(),
AbsoluteRow::new(300),
AbsoluteRow::new(899),
AbsoluteRow::new(1200),
)
.unwrap();
let validated = checked.validated_facts(extent).unwrap();
let mut progress = encoder
.begin_match_rows(extent, validated, 7, true)
.unwrap();
let mut rows = Vec::new();
let mut calls = 0;
let mut visited = 0;
while progress.phase() != MatchRowPhase::Done {
let mut chunk_work = 0;
let rows_before = rows.len();
encoder
.encode_match_chunk(
&mut progress,
&path,
step_limit,
&mut |row, _| {
rows.push(row);
Ok(())
},
&mut |units| {
chunk_work += units;
Ok(())
},
)
.unwrap();
assert!(chunk_work <= step_limit);
if step_limit == 1 {
assert!(rows.len() - rows_before <= 1);
}
visited += chunk_work;
calls += 1;
}
if step_limit == 1 {
assert!(calls >= 1200);
} else if step_limit == 256 {
assert_eq!(calls, 9);
} else {
assert_eq!(calls, 3);
}
assert_eq!(visited, 1800, "deduplicated path steps still consume work");
assert_eq!(rows.len(), 1200);
for (index, row) in rows.iter().enumerate() {
assert_eq!(row.row_ref, AbsoluteRow::new(index as u64));
}
assert_eq!(rows[0].sequence_number, -300);
assert_eq!(rows[299].sequence_number, -1);
assert!(rows[300..900].iter().all(|row| row.excluded));
assert_eq!(rows[300].sequence_number, 1);
assert_eq!(rows[899].sequence_number, 1199);
assert_eq!(
rows[1199].sequence_number,
next_buffer_sequence_number(NavigationOffset::try_new(300).unwrap(), 299)
.unwrap()
);
}
}
#[test]
fn empty_halo_ranges_start_and_finish_with_the_path() {
let encoder = encoder(NavigationOffsets::try_from_raw(2, 2).unwrap(), false);
let extent = validate_emission_extent(&(0..1), 0, 1).unwrap();
let path = [PathStep {
row: AbsoluteRow::ZERO,
sym: Sym::from_index(1),
excluded: false,
}];
let mut validator = encoder
.selected_path_validator(&(0..1), 0, 1, SelectedPathFillOrder::Forward)
.unwrap();
validator.observe(path[0]).unwrap();
let checked = validator
.finish(
path.to_vec(),
AbsoluteRow::ZERO,
AbsoluteRow::ZERO,
AbsoluteRow::ZERO,
)
.unwrap();
let facts = checked.validated_facts(extent).unwrap();
let mut progress = encoder.begin_match_rows(extent, facts, 1, true).unwrap();
assert_eq!(progress.phase(), MatchRowPhase::Path);
let mut emitted = 0;
let mut work = 0;
encoder
.encode_match_chunk(
&mut progress,
&path,
1,
&mut |_, _| {
emitted += 1;
Ok(())
},
&mut |units| {
work += units;
Ok(())
},
)
.unwrap();
assert_eq!((emitted, work), (1, 1));
assert_eq!(progress.phase(), MatchRowPhase::Done);
}
#[test]
fn descriptors_cover_classified_excluded_buffer_and_virtual_rows() {
let encoder = encoder(NavigationOffsets::try_from_raw(2, 2).unwrap(), false);
let extent = validate_emission_extent(&(0..5), 0, 5).unwrap();
let path = [PathStep {
row: AbsoluteRow::new(2),
sym: Sym::from_index(1),
excluded: true,
}];
let mut validator = encoder
.selected_path_validator(&(0..5), 0, 5, SelectedPathFillOrder::Forward)
.unwrap();
validator.observe(path[0]).unwrap();
let row = AbsoluteRow::new(2);
let checked = validator.finish(path.to_vec(), row, row, row).unwrap();
let validated = checked.validated_facts(extent).unwrap();
let mut rows = Vec::new();
let mut progress = encoder
.begin_match_rows(extent, validated, 7, true)
.unwrap();
while progress.phase() != MatchRowPhase::Done {
encoder
.encode_match_chunk(
&mut progress,
&path,
256,
&mut |row, _| {
rows.push(row);
Ok(())
},
&mut |_| Ok(()),
)
.unwrap();
}
rows.push(encoder.empty_row(8, 4, 0..5).unwrap().unwrap());
let physical = AbsoluteRow::new;
let actual: Vec<_> = rows
.iter()
.map(|row| {
(
row.row_ref,
row.match_number,
row.sequence_number,
row.classifier.map(|classifier| classifier.name),
row.excluded,
)
})
.collect();
assert_eq!(
actual,
[
(physical(0), 7, -2, None, false),
(physical(1), 7, -1, None, false),
(physical(2), 7, 1, Some("A"), true),
(physical(3), 7, i64::MAX - 2, None, false),
(physical(4), 7, i64::MAX - 1, None, false),
(physical(4), 8, 1, None, false),
]
);
assert_eq!(rows[2].matched_physical_row, Some(AbsoluteRow::new(2)));
assert_eq!(rows[5].source_floor, 4);
assert_eq!(rows[5].matched_physical_row, Some(AbsoluteRow::new(4)));
assert!(encoder.empty_row(9, 5, 0..5).is_err());
}
#[test]
fn next_sequence_categories_cover_small_and_platform_maximum_offsets() {
for (raw, first) in [
(1, i64::MAX - 1),
(300, i64::MAX - 300),
(
crate::core::MAX_NAVIGATION_OFFSET,
MAX_VALID_MATCH_SEQUENCE_NUMBER + 1,
),
] {
if let Some(offset) = NavigationOffset::try_from_u64(raw) {
assert_eq!(next_buffer_sequence_number(offset, 0).unwrap(), first);
assert_eq!(
next_buffer_sequence_number(offset, offset.as_usize() - 1).unwrap(),
i64::MAX - 1
);
}
}
}
}