use crate::execution::storage::PendingOutput;
use std::num::NonZeroUsize;
use std::ops::Range;
use std::sync::Arc;
use crate::nfa::CompiledAutomaton;
use datafusion::arrow::array::UInt64Array;
#[cfg(test)]
use datafusion::arrow::datatypes::SchemaRef;
#[cfg(test)]
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;
use crate::config::CancellationPolicy;
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::common::progress::ComputeStep;
use crate::execution::identity::{
CollectionHeadGeneration, ExecutionPartitionId, MatchPartitionId, PartitionKeyBinding,
};
use crate::execution::matching::collection::{
ClosedDirectDriver, ClosedSegmentOutcome, SkipDirect,
};
use crate::execution::matching::row_loop::continuation::{
ActiveVariant, NextMatchCursor,
};
use crate::execution::matching::row_loop::lane_scan::direct_payload::{
DirectRouteCounters, direct_quantum,
};
use crate::execution::matching::row_loop::state::{
CollectionWindow, LogicalPartitionBinding, ScanContext, WorkGovernor,
};
use crate::execution::matching::symbol_columns::MultiBatchBoolColumnsBacking;
use crate::execution::matching::{
ExecutableOutputPlan, PartitionKey, PatternMatcher, PreparingPhysicalBoolColumns,
};
use crate::execution::metrics::PatternMetrics;
use crate::execution::storage::accumulator::MatchAccumulator;
#[cfg(test)]
use crate::execution::storage::buffer::PhysicalHeadEnd;
use crate::execution::storage::buffer::{HeadPartitions, HeadSegment, SegmentCursor};
use crate::execution::storage::collection::BatchCollection;
fn candidate_end_row(
core_rows: Option<NonZeroUsize>,
partition: &Range<usize>,
) -> Result<Option<usize>> {
let Some(core_rows) = core_rows else {
return Ok(None);
};
let end = partition
.start
.checked_add(core_rows.get())
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE candidate-start boundary exceeds usize".to_string(),
)
})?;
Ok(Some(end.min(partition.end)))
}
enum PendingPartitionOutput {
StageUnmatched { end: usize, flush_tail: bool },
Flush { then_stage: Option<(usize, bool)> },
}
pub(in crate::execution) struct PreparedPartitions {
generation: CollectionHeadGeneration,
head: HeadPartitions,
cursor: SegmentCursor,
suspended_partition: Option<MatchPartitionId>,
pending_output: Option<PendingPartitionOutput>,
first_new_id: usize,
bool_columns: Arc<MultiBatchBoolColumnsBacking>,
}
pub(crate) struct ComputeRuntime<'a> {
pub(crate) pattern_matcher: &'a mut PatternMatcher,
pub(crate) history_buffer:
Option<&'a crate::execution::storage::history_buffer::SharedHistoryBuffer>,
pub(crate) metrics: &'a PatternMetrics,
pub(crate) pending_output: &'a mut PendingOutput,
}
pub(in crate::execution) struct BoundHead<'a> {
pub(in crate::execution) scan: &'a mut PartitionScan,
pub(in crate::execution) partitions: PreparedPartitions,
stop_on_output: bool,
collection: &'a BatchCollection,
origin: usize,
}
pub(in crate::execution) struct PartitionScan {
scratch: Option<Box<ScanContext>>,
execution_partition_id: ExecutionPartitionId,
state_memory: Arc<MemoryReservation>,
next_partition_id: usize,
base_match_number: u64,
next_head_generation: CollectionHeadGeneration,
flush_threshold: usize,
yield_policy: crate::config::YieldPolicy,
has_partition_by: bool,
candidate_start_core_rows: Option<NonZeroUsize>,
accumulator: MatchAccumulator,
}
impl PartitionScan {
#[cfg(test)]
pub fn try_new_for_test(
_input_schema: SchemaRef,
resolved_output: Arc<ExecutableOutputPlan>,
flush_threshold: usize,
yield_budget: usize,
automaton: Arc<CompiledAutomaton>,
base_match_number: u64,
) -> Result<Self> {
Self::try_new(
resolved_output,
flush_threshold,
crate::config::YieldPolicy::from_test_budget(yield_budget),
automaton,
base_match_number,
false,
None,
ExecutionPartitionId::new(0),
crate::execution::common::memory::new_unbounded_state_memory(),
)
}
#[expect(
clippy::too_many_arguments,
reason = "runtime inputs are independently owned"
)]
pub(crate) fn try_new(
resolved_output: Arc<ExecutableOutputPlan>,
flush_threshold: usize,
yield_policy: crate::config::YieldPolicy,
automaton: Arc<CompiledAutomaton>,
base_match_number: u64,
has_partition_by: bool,
candidate_start_core_rows: Option<NonZeroUsize>,
execution_partition_id: ExecutionPartitionId,
state_memory: Arc<MemoryReservation>,
) -> Result<Self> {
log::debug!(
target: "datafusion_match_recognize::execution::matching",
event = "partition_scan_created",
flush_threshold,
base_match_number;
"created partition scan with threshold {flush_threshold}, base match {base_match_number}"
);
let presence_memory = state_memory.new_empty();
let summary_memory = state_memory.new_empty();
let accumulator = MatchAccumulator::try_new(
automaton,
flush_threshold,
resolved_output,
presence_memory,
summary_memory,
)?;
Ok(Self {
scratch: None,
execution_partition_id,
state_memory,
next_partition_id: 0,
base_match_number,
next_head_generation: CollectionHeadGeneration::new(1),
flush_threshold,
yield_policy,
has_partition_by,
candidate_start_core_rows,
accumulator,
})
}
pub(crate) fn set_yield_policy(&mut self, policy: crate::config::YieldPolicy) {
self.yield_policy = policy;
}
#[cfg(test)]
pub(crate) fn row_presence_reserved_bytes(&self) -> usize {
self.accumulator.row_presence_reserved_bytes()
}
pub fn min_retained_input_row(
&self,
max_prev_offset: usize,
) -> Result<Option<usize>> {
Ok([
self.accumulator.min_buffered_row(),
self.accumulator.min_unfinalized_presence_row()?,
self.min_replay_input_row(max_prev_offset)?,
]
.into_iter()
.flatten()
.min())
}
pub(crate) fn min_replay_input_row(
&self,
max_prev_offset: usize,
) -> Result<Option<usize>> {
self.current_scan()
.map(|scan| scan.min_retained_input_row(max_prev_offset))
.transpose()
}
#[expect(
clippy::too_many_arguments,
reason = "flush borrows independent output subsystems"
)]
fn flush_pending_output(
accumulator: &mut MatchAccumulator,
scratch: Option<&mut ScanContext>,
pattern_matcher: &PatternMatcher,
batch_collection: &BatchCollection,
global_offset: usize,
history_buffer: Option<
&crate::execution::storage::history_buffer::SharedHistoryBuffer,
>,
metrics: &PatternMetrics,
pending_output: &mut PendingOutput,
) -> Result<()> {
if accumulator.is_empty() {
Self::publish_committed_match_telemetry(accumulator, metrics);
return Ok(());
}
pending_output.try_reserve(1).map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE output queue could not reserve one flush batch slot: {error}"
))
})?;
let governor = scratch
.map(|scan| &mut scan.scan_state.governor)
.ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE output flush has no owning scan governor"
.to_string(),
)
})?;
let flush_result = accumulator.flush_collection_with_work(
batch_collection,
global_offset,
history_buffer,
&mut |units| {
governor.record_completed(units, || pattern_matcher.is_aborted())
},
)?;
if let Some(batch) = flush_result {
pending_output.push_back(batch)?;
}
Self::publish_committed_match_telemetry(accumulator, metrics);
Ok(())
}
#[inline]
fn publish_committed_match_telemetry(
accumulator: &mut MatchAccumulator,
metrics: &PatternMetrics,
) {
let matches_emitted = accumulator.take_matches_total();
if matches_emitted != 0 {
metrics.matches_emitted.add(matches_emitted);
}
}
fn take_post_partition_yield_if_due(
scratch: Option<&mut ScanContext>,
accumulator: &mut MatchAccumulator,
yield_policy: crate::config::YieldPolicy,
metrics: &PatternMetrics,
sample_clock: bool,
) -> bool {
let yield_due = scratch.map_or_else(
|| yield_policy.is_expired(),
|scan| {
let governor = &mut scan.scan_state.governor;
if sample_clock {
governor.take_yield_if_due_hot(yield_policy)
} else {
governor.take_yield_if_due(yield_policy)
}
},
);
if yield_due {
Self::publish_committed_match_telemetry(accumulator, metrics);
}
yield_due
}
}
enum ClosedDirectStop {
Continue { skip_direct: SkipDirect },
Flush,
Yield,
}
impl BoundHead<'_> {
#[inline]
fn can_precheck_single_batch_match_free(
pattern_matcher: &PatternMatcher,
accumulator: &MatchAccumulator,
) -> bool {
let program = &pattern_matcher.program;
program.can_skip_candidate_evaluation()
&& !program.config().runtime_absent_symbol_pruning_disabled
&& !accumulator.requires_partition_output_flush()
&& if program.packed_lane_column.is_some() {
program.required_packed_mask != 0
} else {
!program.required_static_symbol_indices.is_empty()
|| !program.required_and_precheck_columns.is_empty()
}
}
#[inline(never)]
fn single_batch_complete_partition_is_match_free(
collection: &BatchCollection,
bool_columns: &MultiBatchBoolColumnsBacking,
part: &Range<usize>,
pattern_matcher: &PatternMatcher,
) -> Option<usize> {
let (start_batch, local_start) = collection.locate(part.start);
let (end_batch, last_local) = collection.locate(part.end - 1);
if start_batch != end_batch {
return None;
}
if let Some(packed_col) = pattern_matcher.program.packed_lane_column {
let required_mask = pattern_matcher.program.required_packed_mask;
let batch = collection.batch(start_batch);
let words = batch
.columns()
.get(packed_col)?
.as_any()
.downcast_ref::<UInt64Array>()?
.values();
let slice = &words[local_start..=last_local];
let mut seen = 0u64;
for chunk in slice.chunks(64) {
for &w in chunk {
seen |= w;
}
if (seen & required_mask) == required_mask {
return None;
}
}
return ((seen & required_mask) != required_mask).then_some(slice.len());
}
let static_indices = &pattern_matcher.program.required_static_symbol_indices;
let and_cols = &pattern_matcher.program.required_and_precheck_columns;
bool_columns
.range_missing_any_required(part, static_indices, and_cols)
.then_some(part.len())
}
#[inline(never)]
#[expect(
clippy::too_many_arguments,
reason = "commits a skipped segment across independent scan and cursor state"
)]
fn commit_match_free_segment(
scan: &mut PartitionScan,
partitions: &mut PreparedPartitions,
next: SegmentCursor,
part: &Range<usize>,
scanned_rows: usize,
absolute_end: usize,
pattern_matcher: &PatternMatcher,
metrics: &PatternMetrics,
) -> Result<(Option<PendingPartitionOutput>, bool)> {
if pattern_matcher.is_aborted() {
return internal_err!("MATCH_RECOGNIZE execution cancelled");
}
let next_id = scan.next_partition_id.checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE logical partition ID space exhausted".into(),
)
})?;
let scratch = scan.ensure_governed_scratch(pattern_matcher)?;
scratch
.scan_state
.governor
.record_completed(scanned_rows.max(1), || pattern_matcher.is_aborted())?;
metrics.static_absence_pruned_partitions.add(1);
#[cfg(test)]
metrics.partition_preparations.add(1);
scan.next_partition_id = next_id;
scan.accumulator.max_processed_row =
scan.accumulator.max_processed_row.max(absolute_end);
partitions.cursor = next;
let sample_clock = part.len() <= COARSE_WORK_BATCH_SIZE
&& scan.accumulator.can_append_direct_winner();
let next_closed = partitions
.cursor
.peek(&partitions.head)
.is_some_and(|next| next.ends_partition);
let pending = if scan.accumulator.len() >= scan.accumulator.output_batch_size()
|| (!next_closed && !scan.accumulator.is_empty())
{
Some(PendingPartitionOutput::Flush { then_stage: None })
} else {
None
};
Ok((pending, sample_clock))
}
fn suspend_closed_direct_segment(
scan: &mut PartitionScan,
partitions: &mut PreparedPartitions,
segment: &HeadSegment,
global_offset: usize,
pattern_matcher: &PatternMatcher,
match_number: u64,
row_idx: usize,
) -> Result<()> {
let descriptor = partitions.descriptor(segment, scan)?;
let partition_id = scan.activate_partition(
&descriptor,
global_offset,
partitions.generation,
pattern_matcher,
)?;
let part_start = global_offset + segment.range.start;
let part_end = global_offset + segment.range.end;
let scan_ctx = scan.scratch.as_deref_mut().expect("activated partition");
scan_ctx.prepare_collection_start(part_start);
scan_ctx.partition.next_match_number = match_number;
scan_ctx.install_active_variant(ActiveVariant::base(
pattern_matcher.program.base_variant(),
))?;
let binding = scan_ctx.prepare_collection_binding(
CollectionWindow {
head_generation: partitions.generation,
provider_origin: part_start,
provider_end: part_end,
has_virtual_end: true,
backing_start: segment.range.start,
candidate_end_row: segment.range.end,
},
Arc::clone(&partitions.bool_columns),
)?;
scan_ctx.collection.commit_binding(binding);
scan_ctx.partition.global_row_offset = global_offset;
scan_ctx.partition.partition_start_row = segment.range.start;
scan_ctx.partition.partition_end_row = segment.range.end;
scan_ctx.cursor = NextMatchCursor { row_idx };
partitions.suspended_partition = Some(partition_id);
Ok(())
}
fn try_drive_closed_direct(
scan: &mut PartitionScan,
partitions: &mut PreparedPartitions,
collection: &BatchCollection,
global_offset: usize,
pattern_matcher: &PatternMatcher,
metrics: &PatternMetrics,
batched_routes: &mut DirectRouteCounters,
) -> Result<ClosedDirectStop> {
if partitions.pending_output.is_some()
|| partitions.suspended_partition.is_some()
|| scan.candidate_start_core_rows.is_some()
|| scan.current_scan().is_some()
|| scan.accumulator.len() >= scan.flush_threshold
{
return Ok(ClosedDirectStop::Continue {
skip_direct: SkipDirect::None,
});
}
let total_rows = collection.num_rows();
let Some(first) = partitions.cursor.peek(&partitions.head) else {
return Ok(ClosedDirectStop::Continue {
skip_direct: SkipDirect::None,
});
};
if !first.ends_partition
|| (first.range.start == 0 && first.range.end == total_rows)
{
return Ok(ClosedDirectStop::Continue {
skip_direct: SkipDirect::None,
});
}
let Some(mut driver) = ClosedDirectDriver::try_new(
pattern_matcher,
collection,
global_offset,
&scan.accumulator,
scan.yield_policy,
) else {
return Ok(ClosedDirectStop::Continue {
skip_direct: SkipDirect::None,
});
};
let _ = scan.ensure_governed_scratch(pattern_matcher)?;
let can_precheck_absence = Self::can_precheck_single_batch_match_free(
pattern_matcher,
&scan.accumulator,
);
let mut work = 0usize;
let quantum = direct_quantum(scan.yield_policy);
let mut stop = ClosedDirectStop::Continue {
skip_direct: SkipDirect::None,
};
let mut completed_any = false;
let mut suspend: Option<(HeadSegment, u64, usize)> = None;
let loop_res: Result<()> = (|| {
loop {
if scan.accumulator.len() >= scan.flush_threshold
|| !scan.accumulator.can_append_direct_winner()
{
stop = ClosedDirectStop::Flush;
break;
}
let mut next = partitions.cursor;
let Some(segment) = next.next_segment(&partitions.head) else {
break;
};
if !segment.ends_partition
|| (segment.range.start == 0 && segment.range.end == total_rows)
{
if completed_any
&& !segment.ends_partition
&& !scan.accumulator.is_empty()
{
stop = ClosedDirectStop::Flush;
}
break;
}
let next_id = scan.next_partition_id.checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE logical partition ID space exhausted".into(),
)
})?;
let absolute_end = global_offset
.checked_add(segment.range.end)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE absolute partition end exceeds usize"
.to_string(),
)
})?;
let scratch = scan.scratch.as_deref_mut().expect("allocated scratch");
let initial_match_number = if scan.has_partition_by {
scan.base_match_number
} else {
scratch.partition.next_match_number
};
let mut match_number = initial_match_number;
let resources = scratch.resources_mut();
let outcome = if can_precheck_absence
&& segment.fresh_index.is_some()
&& segment.range.len() >= 8
&& let Some(scanned_rows) =
Self::single_batch_complete_partition_is_match_free(
collection,
&partitions.bool_columns,
&segment.range,
pattern_matcher,
) {
metrics.static_absence_pruned_partitions.add(1);
work += scanned_rows.max(1);
ClosedSegmentOutcome::Complete(absolute_end)
} else {
driver.drive_segment(
&segment.range,
&mut match_number,
&mut scan.accumulator,
&mut resources.lane_scan,
&resources.lane_state_memory,
&mut resources.scan_state.governor,
&mut work,
)?
};
match outcome {
ClosedSegmentOutcome::Complete(_) => {
#[cfg(test)]
metrics.partition_preparations.add(1);
completed_any = true;
if !scan.has_partition_by {
scratch.partition.next_match_number = match_number;
}
scan.next_partition_id = next_id;
scan.accumulator.max_processed_row =
scan.accumulator.max_processed_row.max(absolute_end);
partitions.cursor = next;
if work >= quantum {
scratch
.scan_state
.governor
.record_completed(std::mem::take(&mut work), || {
pattern_matcher.is_aborted()
})?;
}
if work == 0
&& scratch
.scan_state
.governor
.take_yield_if_due_hot(scan.yield_policy)
{
stop = ClosedDirectStop::Yield;
break;
}
}
ClosedSegmentOutcome::Flush(row_idx) => {
if match_number != initial_match_number
|| row_idx > global_offset + segment.range.start
{
suspend = Some((segment, match_number, row_idx));
}
stop = ClosedDirectStop::Flush;
break;
}
ClosedSegmentOutcome::Yield(row_idx) => {
suspend = Some((segment, match_number, row_idx));
stop = ClosedDirectStop::Yield;
break;
}
ClosedSegmentOutcome::Handoff {
row_idx,
skip_direct,
} => {
if match_number != initial_match_number
|| row_idx > global_offset + segment.range.start
{
suspend = Some((segment, match_number, row_idx));
}
stop = ClosedDirectStop::Continue { skip_direct };
break;
}
}
}
Ok(())
})();
driver.merge_routes_into(batched_routes);
let direct_suffix = driver.into_suffix_cursor();
let charge_res = if work != 0 {
scan.scratch
.as_deref_mut()
.expect("allocated scratch")
.scan_state
.governor
.record_completed(work, || pattern_matcher.is_aborted())
} else {
Ok(())
};
if loop_res.is_err() || charge_res.is_err() {
scan.scratch
.as_deref_mut()
.expect("allocated scratch")
.collection
.poison();
}
loop_res?;
charge_res?;
if let Some((segment, match_number, row_idx)) = suspend {
Self::suspend_closed_direct_segment(
scan,
partitions,
&segment,
global_offset,
pattern_matcher,
match_number,
row_idx,
)?;
if matches!(stop, ClosedDirectStop::Yield | ClosedDirectStop::Flush) {
scan.scratch
.as_deref_mut()
.expect("suspended scratch")
.direct_suffix = direct_suffix;
}
}
if matches!(stop, ClosedDirectStop::Yield) {
PartitionScan::publish_committed_match_telemetry(
&mut scan.accumulator,
metrics,
);
}
Ok(stop)
}
pub(in crate::execution) fn advance(
&mut self,
runtime: ComputeRuntime<'_>,
) -> Result<ComputeStep> {
let stop_on_output = self.stop_on_output;
let scan = &mut *self.scan;
let partitions = &mut self.partitions;
let collection = self.collection;
let global_offset = self.origin;
let end = partitions.head.end;
let candidate_start_core_rows = scan.candidate_start_core_rows;
let ComputeRuntime {
pattern_matcher,
history_buffer,
metrics,
pending_output,
} = runtime;
let final_flush = end.ends_partition();
let absolute_partition_end = |partition_end| {
global_offset.checked_add(partition_end).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE absolute partition end exceeds usize".to_string(),
)
})
};
let can_precheck_absence = Self::can_precheck_single_batch_match_free(
pattern_matcher,
&scan.accumulator,
);
let mut batched_routes = DirectRouteCounters::default();
let result = (|| -> Result<ComputeStep> {
loop {
if stop_on_output && !pending_output.is_empty() {
return Ok(ComputeStep::Yield);
}
let mut sample_clock = false;
let mut pending = if let Some(pending) = partitions.pending_output.take()
{
Some(pending)
} else {
match Self::try_drive_closed_direct(
scan,
partitions,
collection,
global_offset,
pattern_matcher,
metrics,
&mut batched_routes,
)? {
ClosedDirectStop::Yield => return Ok(ComputeStep::Yield),
ClosedDirectStop::Flush => {
Some(PendingPartitionOutput::Flush { then_stage: None })
}
ClosedDirectStop::Continue { skip_direct } => {
let mut next = partitions.cursor;
if let Some(segment) = next.next_segment(&partitions.head) {
let part = &segment.range;
let closes = segment.ends_partition;
if can_precheck_absence
&& closes
&& segment.fresh_index.is_some()
&& part.len() >= 8
&& partitions.suspended_partition.is_none()
&& scan.current_scan().is_none()
&& candidate_start_core_rows.is_none()
&& let Some(scanned_rows) =
Self::single_batch_complete_partition_is_match_free(
collection,
&partitions.bool_columns,
part,
pattern_matcher,
)
{
let (next_pending, clock) =
Self::commit_match_free_segment(
scan,
partitions,
next,
part,
scanned_rows,
absolute_partition_end(part.end)?,
pattern_matcher,
metrics,
)?;
sample_clock = clock;
next_pending
} else {
sample_clock = closes
&& part.len() <= COARSE_WORK_BATCH_SIZE
&& scan.scratch.is_some()
&& scan.accumulator.can_append_direct_winner();
let partition_id =
if let Some(id) = partitions.suspended_partition {
id
} else {
let descriptor =
partitions.descriptor(&segment, scan)?;
scan.activate_partition(
&descriptor,
global_offset,
partitions.generation,
pattern_matcher,
)?
};
let scratch = scan
.scratch
.as_deref_mut()
.expect("activated partition");
let (progress, inline_only) = pattern_matcher
.process_rows_collection(
scratch,
crate::execution::matching::ProcessRowsInput {
stop_on_output,
batches: collection,
bool_columns: &partitions.bool_columns,
start_row: part.start,
end_row: part.end,
candidate_end_row: candidate_end_row(
candidate_start_core_rows,
part,
)?,
out: &mut scan.accumulator,
pending_output,
history_buffer,
metrics,
yield_policy: scan.yield_policy,
partition_id,
head_generation: partitions.generation,
final_flush: closes,
global_offset,
skip_direct,
batched_base_routes: Some(
&mut batched_routes,
),
},
)?;
sample_clock &= inline_only;
if matches!(progress, ComputeStep::Yield) {
partitions.suspended_partition =
Some(partition_id);
PartitionScan::publish_committed_match_telemetry(
&mut scan.accumulator,
metrics,
);
return Ok(ComputeStep::Yield);
}
let absolute_end = absolute_partition_end(part.end)?;
scan.accumulator.max_processed_row = scan
.accumulator
.max_processed_row
.max(absolute_end);
partitions.suspended_partition = None;
if closes {
scan.finish_partition();
}
partitions.cursor = next;
let next_closed = partitions
.cursor
.peek(&partitions.head)
.is_some_and(|next| next.ends_partition);
if closes
&& scan
.accumulator
.requires_partition_output_flush()
{
Some(PendingPartitionOutput::StageUnmatched {
end: absolute_end,
flush_tail: !next_closed,
})
} else if scan.accumulator.len()
>= scan.accumulator.output_batch_size()
|| (closes && !next_closed)
{
Some(PendingPartitionOutput::Flush {
then_stage: None,
})
} else {
None
}
}
} else {
let input_end =
absolute_partition_end(collection.num_rows())?;
let tail_end = final_flush
.then(|| {
scan.accumulator.max_processed_row.min(input_end)
})
.filter(|_| {
scan.accumulator.requires_partition_output_flush()
});
if let Some(end) = tail_end
&& scan
.accumulator
.min_unfinalized_presence_row()?
.is_some_and(|row| row < end)
{
Some(PendingPartitionOutput::StageUnmatched {
end,
flush_tail: true,
})
} else if !scan.accumulator.is_empty() {
Some(PendingPartitionOutput::Flush {
then_stage: None,
})
} else {
PartitionScan::publish_committed_match_telemetry(
&mut scan.accumulator,
metrics,
);
break;
}
}
}
}
};
sample_clock &= pending.is_none();
while let Some(work) = pending.take() {
match work {
PendingPartitionOutput::Flush { then_stage } => {
PartitionScan::flush_pending_output(
&mut scan.accumulator,
scan.scratch.as_deref_mut(),
pattern_matcher,
collection,
global_offset,
history_buffer,
metrics,
pending_output,
)?;
if stop_on_output && !pending_output.is_empty() {
partitions.pending_output =
then_stage.map(|(end, flush_tail)| {
PendingPartitionOutput::StageUnmatched {
end,
flush_tail,
}
});
return Ok(ComputeStep::Yield);
}
if let Some((end, flush_tail)) = then_stage {
let next_stage = PendingPartitionOutput::StageUnmatched {
end,
flush_tail,
};
if PartitionScan::take_post_partition_yield_if_due(
scan.scratch.as_deref_mut(),
&mut scan.accumulator,
scan.yield_policy,
metrics,
false,
) {
partitions.pending_output = Some(next_stage);
return Ok(ComputeStep::Yield);
}
pending = Some(next_stage);
}
}
PendingPartitionOutput::StageUnmatched { end, flush_tail } => {
let batch_size = scan.accumulator.output_batch_size();
if scan.accumulator.len() >= batch_size {
pending = Some(PendingPartitionOutput::Flush {
then_stage: Some((end, flush_tail)),
});
continue;
}
let finished = {
let governor = scan
.scratch
.as_deref_mut()
.map(|s| &mut s.scan_state.governor)
.ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE unmatched staging has no owning scan governor"
.to_string(),
)
})?;
scan.accumulator.append_unmatched_prefix_chunk(
end,
&mut |units| {
governor.record_completed(units, || {
pattern_matcher.is_aborted()
})
},
)?
};
if scan.accumulator.len() >= batch_size {
pending = Some(PendingPartitionOutput::Flush {
then_stage: (!finished).then_some((end, flush_tail)),
});
continue;
}
if finished {
if flush_tail && !scan.accumulator.is_empty() {
pending = Some(PendingPartitionOutput::Flush {
then_stage: None,
});
continue;
}
break;
}
if PartitionScan::take_post_partition_yield_if_due(
scan.scratch.as_deref_mut(),
&mut scan.accumulator,
scan.yield_policy,
metrics,
false,
) {
partitions.pending_output =
Some(PendingPartitionOutput::StageUnmatched {
end,
flush_tail,
});
return Ok(ComputeStep::Yield);
}
pending = Some(PendingPartitionOutput::StageUnmatched {
end,
flush_tail,
});
}
}
}
if partitions.cursor.peek(&partitions.head).is_some()
&& PartitionScan::take_post_partition_yield_if_due(
scan.scratch.as_deref_mut(),
&mut scan.accumulator,
scan.yield_policy,
metrics,
sample_clock,
)
{
return Ok(ComputeStep::Yield);
}
}
Ok(ComputeStep::Complete)
})();
batched_routes
.record_routes(pattern_matcher, pattern_matcher.program.base_variant());
result
}
}
impl PartitionScan {
pub(in crate::execution) fn resume<'a>(
&'a mut self,
partitions: PreparedPartitions,
collection: &'a BatchCollection,
origin: usize,
) -> BoundHead<'a> {
BoundHead {
scan: self,
partitions,
stop_on_output: true,
collection,
origin,
}
}
pub(in crate::execution) async fn prepare(
&mut self,
head: HeadPartitions,
collection: &BatchCollection,
matcher: &PatternMatcher,
governor: &mut WorkGovernor,
slice: &crate::execution::common::scheduling::SliceControl,
memory: &MemoryReservation,
) -> Result<PreparedPartitions> {
let mut pending = self.begin_partition_preparation(
head,
collection.num_rows(),
matcher,
memory,
)?;
while !pending.advance(collection, matcher, governor, slice.current_policy())? {
slice.yield_once().await;
}
self.finish_preparation(pending)
}
pub(crate) fn current_scan(&self) -> Option<&ScanContext> {
self.scratch
.as_deref()
.filter(|scan| scan.partition.logical.is_some())
}
pub(crate) fn open_tail_key(&self) -> Result<Option<PartitionKey>> {
self.current_scan()
.map(|scan| {
scan.partition
.logical()?
.key
.canonical()
.cloned()
.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE closed partition escaped its input head"
)
})
})
.transpose()
}
fn ensure_governed_scratch(
&mut self,
pattern_matcher: &PatternMatcher,
) -> Result<&mut ScanContext> {
if pattern_matcher.is_aborted() {
return internal_err!("MATCH_RECOGNIZE execution cancelled");
}
let program_id = pattern_matcher.program_id();
if let Some(scratch) = self.scratch.as_deref() {
scratch.collection.validate_not_poisoned("step")?;
scratch
.validate_execution_identity(self.execution_partition_id, program_id)?;
} else {
let mut ctx = ScanContext::try_new_with_state_memory(
pattern_matcher.automaton().nfa().state_count(),
pattern_matcher.automaton().id_to_symbol().len(),
self.base_match_number,
Arc::clone(&self.state_memory),
)?;
ctx.commit_execution_identity(self.execution_partition_id, program_id);
self.scratch = Some(Box::new(ctx));
}
let cancellation_policy = CancellationPolicy::try_from_configured(
pattern_matcher.program.config().cancellation_poll_interval,
pattern_matcher.program.config().execution_deadline_millis,
)?;
let scratch = self.scratch.as_deref_mut().expect("allocated scratch");
scratch
.scan_state
.governor
.bind_cancellation_policy(cancellation_policy)?;
Ok(scratch)
}
fn finish_partition(&mut self) {
let scan = self
.scratch
.as_deref_mut()
.expect("completed partition owns a scan");
scan.collection.clear();
scan.partition.logical = None;
}
fn activate_partition(
&mut self,
descriptor: &PartitionDescriptor,
global_offset: usize,
head: CollectionHeadGeneration,
matcher: &PatternMatcher,
) -> Result<MatchPartitionId> {
if let PartitionKeyBinding::HeadLocal(owner) = &descriptor.key
&& (*owner != head || !descriptor.ends_partition)
{
return internal_err!(
"MATCH_RECOGNIZE closed partition bound outside its input head"
);
}
let absolute_start = global_offset
.checked_add(descriptor.range.start)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE absolute partition start exceeds usize".into(),
)
})?;
let target = descriptor.partition_id;
let program_id = matcher.program_id();
if let Some(scan) = self.scratch.as_deref() {
scan.validate_execution_identity(self.execution_partition_id, program_id)?;
}
if let Some(scan) = self.current_scan() {
let binding = scan.partition.logical()?;
if binding.partition_id != target || !binding.key.same_owner(&descriptor.key)
{
return internal_err!(
"MATCH_RECOGNIZE partition descriptor does not match the open partition"
);
}
if matches!(binding.key, PartitionKeyBinding::HeadLocal(_))
&& (scan.partition.global_row_offset != global_offset
|| scan.partition.partition_start_row != descriptor.range.start
|| scan.partition.partition_end_row != descriptor.range.end)
{
return internal_err!(
"MATCH_RECOGNIZE closed partition resumed with a changed collection range within its input head"
);
}
} else {
if target.get() != self.next_partition_id {
return internal_err!(
"MATCH_RECOGNIZE cannot activate partition ID {}; next ID is {}",
target,
self.next_partition_id
);
}
#[cfg(test)]
if let Some(metrics) = &matcher.services.metrics {
metrics.partition_preparations.add(1);
}
let next_id = self.next_partition_id.checked_add(1).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE logical partition ID space exhausted".into(),
)
})?;
let scan = match &mut self.scratch {
Some(recycled) => {
let next_match = if self.has_partition_by {
self.base_match_number
} else {
recycled.partition.next_match_number
};
recycled.reset_for_partition(absolute_start, next_match);
recycled.as_mut()
}
vacant @ None => vacant
.insert(Box::new(ScanContext::try_new_with_state_memory(
matcher.automaton().nfa().state_count(),
matcher.automaton().id_to_symbol().len(),
self.base_match_number,
Arc::clone(&self.state_memory),
)?))
.as_mut(),
};
scan.partition.logical = Some(LogicalPartitionBinding {
partition_id: target,
key: descriptor.key.clone(),
});
scan.commit_execution_identity(self.execution_partition_id, program_id);
scan.partition.absolute_partition_start = absolute_start;
self.next_partition_id = next_id;
}
let scan = self.scratch.as_deref_mut().expect("activated partition");
scan.partition.global_row_offset = global_offset;
scan.partition.partition_start_row = descriptor.range.start;
scan.partition.partition_end_row = descriptor.range.end;
Ok(target)
}
}
#[derive(Clone)]
struct PartitionDescriptor {
range: Range<usize>,
partition_id: MatchPartitionId,
key: PartitionKeyBinding,
ends_partition: bool,
}
struct PreparingPartitions {
head: HeadPartitions,
generation: CollectionHeadGeneration,
next_generation: CollectionHeadGeneration,
implicit: bool,
bool_columns: PreparingPhysicalBoolColumns,
}
impl PartitionScan {
fn begin_partition_preparation(
&self,
head: HeadPartitions,
rows: usize,
matcher: &PatternMatcher,
memory: &MemoryReservation,
) -> Result<PreparingPartitions> {
let next_generation =
self.next_head_generation
.get()
.checked_add(1)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE collection head generation space exhausted"
.into(),
)
})?;
let implicit = rows == 0
&& head.ranges.is_empty()
&& !self.has_partition_by
&& self.next_partition_id == 0;
let new_ranges = (head.ranges.len() + usize::from(implicit))
.checked_sub(usize::from(head.continues_tail))
.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE continuing head has no physical range"
)
})?;
self.next_partition_id
.checked_add(new_ranges)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE logical partition ID space exhausted".into(),
)
})?;
Ok(PreparingPartitions {
head,
generation: self.next_head_generation,
next_generation: CollectionHeadGeneration::new(next_generation),
implicit,
bool_columns: matcher
.begin_physical_bool_columns(rows, memory.new_empty())?,
})
}
fn finish_preparation(
&mut self,
pending: PreparingPartitions,
) -> Result<PreparedPartitions> {
let previous = if let Some(scan) = self.current_scan() {
if scan.partition.logical()?.key.canonical().is_none() {
return internal_err!(
"MATCH_RECOGNIZE closed partition escaped its input head"
);
}
true
} else {
false
};
let bool_columns = pending.bool_columns.finish()?;
self.next_head_generation = pending.next_generation;
Ok(PreparedPartitions {
generation: pending.generation,
head: pending.head,
cursor: SegmentCursor::new(previous, pending.implicit),
first_new_id: self.next_partition_id,
bool_columns,
suspended_partition: None,
pending_output: None,
})
}
}
impl PreparingPartitions {
fn advance(
&mut self,
collection: &BatchCollection,
matcher: &PatternMatcher,
governor: &mut WorkGovernor,
policy: crate::config::YieldPolicy,
) -> Result<bool> {
loop {
let done = matcher
.advance_physical_bool_columns(&mut self.bool_columns, collection)?;
governor.record_completed(collection.num_rows().max(1), || {
matcher.is_aborted()
})?;
if done {
return Ok(true);
}
if governor.take_yield_if_due(policy) {
return Ok(false);
}
}
}
}
impl PreparedPartitions {
fn descriptor(
&self,
segment: &HeadSegment,
context: &PartitionScan,
) -> Result<PartitionDescriptor> {
let previous = context
.current_scan()
.and_then(|scan| scan.partition.logical.as_ref());
let partition_id = match segment.fresh_index {
Some(i) => MatchPartitionId::new(self.first_new_id + i),
None => {
previous
.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE prior partition lost its scan binding"
)
})?
.partition_id
}
};
let key = match segment.key(
&self.head,
context.has_partition_by,
previous.and_then(|binding| binding.key.canonical()),
)? {
Some(key) => PartitionKeyBinding::Canonical(key),
None => PartitionKeyBinding::HeadLocal(self.generation),
};
Ok(PartitionDescriptor {
partition_id,
range: segment.range.clone(),
key,
ends_partition: segment.ends_partition,
})
}
}
#[cfg(test)]
mod tests;