use super::aggregate_engine::AggregateEngineState;
use super::lane_scan::{DirectLinearCursor, LaneScanProgram, LaneScanState};
use super::state::{CollectionIdentity, ScanState, SymbolEvaluationContext};
use super::thread_store::ThreadStore;
use crate::core::{AbsoluteRow, PhysicalExtent, PhysicalRowCount};
use crate::execution::common::coordinates::{
absolute_row_from_usize, absolute_row_to_usize,
};
use crate::execution::identity::PartitionKeyBinding;
#[cfg(test)]
use crate::execution::matching::PartitionKey;
use crate::execution::matching::epsilon::EpsilonClosureScratch;
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;
use std::sync::Arc;
pub(super) fn absolute_provider_row(
origin: AbsoluteRow,
local: usize,
) -> Result<AbsoluteRow> {
let row = absolute_row_to_usize(origin, "provider origin")?
.checked_add(local)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE next unread row exceeds usize".into(),
)
})?;
absolute_row_from_usize(row, "next unread row")
}
#[inline]
pub(crate) fn lookbehind_floor(
position: AbsoluteRow,
required: PhysicalRowCount,
partition_start: AbsoluteRow,
) -> AbsoluteRow {
let floor = position.checked_sub(required).unwrap_or(partition_start);
if floor.as_u64() < partition_start.as_u64() {
partition_start
} else {
floor
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ScanFrontiers {
candidate_start_abs: AbsoluteRow,
next_unread_abs: AbsoluteRow,
replay_start_abs: AbsoluteRow,
min_retained_input_abs: AbsoluteRow,
}
#[derive(Clone)]
pub(crate) enum ActiveVariant {
Base,
Pruned(Arc<ExecutablePatternVariant>),
}
impl ActiveVariant {
#[inline]
pub(crate) fn base(_variant: &ExecutablePatternVariant) -> Self {
Self::Base
}
#[inline]
pub(crate) fn from_pruned(
variant: Arc<ExecutablePatternVariant>,
base: &Arc<ExecutablePatternVariant>,
) -> Self {
if Arc::ptr_eq(&variant, base) {
Self::base(base)
} else {
Self::Pruned(variant)
}
}
#[inline]
pub(crate) fn resolve<'a>(
&'a self,
base: &'a Arc<ExecutablePatternVariant>,
) -> &'a Arc<ExecutablePatternVariant> {
match self {
Self::Base => base,
Self::Pruned(variant) => variant,
}
}
#[inline]
pub(crate) const fn is_base(&self) -> bool {
matches!(self, Self::Base)
}
}
pub(crate) struct ScanResources {
pub(crate) traversal: EpsilonClosureScratch,
pub(crate) symbols: SymbolEvaluationContext,
pub(crate) aggregation: AggregateEngineState,
pub(crate) thread_store: ThreadStore,
pub(crate) candidate_history:
Option<Box<crate::execution::deferred::CandidateHistory>>,
pub(crate) scan_state: ScanState,
pub(crate) active_variant: Option<ActiveVariant>,
pub(crate) lane_scan: Option<LaneScanState>,
pub(crate) direct_suffix: Option<(Arc<LaneScanProgram>, DirectLinearCursor)>,
pub(crate) selected_output:
Option<crate::execution::matching::collection::SelectedOutputTransaction>,
pub(crate) lane_state_memory: Arc<MemoryReservation>,
}
impl ScanResources {
pub(crate) fn try_new(
n_states: usize,
n_symbols: usize,
state_memory: Arc<MemoryReservation>,
) -> Result<Self> {
let arena_memory = state_memory.new_empty();
let aggregation = AggregateEngineState::new(arena_memory, n_symbols);
Ok(Self {
traversal: EpsilonClosureScratch::new(&state_memory),
symbols: SymbolEvaluationContext::new(n_symbols, state_memory.new_empty())?,
aggregation,
thread_store: ThreadStore::try_new_with_state_memory(
n_states,
Arc::clone(&state_memory),
)?,
candidate_history: None,
scan_state: ScanState::default(),
active_variant: None,
lane_scan: None,
direct_suffix: None,
selected_output: None,
lane_state_memory: state_memory,
})
}
pub(crate) fn retain_lane_variant_memory(&mut self) {
if let Some(ActiveVariant::Pruned(variant)) = &self.active_variant
&& let Some(lane) = &mut self.lane_scan
&& variant
.lane_scan_program()
.is_some_and(|program| lane.is_for(program))
{
lane.retain_variant_memory(variant);
}
}
pub(crate) fn prepare_lane_scan(
&mut self,
program: &Arc<LaneScanProgram>,
match_start: AbsoluteRow,
) -> Result<usize> {
if self
.lane_scan
.as_ref()
.is_some_and(LaneScanState::candidate_is_live)
{
return datafusion::common::internal_err!(
"MATCH_RECOGNIZE cannot replace a live lane candidate"
);
}
if self
.lane_scan
.as_ref()
.is_some_and(|state| !state.is_for(program))
{
self.lane_scan = None;
}
if self.lane_scan.is_none() {
let mut state =
LaneScanState::try_new(Arc::clone(program), &self.lane_state_memory)?;
if let Some(ActiveVariant::Pruned(variant)) = &self.active_variant {
state.retain_variant_memory(variant);
}
self.lane_scan = Some(state);
}
let state = self
.lane_scan
.as_mut()
.expect("lane state was created before candidate initialization");
Ok(state.start_candidate(match_start))
}
pub(super) fn generic_candidate_state_is_empty(&self) -> bool {
!self.thread_store.has_in_flight_states_for_tier()
&& self.thread_store.node_arena.is_empty()
&& self.scan_state.resume.is_start_row()
&& self.scan_state.incumbent.is_none()
&& self.candidate_history.is_none()
}
}
pub(crate) struct ScanContinuation {
owner_id: CollectionIdentity,
partition_key: PartitionKeyBinding,
partition_start_abs: AbsoluteRow,
frontiers: ScanFrontiers,
required_lookbehind: PhysicalRowCount,
bound_provider: PhysicalExtent,
}
impl ScanContinuation {
fn provider_work_end(
provider: PhysicalExtent,
has_virtual_end: bool,
) -> Result<AbsoluteRow> {
if has_virtual_end {
provider
.end()
.position()
.checked_add(PhysicalRowCount::new(1))
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE virtual provider end exceeds the absolute row domain"
.to_string(),
)
})
} else {
Ok(provider.end().position())
}
}
#[expect(
clippy::too_many_arguments,
reason = "binds independently validated continuation identity and bounds"
)]
pub(crate) fn try_new(
resources: &ScanResources,
owner_id: CollectionIdentity,
partition_key: PartitionKeyBinding,
partition_start_abs: AbsoluteRow,
frontiers: ScanFrontiers,
required_lookbehind: PhysicalRowCount,
bound_provider: PhysicalExtent,
bound_has_virtual_end: bool,
) -> Result<Self> {
if frontiers.candidate_start_abs() < partition_start_abs {
return internal_err!(
"MATCH_RECOGNIZE continuation candidate start precedes its partition"
);
}
if bound_provider.start() > frontiers.next_unread_abs() {
return internal_err!(
"MATCH_RECOGNIZE continuation provider origin {} is after next unread row {}",
bound_provider.start(),
frontiers.next_unread_abs()
);
}
let provider_work_end =
Self::provider_work_end(bound_provider, bound_has_virtual_end)?;
if provider_work_end < frontiers.next_unread_abs() {
return internal_err!(
"MATCH_RECOGNIZE continuation provider end {} is before next unread row {}",
provider_work_end,
frontiers.next_unread_abs()
);
}
if resources.active_variant.is_none() {
return internal_err!(
"MATCH_RECOGNIZE continuation has no active executable variant"
);
}
if !resources.scan_state.resume.is_start_row() {
return internal_err!(
"MATCH_RECOGNIZE fresh continuation has invalid resume phase {}",
resources.scan_state.resume.name()
);
}
if let Some(lane_start) = resources
.lane_scan
.as_ref()
.and_then(LaneScanState::candidate_start)
{
if lane_start != frontiers.candidate_start_abs()
|| !resources.generic_candidate_state_is_empty()
{
return internal_err!(
"MATCH_RECOGNIZE lane continuation retained incompatible candidate state"
);
}
} else {
if resources.thread_store.selected_tier().is_none() {
return internal_err!(
"MATCH_RECOGNIZE continuation has no selected thread tier"
);
}
if !resources.thread_store.has_active_states_for_tier() {
return internal_err!(
"MATCH_RECOGNIZE fresh continuation has no live initial state"
);
}
if resources.thread_store.min_match_start_row_for_tier()
!= Some(frontiers.candidate_start_abs())
{
return internal_err!(
"MATCH_RECOGNIZE fresh continuation state does not belong to candidate {}",
frontiers.candidate_start_abs()
);
}
}
let current_abs = absolute_provider_row(
bound_provider.start(),
resources.scan_state.current_row,
)?;
let expected_cursor = frontiers.next_unread_abs();
if current_abs != expected_cursor {
return internal_err!(
"MATCH_RECOGNIZE continuation cursor {} does not address expected row {}",
current_abs,
expected_cursor
);
}
Ok(Self {
owner_id,
partition_key,
partition_start_abs,
frontiers,
required_lookbehind,
bound_provider,
})
}
#[cfg(test)]
pub(crate) fn partition_key_arc_for_validation(&self) -> Option<&PartitionKey> {
self.partition_key.canonical()
}
pub(crate) const fn frontiers(&self) -> ScanFrontiers {
self.frontiers
}
pub(crate) const fn required_lookbehind(&self) -> PhysicalRowCount {
self.required_lookbehind
}
pub(crate) const fn bound_provider(&self) -> PhysicalExtent {
self.bound_provider
}
pub(crate) fn checkpoint(&mut self, frontiers: ScanFrontiers) -> Result<()> {
if frontiers.candidate_start_abs() != self.frontiers.candidate_start_abs() {
return internal_err!(
"MATCH_RECOGNIZE continuation candidate start changed from {} to {}",
self.frontiers.candidate_start_abs(),
frontiers.candidate_start_abs()
);
}
if self.bound_provider.start() > frontiers.next_unread_abs() {
return internal_err!(
"MATCH_RECOGNIZE continuation provider origin {} is after next unread row {}",
self.bound_provider.start(),
frontiers.next_unread_abs()
);
}
self.frontiers = frontiers;
Ok(())
}
pub(crate) fn bind_head(
&mut self,
resources: &mut ScanResources,
expected_owner: CollectionIdentity,
expected_partition_key: &PartitionKeyBinding,
partition_start_abs: AbsoluteRow,
provider: PhysicalExtent,
has_virtual_end: bool,
) -> Result<usize> {
if expected_owner != self.owner_id {
return internal_err!(
"MATCH_RECOGNIZE continuation owner changed from {:?} to {:?}",
self.owner_id,
expected_owner
);
}
if !expected_partition_key.same_owner(&self.partition_key) {
return internal_err!(
"MATCH_RECOGNIZE continuation partition key lost canonical ownership during head binding"
);
}
if partition_start_abs != self.partition_start_abs {
return internal_err!(
"MATCH_RECOGNIZE continuation partition start changed from {} to {}",
self.partition_start_abs,
partition_start_abs
);
}
if provider.start() > self.frontiers.min_retained_input_abs() {
return internal_err!(
"MATCH_RECOGNIZE resumed provider origin {} is after retained input floor {}",
provider.start(),
self.frontiers.min_retained_input_abs()
);
}
let next_unread = self.frontiers.next_unread_abs();
let provider_work_end = Self::provider_work_end(provider, has_virtual_end)?;
if next_unread > provider_work_end {
return internal_err!(
"MATCH_RECOGNIZE next unread row {} is after provider end {}",
next_unread,
provider_work_end
);
}
let provider_changed = provider.start() != self.bound_provider.start();
let at_row_boundary = match resources
.lane_scan
.as_ref()
.filter(|lane| lane.candidate_is_live())
{
Some(lane) => lane.is_at_row_boundary(),
None => resources.scan_state.resume.is_start_row(),
};
if provider_changed && !at_row_boundary {
return internal_err!(
"MATCH_RECOGNIZE cannot bind a changed provider while continuation is in progress at scan phase {}",
resources.scan_state.resume.name()
);
}
let provider_row = next_unread
.checked_offset_from(provider.start())
.and_then(|offset| usize::try_from(offset.as_u64()).ok())
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE resumed provider row exceeds usize".to_string(),
)
})?;
self.bound_provider = provider;
resources.scan_state.current_row = provider_row;
Ok(provider_row)
}
}
impl ScanFrontiers {
pub(crate) fn try_new(
partition_start: AbsoluteRow,
candidate_start_abs: AbsoluteRow,
next_unread_abs: AbsoluteRow,
required_lookbehind: PhysicalRowCount,
) -> Result<Self> {
if candidate_start_abs < partition_start {
return internal_err!(
"MATCH_RECOGNIZE candidate start {} precedes partition start {}",
candidate_start_abs,
partition_start
);
}
if next_unread_abs < candidate_start_abs {
return internal_err!(
"MATCH_RECOGNIZE next unread row {} precedes candidate start {}",
next_unread_abs,
candidate_start_abs
);
}
let replay_start_abs = candidate_start_abs
.checked_add(PhysicalRowCount::new(1))
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE replay start exceeds the absolute row domain"
.to_string(),
)
})?;
let min_retained_input_abs =
lookbehind_floor(candidate_start_abs, required_lookbehind, partition_start);
Ok(Self {
candidate_start_abs,
next_unread_abs,
replay_start_abs,
min_retained_input_abs,
})
}
pub(crate) const fn candidate_start_abs(self) -> AbsoluteRow {
self.candidate_start_abs
}
pub(crate) const fn next_unread_abs(self) -> AbsoluteRow {
self.next_unread_abs
}
pub(crate) const fn replay_start_abs(self) -> AbsoluteRow {
self.replay_start_abs
}
pub(crate) const fn min_retained_input_abs(self) -> AbsoluteRow {
self.min_retained_input_abs
}
}
pub(crate) use crate::execution::matching::NextMatchCursor;
#[cfg(test)]
mod tests {
use super::{ScanFrontiers, lookbehind_floor};
use crate::core::{AbsoluteRow, PhysicalRowCount};
use datafusion::common::DataFusionError;
#[test]
fn lookbehind_floor_is_exact_and_partition_clamped() {
let partition_start = AbsoluteRow::new(100);
assert_eq!(
lookbehind_floor(
AbsoluteRow::new(115),
PhysicalRowCount::ZERO,
partition_start,
),
AbsoluteRow::new(115)
);
assert_eq!(
lookbehind_floor(
AbsoluteRow::new(115),
PhysicalRowCount::new(3),
partition_start,
),
AbsoluteRow::new(112)
);
assert_eq!(
lookbehind_floor(
AbsoluteRow::new(102),
PhysicalRowCount::new(8),
partition_start,
),
partition_start
);
}
#[test]
fn scan_frontiers_reject_invalid_or_unrepresentable_coordinates() {
for (partition, start, unread, fragment, exhausted) in [
(
100,
99,
101,
"candidate start 99 precedes partition start 100",
false,
),
(
100,
110,
109,
"next unread row 109 precedes candidate start 110",
false,
),
(
0,
u64::MAX,
u64::MAX,
"replay start exceeds the absolute row domain",
true,
),
] {
let error = ScanFrontiers::try_new(
AbsoluteRow::new(partition),
AbsoluteRow::new(start),
AbsoluteRow::new(unread),
PhysicalRowCount::ZERO,
)
.unwrap_err();
assert!(error.to_string().contains(fragment), "{error}");
if exhausted {
assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
} else {
assert!(matches!(error, DataFusionError::Internal(_)));
}
}
}
}