use crate::execution::storage::PendingOutput;
use std::collections::VecDeque;
use std::ops::Range;
use std::sync::Arc;
#[cfg(test)]
use datafusion::arrow::datatypes::Schema;
#[cfg(test)]
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;
#[cfg(test)]
use crate::core::MatchRecognizeOutputSpec;
use crate::core::{AbsoluteRow, NavigationOffset};
#[cfg(test)]
use crate::core::{EmptyMatchesMode, MatchMetadataColumn, RowsPerMatch};
use crate::execution::common::coordinates::{
absolute_row_to_usize, checked_match_number,
};
use crate::execution::common::memory::try_reserve_accounted;
use crate::execution::common::progress::{COARSE_WORK_BATCH_SIZE, CoarseWorkBatch};
use crate::execution::matching::path::PathStep;
use crate::execution::matching::row_loop::lane_scan::ClassifierDemand;
use crate::execution::matching::{
ExecutableDirectCountSummary, ExecutableOutputFinalizer, ExecutableOutputPlan,
};
use crate::execution::storage::collection::BatchCollection;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
pub(crate) use crate::execution::storage::output::{
CheckedSelectedPath, SelectedPathFillOrder, SelectedPathValidation,
SelectedPathValidator,
};
use crate::execution::storage::output::{
EncodedOutputRow, MatchRowPhase, MatchRowProgress, MatchRowsEncoder,
OutputBatchBuilder, VIRTUAL_DEFAULT_COORD, validate_emission_extent,
};
use crate::execution::storage::row_presence::RowPresence;
use crate::nfa::CompiledAutomaton;
use crate::planning::logical::MetadataEndpoint;
mod compact;
mod expanded;
mod reduction;
pub(crate) use compact::{CompactMatchPreparation, DirectPublicationBatch};
pub(crate) use expanded::{ExpandedMatchPreparation, SelectedPathFill};
use reduction::PendingSummaryRow;
fn checked_match_count_successor(matches_emitted: usize) -> Result<usize> {
matches_emitted.checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE emitted-match counter overflow".to_string(),
)
})
}
pub(crate) struct PreparedMatchEmission {
emitted: bool,
}
pub(crate) struct MatchEmissionProgress {
emits_match: bool,
state: MatchEmissionState,
}
enum MatchEmissionState {
Physical {
rows: MatchRowProgress,
representative: bool,
pending_row: Option<PendingSummaryRow>,
},
Done,
}
pub(crate) struct MatchEmissionContext<'a> {
pub(crate) partition: Range<usize>,
pub(crate) global_offset: usize,
pub(crate) batches: &'a BatchCollection,
pub(crate) pending_output: &'a mut PendingOutput,
pub(crate) history: Option<&'a SharedHistoryBuffer>,
}
impl MatchEmissionContext<'_> {
pub(in crate::execution) fn reborrow(&mut self) -> MatchEmissionContext<'_> {
MatchEmissionContext {
partition: self.partition.clone(),
global_offset: self.global_offset,
batches: self.batches,
pending_output: self.pending_output,
history: self.history,
}
}
}
pub(super) enum EdgeScratchState {
None,
First { seen: usize },
Last { ring: VecDeque<u64>, offset: usize },
}
impl EdgeScratchState {
fn reset(&mut self) {
match self {
Self::None => {}
Self::First { seen } => *seen = 0,
Self::Last { ring, .. } => ring.clear(),
}
}
}
#[allow(clippy::large_enum_variant)]
enum OutputFinalizerRuntime {
Rows,
DirectCounts {
summaries: Arc<[ExecutableDirectCountSummary]>,
symbol_demand: ClassifierDemand,
has_reductions: bool,
needs_edge_finalization: bool,
scratch: Vec<u64>,
edge_states: Vec<EdgeScratchState>,
_scratch_memory: MemoryReservation,
},
}
pub struct MatchAccumulator {
encoder: MatchRowsEncoder,
supports_compact_selected: bool,
row_presence: RowPresence,
output: OutputBatchBuilder,
finalizer: OutputFinalizerRuntime,
matches_emitted: usize,
pub(crate) max_processed_row: usize,
#[cfg(test)]
fail_match_preparation: bool,
#[cfg(test)]
cancel_match_publication: bool,
}
impl MatchAccumulator {
#[cfg(test)]
pub(crate) fn try_new_unbounded(
automaton: Arc<CompiledAutomaton>,
flush_threshold: usize,
output_plan: Arc<ExecutableOutputPlan>,
) -> Result<Self> {
Self::try_new(
automaton,
flush_threshold,
output_plan,
crate::execution::common::memory::new_unbounded_state_memory().new_empty(),
crate::execution::common::memory::new_unbounded_state_memory().new_empty(),
)
}
pub(crate) fn try_new(
automaton: Arc<CompiledAutomaton>,
flush_threshold: usize,
output_plan: Arc<ExecutableOutputPlan>,
presence_memory: MemoryReservation,
summary_memory: MemoryReservation,
) -> Result<Self> {
let row_presence = RowPresence::try_new(presence_memory)?;
let stream = Arc::clone(output_plan.stream());
let encoder = MatchRowsEncoder::new(Arc::clone(&automaton), &output_plan);
let (output, finalizer) = match output_plan.finalizer() {
ExecutableOutputFinalizer::Rows => (
OutputBatchBuilder::try_new(stream, flush_threshold, 0, summary_memory)?,
OutputFinalizerRuntime::Rows,
),
ExecutableOutputFinalizer::DirectCounts { summaries } => {
let scratch_memory = summary_memory;
let mut scratch = Vec::new();
try_reserve_accounted(
&mut scratch,
&scratch_memory,
summaries.len(),
"count-summary scratch",
)?;
scratch.resize(summaries.len(), 0);
let mut has_offset_edges = false;
let mut needs_edge_finalization = false;
let mut has_reductions = false;
let mut packed_mask = 0u64;
let mut needs_runs = false;
let mut edge_states = Vec::new();
for (index, summary) in summaries.iter().enumerate() {
let edge = summary.edge();
let offset_edge = edge.filter(|e| e.logical_offset > 0);
let reduction = summary.reduction().is_some();
has_reductions |= reduction;
needs_edge_finalization |= edge.is_some_and(|e| {
e.physical_shift != 0 || e.default_value.is_some()
});
if let Some(symbol) = summary.symbol_id() {
match symbol.packed_membership_bit() {
Some(bit) => packed_mask |= bit,
None => needs_runs = true,
}
needs_runs |= reduction || offset_edge.is_some();
} else {
needs_runs |= matches!(
summary.metadata(),
Some(MetadataEndpoint::Classifier { .. })
);
}
if offset_edge.is_some() && !has_offset_edges {
try_reserve_accounted(
&mut edge_states,
&scratch_memory,
summaries.len(),
"offset edge summary states",
)?;
edge_states.resize_with(index, || EdgeScratchState::None);
has_offset_edges = true;
}
if has_offset_edges {
let state = match offset_edge {
Some(edge) if edge.last => {
let cap = edge.logical_offset + 1;
let bytes = cap
.checked_mul(size_of::<u64>())
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE edge ring capacity overflow"
.into(),
)
})?;
scratch_memory.try_grow(bytes)?;
let mut ring = VecDeque::new();
ring.try_reserve_exact(cap).map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE edge ring could not reserve {cap} entries: {error}"
))
})?;
let actual_bytes = ring.capacity() * size_of::<u64>();
if actual_bytes > bytes {
scratch_memory.try_grow(actual_bytes - bytes)?;
} else {
scratch_memory.shrink(bytes - actual_bytes);
}
EdgeScratchState::Last {
ring,
offset: edge.logical_offset,
}
}
Some(_) => EdgeScratchState::First { seen: 0 },
None => EdgeScratchState::None,
};
edge_states.push(state);
}
}
(
OutputBatchBuilder::try_new_direct_counts(
stream,
Arc::clone(summaries),
Arc::clone(&automaton),
flush_threshold,
0,
scratch_memory.new_empty(),
)?,
OutputFinalizerRuntime::DirectCounts {
summaries: Arc::clone(summaries),
has_reductions,
needs_edge_finalization,
symbol_demand: if needs_runs {
if packed_mask != 0 {
ClassifierDemand::AllWithCaptures(packed_mask)
} else {
ClassifierDemand::All
}
} else {
ClassifierDemand::Symbols(packed_mask)
},
scratch,
edge_states,
_scratch_memory: scratch_memory,
},
)
}
};
let supports_compact_selected = encoder.supports_compact_output();
Ok(Self {
encoder,
supports_compact_selected,
row_presence,
output,
finalizer,
matches_emitted: 0,
max_processed_row: 0,
#[cfg(test)]
fail_match_preparation: false,
#[cfg(test)]
cancel_match_publication: false,
})
}
#[inline]
pub fn len(&self) -> usize {
self.output.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.output.is_empty()
}
pub(crate) fn requires_partition_output_flush(&self) -> bool {
self.encoder.tracks_unmatched_rows()
}
#[cfg(test)]
pub(crate) fn selected_path_validator(
&self,
partition: &Range<usize>,
global_offset: usize,
collection_rows: usize,
fill_order: SelectedPathFillOrder,
) -> Result<SelectedPathValidator<'_>> {
self.encoder.selected_path_validator(
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>> {
self.encoder.selected_path_validator_for_automaton(
automaton,
partition,
global_offset,
collection_rows,
fill_order,
)
}
fn begin_checked_match(
&mut self,
match_id: u64,
path: &CheckedSelectedPath,
emission: &MatchEmissionContext<'_>,
) -> Result<MatchEmissionProgress> {
let extent = validate_emission_extent(
&emission.partition,
emission.global_offset,
emission.batches.num_rows(),
)?;
let facts = path.validated_facts(extent)?;
let match_number = checked_match_number(match_id)?;
let emits_match = facts.will_emit_physical_row;
if emits_match {
checked_match_count_successor(self.matches_emitted)?;
}
#[cfg(test)]
self.fail_match_preparation_before_mutation()?;
let rows = match &mut self.finalizer {
OutputFinalizerRuntime::DirectCounts {
summaries,
edge_states,
..
} => {
for state in edge_states.iter_mut() {
state.reset();
}
let mut rows =
self.encoder
.begin_match_rows(extent, facts, match_number, false)?;
if summaries.is_empty() {
rows.retain_first_path_row();
}
rows
}
OutputFinalizerRuntime::Rows => {
let include_halo = emits_match && !path.is_empty();
self.encoder.begin_match_rows(
extent,
facts,
match_number,
include_halo,
)?
}
};
Ok(MatchEmissionProgress {
emits_match,
state: MatchEmissionState::Physical {
rows,
representative: false,
pending_row: None,
},
})
}
#[cfg(test)]
fn prepare_match_chunk(
&mut self,
progress: &mut MatchEmissionProgress,
path: &CheckedSelectedPath,
emission: MatchEmissionContext<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<PreparedMatchEmission>> {
self.prepare_path_chunk(progress, path.steps(), emission, completed)
}
#[cfg(test)]
pub(crate) fn prepare_checked_match_with_work(
&mut self,
match_id: u64,
path: &CheckedSelectedPath,
mut emission: MatchEmissionContext<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<PreparedMatchEmission> {
let mut progress = self.begin_checked_match(match_id, path, &emission)?;
loop {
if let Some(prepared) = self.prepare_match_chunk(
&mut progress,
path,
emission.reborrow(),
completed,
)? {
return Ok(prepared);
}
}
}
fn prepare_path_chunk(
&mut self,
progress: &mut MatchEmissionProgress,
path: &[PathStep],
mut emission: MatchEmissionContext<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<PreparedMatchEmission>> {
let MatchEmissionContext {
partition,
global_offset,
batches,
pending_output,
history,
} = emission.reborrow();
let MatchEmissionState::Physical {
rows,
representative,
pending_row,
} = &mut progress.state
else {
return internal_err!("MATCH_RECOGNIZE completed match preparation resumed");
};
if let Some(row) = pending_row {
let OutputFinalizerRuntime::DirectCounts {
summaries,
scratch,
edge_states,
..
} = &mut self.finalizer
else {
return internal_err!("missing selected summary state");
};
if row.advance(
&mut self.output,
summaries,
scratch,
edge_states,
batches,
global_offset,
history,
completed,
)? {
*pending_row = None;
}
return Ok(None);
}
if rows.phase() != MatchRowPhase::Done {
match &mut self.finalizer {
OutputFinalizerRuntime::DirectCounts {
summaries,
scratch,
edge_states,
has_reductions,
..
} => {
let summary_width = summaries.len().max(1);
let step_limit = if *has_reductions {
(COARSE_WORK_BATCH_SIZE / summary_width).max(1)
} else {
(self.output.batch_size().max(COARSE_WORK_BATCH_SIZE)
/ summary_width)
.max(1)
};
self.encoder.encode_match_chunk(
rows,
path,
step_limit,
&mut |row, work| {
let first = !*representative;
if first {
self.output.reserve_row(row)?;
self.output.begin_reserved_row(row);
*representative = true;
}
let classifier =
row.classifier_symbol().map(|symbol| symbol.to_index());
if let Some((absolute, classifier)) =
row.matched_physical_row.zip(classifier)
{
if *has_reductions {
let mut fields = PendingSummaryRow {
absolute,
classifier,
sequence: row.sequence_number,
field: 0,
};
if !fields.advance(
&mut self.output,
summaries,
scratch,
edge_states,
batches,
global_offset,
history,
work.reporter(),
)? {
*pending_row = Some(fields);
}
} else {
update_direct_summaries(
summaries,
scratch,
edge_states,
classifier,
|previous, summary, edge_state| {
row_summary(
previous,
summary,
edge_state,
classifier,
row.sequence_number,
absolute,
)
},
&mut || work.complete_one(),
)?;
}
}
if first {
self.output.append_classifier_fields(classifier, work)?;
}
Ok(())
},
completed,
)?;
if pending_row.is_some() {
return Ok(None);
}
}
OutputFinalizerRuntime::Rows => {
self.output.maybe_flush_with_work(
batches,
global_offset,
history,
pending_output,
completed,
)?;
let output = &mut self.output;
let row_presence = &mut self.row_presence;
let track_presence = self.encoder.tracks_unmatched_rows();
self.encoder.encode_match_chunk(
rows,
path,
output.rows_until_flush(),
&mut |row, work| {
begin_encoded_row(
output,
row_presence,
track_presence,
row,
work,
)?;
output.append_classifier_fields(
row.classifier_symbol().map(|symbol| symbol.to_index()),
work,
)?;
Ok(())
},
completed,
)?;
self.output.maybe_flush_with_work(
batches,
global_offset,
history,
pending_output,
completed,
)?;
}
}
if rows.phase() != MatchRowPhase::Done {
return Ok(None);
}
}
if matches!(self.finalizer, OutputFinalizerRuntime::DirectCounts { .. })
&& !*representative
{
return internal_err!(
"MATCH_RECOGNIZE count-summary path emitted no representative row"
);
}
let emitted = rows.emitted_any_row();
if emitted && !progress.emits_match {
return internal_err!(
"MATCH_RECOGNIZE path emitted a row after prevalidation classified it as non-emitting"
);
}
self.finish_direct_summaries(&partition, completed)?;
let prepared = self.finalize_match(emitted, emission, completed)?;
progress.state = MatchEmissionState::Done;
Ok(Some(prepared))
}
fn finish_direct_summaries(
&mut self,
partition: &Range<usize>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
if let OutputFinalizerRuntime::DirectCounts {
summaries,
scratch,
edge_states,
needs_edge_finalization,
..
} = &mut self.finalizer
{
for state in edge_states.iter_mut() {
state.reset();
}
let mut min_floor = usize::MAX;
finalize_direct_edge_coords(
summaries,
scratch,
*needs_edge_finalization,
partition,
&mut min_floor,
)?;
if min_floor < usize::MAX {
self.output.retain_source_floor(min_floor);
}
self.output.reserve_summary(scratch.len())?;
self.output.append_summary(scratch, completed)?;
}
Ok(())
}
fn finalize_match(
&mut self,
emitted: bool,
emission: MatchEmissionContext<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<PreparedMatchEmission> {
self.output.maybe_flush_with_work(
emission.batches,
emission.global_offset,
emission.history,
emission.pending_output,
completed,
)?;
Ok(PreparedMatchEmission { emitted })
}
pub(crate) fn try_prepare_empty_in_batch(
&mut self,
match_id: u64,
position: usize,
partition: Range<usize>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<PreparedMatchEmission>> {
if !matches!(self.finalizer, OutputFinalizerRuntime::Rows)
|| self.output.rows_until_flush() <= 1
{
return Ok(None);
}
debug_assert!(self.encoder.supports_compact_output());
debug_assert!((partition.start..partition.end).contains(&position));
#[cfg(test)]
self.fail_match_preparation_before_mutation()?;
completed(1)?;
self.prepare_empty_match(
checked_match_number(match_id)?,
position,
partition,
completed,
)
.map(Some)
}
pub(crate) fn try_publish_empty_in_batch(
&mut self,
match_id: u64,
position: usize,
partition: Range<usize>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<bool> {
#[cfg(test)]
self.check_publication_cancellation()?;
let Some(prepared) =
self.try_prepare_empty_in_batch(match_id, position, partition, completed)?
else {
return Ok(false);
};
self.commit_prepared_match(prepared);
Ok(true)
}
fn prepare_empty_match(
&mut self,
match_number: i64,
position: usize,
partition: Range<usize>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<PreparedMatchEmission> {
let Some(row) = self.encoder.empty_row(match_number, position, partition)? else {
return Ok(PreparedMatchEmission { emitted: false });
};
checked_match_count_successor(self.matches_emitted)?;
debug_assert!(matches!(self.finalizer, OutputFinalizerRuntime::Rows));
let mut work = CoarseWorkBatch::new(completed);
begin_encoded_row(
&mut self.output,
&mut self.row_presence,
self.encoder.tracks_unmatched_rows(),
row,
&mut work,
)?;
self.output.append_classifier_fields(None, &mut work)?;
work.finish()?;
Ok(PreparedMatchEmission { emitted: true })
}
fn commit_prepared_match(&mut self, prepared: PreparedMatchEmission) {
if prepared.emitted {
self.matches_emitted += 1;
}
}
pub(crate) fn prepare_match_publication(
&mut self,
staged_output: &PendingOutput,
pending_output: &mut PendingOutput,
) -> Result<()> {
#[cfg(test)]
self.check_publication_cancellation()?;
pending_output
.prepare_append(staged_output)
.map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE pending output could not reserve {} staged match batches: {error}",
staged_output.len()
))
})
}
pub(crate) fn publish_prepared_match(
&mut self,
prepared: PreparedMatchEmission,
staged_output: &mut PendingOutput,
pending_output: &mut PendingOutput,
) {
pending_output.append(staged_output);
self.commit_prepared_match(prepared)
}
#[cfg(test)]
fn check_publication_cancellation(&mut self) -> Result<()> {
if std::mem::take(&mut self.cancel_match_publication) {
return internal_err!(
"MATCH_RECOGNIZE execution cancelled during selected-match publication"
);
}
Ok(())
}
#[cfg(test)]
pub(crate) fn cancel_next_match_publication(&mut self) {
self.cancel_match_publication = true;
}
#[cfg(test)]
pub(crate) fn path_validation_observation(&self) -> (usize, usize) {
self.encoder.path_validation_observation()
}
#[cfg(test)]
fn fail_match_preparation_before_mutation(&mut self) -> Result<()> {
if std::mem::take(&mut self.fail_match_preparation) {
return internal_err!(
"injected output failure before selected-match mutation"
);
}
Ok(())
}
#[inline]
pub fn take_matches_total(&mut self) -> usize {
let m = self.matches_emitted;
self.matches_emitted = 0;
m
}
pub fn min_buffered_row(&self) -> Option<usize> {
self.output.min_buffered_row()
}
pub(crate) fn max_next_offset(&self) -> NavigationOffset {
self.encoder.max_next_offset()
}
pub(crate) fn min_unfinalized_presence_row(&self) -> Result<Option<usize>> {
if !self.encoder.tracks_unmatched_rows() {
return Ok(None);
}
absolute_row_to_usize(
self.row_presence.first_unfinalized_row(),
"unfinalized row-presence floor",
)
.map(Some)
}
#[cfg(test)]
pub(crate) fn validate_no_pending_builder_tail(&self) -> Result<()> {
self.output.validate_no_pending_builder_tail()
}
#[cfg(test)]
fn validate_pending_metadata_len(&self, expected: usize) -> Result<()> {
self.output.validate_pending_metadata_len(expected)
}
#[cfg(test)]
fn inject_pending_input(
&mut self,
row: AbsoluteRow,
source_floor: usize,
match_number: i64,
) {
self.output
.inject_pending_input(row, source_floor, match_number);
}
}
#[inline(always)]
fn update_direct_summaries(
summaries: &[ExecutableDirectCountSummary],
values: &mut [u64],
edge_states: &mut [EdgeScratchState],
classifier: usize,
mut update: impl FnMut(
u64,
&ExecutableDirectCountSummary,
Option<&mut EdgeScratchState>,
) -> Result<u64>,
completed: &mut impl FnMut() -> Result<()>,
) -> Result<()> {
debug_assert_eq!(values.len(), summaries.len());
for (index, (value, summary)) in values.iter_mut().zip(summaries).enumerate() {
if summary
.symbol_id()
.is_none_or(|id| id.index() == classifier)
{
*value = update(*value, summary, edge_states.get_mut(index))?;
}
completed()?;
}
Ok(())
}
pub(super) fn row_summary(
previous: u64,
summary: &ExecutableDirectCountSummary,
edge_state: Option<&mut EdgeScratchState>,
symbol: usize,
sequence: i64,
row: AbsoluteRow,
) -> Result<u64> {
if let Some(endpoint) = summary.metadata() {
return Ok(if previous != 0 && !endpoint.last() {
previous
} else {
match endpoint {
MetadataEndpoint::Classifier { .. } => symbol as u64,
MetadataEndpoint::Sequence { .. } => sequence as u64,
}
});
}
if let Some(edge) = summary.edge()
&& edge.logical_offset > 0
{
let pos = row.as_u64() + 1;
return match edge_state {
Some(EdgeScratchState::First { seen }) => {
let current = *seen;
*seen = current.saturating_add(1);
Ok(if current == edge.logical_offset {
pos
} else {
previous
})
}
Some(EdgeScratchState::Last { ring, offset }) => {
let cap = *offset + 1;
if ring.len() == cap {
ring.pop_front();
}
ring.push_back(pos);
Ok(if ring.len() == cap {
*ring.front().expect("populated last ring")
} else {
0
})
}
_ => internal_err!("MATCH_RECOGNIZE offsetted edge missing scratch state"),
};
}
merge_direct_summary(previous, summary, 1, (row, row))
}
pub(super) fn finalize_direct_edge_coords(
summaries: &[ExecutableDirectCountSummary],
scratch: &mut [u64],
needs_edge_finalization: bool,
partition: &Range<usize>,
min_source_floor: &mut usize,
) -> Result<()> {
if !needs_edge_finalization {
return Ok(());
}
for (value, summary) in scratch.iter_mut().zip(summaries) {
let Some(edge) = summary.edge() else {
continue;
};
if edge.physical_shift == 0 && edge.default_value.is_none() {
continue;
}
if *value == 0 {
if edge.default_value.is_some() {
*value = VIRTUAL_DEFAULT_COORD;
}
continue;
}
let anchor =
absolute_row_to_usize(AbsoluteRow::new(*value - 1), "direct edge anchor")?;
let target = if edge.physical_shift < 0 {
usize::try_from(edge.physical_shift.unsigned_abs())
.ok()
.and_then(|delta| anchor.checked_sub(delta))
.filter(|&row| row >= partition.start)
} else if edge.physical_shift > 0 {
usize::try_from(edge.physical_shift)
.ok()
.and_then(|delta| anchor.checked_add(delta))
.filter(|&row| row < partition.end)
} else {
Some(anchor)
};
match target {
Some(row) => {
let coord = (row as u64).checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE shifted direct edge coordinate overflow".into(),
)
})?;
if coord == VIRTUAL_DEFAULT_COORD {
return Err(DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE shifted direct edge coordinate overflow".into(),
));
}
*value = coord;
*min_source_floor = (*min_source_floor).min(row);
}
None => {
*value = if edge.default_value.is_some() {
VIRTUAL_DEFAULT_COORD
} else {
0
};
}
}
}
Ok(())
}
fn merge_direct_summary(
previous: u64,
summary: &ExecutableDirectCountSummary,
multiplicity: u64,
rows: (AbsoluteRow, AbsoluteRow),
) -> Result<u64> {
if let Some(edge) = summary.edge() {
let (first_row, last_row) = rows;
let position = if edge.last { last_row } else { first_row }.as_u64() + 1;
Ok(merge_edge(previous, edge.last, position))
} else {
previous
.checked_add(multiplicity)
.filter(|n| *n <= i64::MAX as u64)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE count-summary result exceeds Int64".into(),
)
})
}
}
fn merge_edge(previous: u64, last: bool, position: u64) -> u64 {
if last {
previous.max(position)
} else if previous == 0 {
position
} else {
previous.min(position)
}
}
#[inline(always)]
fn begin_encoded_row(
output: &mut OutputBatchBuilder,
row_presence: &mut RowPresence,
track_presence: bool,
row: EncodedOutputRow<'_>,
work: &mut CoarseWorkBatch<'_>,
) -> Result<()> {
let saved_class_bytes = output.class_bytes();
output.reserve_row(row)?;
if track_presence
&& let Some(matched_row) = row.matched_physical_row
&& let Err(error) = row_presence.mark_with_work(matched_row, work.reporter())
{
output.rollback_class_bytes(saved_class_bytes);
return Err(error);
}
output.begin_reserved_row(row);
Ok(())
}
#[cfg(test)]
mod row_presence_integration_tests;
impl MatchAccumulator {
#[cfg(test)]
pub(crate) fn record_test_match(
&mut self,
match_id: u64,
steps: &[PathStep],
emission: MatchEmissionContext<'_>,
) -> Result<()> {
let first = steps.first().expect("test_case path must be nonempty").row;
let last = steps.last().expect("test_case path must be nonempty").row;
let mut validator = self.selected_path_validator(
&emission.partition,
emission.global_offset,
emission.batches.num_rows(),
SelectedPathFillOrder::Forward,
)?;
for &step in steps {
validator.observe(step)?;
}
let path = validator.finish(steps.to_vec(), first, last, last)?;
let MatchEmissionContext {
partition,
global_offset,
batches,
pending_output,
history,
} = emission;
let mut staged = pending_output.new_empty();
let prepared = self.prepare_checked_match_with_work(
match_id,
&path,
MatchEmissionContext {
partition,
global_offset,
batches,
pending_output: &mut staged,
history,
},
&mut |_| Ok(()),
)?;
self.prepare_match_publication(&staged, pending_output)?;
self.publish_prepared_match(prepared, &mut staged, pending_output);
Ok(())
}
#[cfg(test)]
pub fn flush_collection(
&mut self,
batches: &BatchCollection,
global_offset: usize,
history: Option<&SharedHistoryBuffer>,
emit_unmatched: bool,
) -> Result<Option<RecordBatch>> {
let mut completed = |_| Ok(());
if emit_unmatched {
let input_end =
global_offset
.checked_add(batches.num_rows())
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE absolute collection end overflow".into(),
)
})?;
let end = self.max_processed_row.min(input_end);
while !self.append_unmatched_prefix_chunk(end, &mut completed)? {}
}
self.flush_collection_with_work(batches, global_offset, history, &mut completed)
}
pub(crate) fn flush_collection_with_work(
&mut self,
batches: &BatchCollection,
global_offset: usize,
history: Option<&SharedHistoryBuffer>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<RecordBatch>> {
self.output
.flush_collection(batches, global_offset, history, completed)
}
pub(crate) fn append_unmatched_prefix_chunk(
&mut self,
end: usize,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<bool> {
if !self.encoder.tracks_unmatched_rows() {
return Ok(true);
}
self.output
.append_unmatched_prefix_chunk(end, &mut self.row_presence, completed)
}
pub(crate) fn output_batch_size(&self) -> usize {
self.output.batch_size()
}
}
#[cfg(test)]
impl MatchAccumulator {
pub(crate) fn fail_next_match_preparation(&mut self) {
self.fail_match_preparation = true;
}
pub(crate) fn row_presence_reserved_bytes(&self) -> usize {
self.row_presence.reserved_bytes()
}
pub(crate) fn set_min_buffered_row_for_test(&mut self, row: Option<usize>) {
self.output.set_min_buffered_row(row);
}
pub(crate) fn set_matches_total_for_test(&mut self, matches: usize) {
self.matches_emitted = matches;
}
}
#[cfg(test)]
mod tests;