use super::reduction::{CompactReductions, ReadRegister};
use super::*;
use crate::config::YieldPolicy;
use crate::core::AbsoluteRow;
use crate::execution::common::coordinates::absolute_row_from_usize;
use crate::execution::common::work::WorkGovernor;
use crate::execution::matching::path::Sym;
use crate::execution::matching::row_loop::lane_scan::{
CompactSelection, LaneSelectedRuns, SymbolFacts,
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Phase {
Reductions(CompactReductions),
Rows,
Done,
}
pub(crate) struct CompactMatchPreparation {
coordinates: (AbsoluteRow, AbsoluteRow, AbsoluteRow),
match_number: i64,
output_rows: usize,
emitted_rows: usize,
run_index: usize,
word_offset: u64,
phase: Phase,
}
impl CompactMatchPreparation {
#[inline]
#[cfg(test)]
pub(crate) fn advance(
&mut self,
accumulator: &mut MatchAccumulator,
selected: &CompactSelection<'_>,
emission: MatchEmissionContext<'_>,
governor: &mut WorkGovernor,
policy: YieldPolicy,
is_aborted: impl Fn() -> bool,
) -> Result<Option<PreparedMatchEmission>> {
self.advance_with_registers(
accumulator,
selected,
emission,
governor,
policy,
is_aborted,
&mut |_, _| None,
)
}
#[inline]
#[allow(clippy::too_many_arguments)]
pub(crate) fn advance_with_registers(
&mut self,
accumulator: &mut MatchAccumulator,
selected: &CompactSelection<'_>,
mut emission: MatchEmissionContext<'_>,
governor: &mut WorkGovernor,
policy: YieldPolicy,
is_aborted: impl Fn() -> bool,
read_register: &mut ReadRegister<'_>,
) -> Result<Option<PreparedMatchEmission>> {
loop {
let prepared = accumulator.prepare_compact_match_chunk_with_registers(
self,
selected,
emission.reborrow(),
read_register,
&mut |units| governor.record_completed(units, &is_aborted),
)?;
if prepared.is_some() || governor.take_yield_if_due(policy) {
return Ok(prepared);
}
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct DirectPublicationBatch<'a> {
readable: (usize, usize),
partition_start: usize,
partition_end: usize,
origin: usize,
source: &'a BatchCollection,
}
impl MatchAccumulator {
pub(crate) fn supports_compact_selected(&self) -> bool {
self.supports_compact_selected
}
pub(crate) fn compact_demand(&self) -> ClassifierDemand {
if !self.supports_compact_selected() || self.output.needs_compact_classifier() {
return ClassifierDemand::All;
}
match &self.finalizer {
OutputFinalizerRuntime::DirectCounts {
symbol_demand,
needs_classifier_endpoint,
..
} => {
if *needs_classifier_endpoint {
symbol_demand.with_runs()
} else {
*symbol_demand
}
}
_ => ClassifierDemand::Symbols(0),
}
}
pub(crate) fn begin_compact_match(
&mut self,
match_id: u64,
selected: &CompactSelection<'_>,
emission: &MatchEmissionContext<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<CompactMatchPreparation> {
let (match_number, physical_steps) =
self.validate_compact_emission(match_id, selected, emission)?;
let (phase, output_rows) = match &mut self.finalizer {
OutputFinalizerRuntime::DirectCounts {
summaries,
has_reductions,
has_offset_edges,
..
} if *has_reductions
|| *has_offset_edges
|| summaries.len() > COARSE_WORK_BATCH_SIZE =>
{
(Phase::Reductions(CompactReductions::default()), 1)
}
OutputFinalizerRuntime::DirectCounts {
summaries, scratch, ..
} => {
let needs_runs = summaries
.iter()
.any(|summary| selected.symbol_facts(summary.symbol_id()).is_none());
let mut words = 0u64;
if needs_runs {
let history = selected.history()?;
for (index, run) in history.runs.iter().enumerate() {
words = words.saturating_add(
history
.edge_and_period(index, 0)?
.1
.min(run.steps().as_u64()),
);
if words > LaneSelectedRuns::MAX_ATOMIC_RUNS as u64 {
break;
}
}
}
if words > LaneSelectedRuns::MAX_ATOMIC_RUNS as u64 {
(Phase::Reductions(CompactReductions::default()), 1)
} else {
let mut work = CoarseWorkBatch::new(completed);
let result = if needs_runs {
reduce_summary_words(
selected,
&mut 0,
&mut 0,
summaries,
scratch,
words as usize,
&mut || work.complete_one(),
)
.map(|_| ())
} else {
fill_summary_facts(selected, summaries, scratch, &mut || {
work.complete_one()
})
};
if let Err(error) = result.and_then(|()| work.finish()) {
scratch.fill(0);
return Err(error);
}
(Phase::Rows, 1)
}
}
OutputFinalizerRuntime::Rows => (Phase::Rows, physical_steps),
};
Ok(CompactMatchPreparation {
coordinates: (selected.start, selected.end, selected.acceptance),
match_number,
output_rows,
emitted_rows: 0,
run_index: 0,
word_offset: 0,
phase,
})
}
fn validate_compact_emission(
&mut self,
match_id: u64,
selected: &CompactSelection<'_>,
emission: &MatchEmissionContext<'_>,
) -> Result<(i64, usize)> {
let readable = self.compact_extent(
&emission.partition,
emission.global_offset,
emission.batches.num_rows(),
emission.history,
)?;
self.validate_bound_winner(match_id, selected, readable)
}
fn compact_extent(
&self,
partition: &Range<usize>,
origin: usize,
rows: usize,
history: Option<&SharedHistoryBuffer>,
) -> Result<(usize, usize)> {
if !self.supports_compact_selected() {
return internal_err!(
"MATCH_RECOGNIZE compact publication has incompatible output"
);
}
let extent = validate_emission_extent(partition, origin, rows)?;
let readable_start = match history {
Some(history) if history.end_index() >= origin => {
extent.partition_start.max(history.head_index().min(origin))
}
_ => extent.partition_start.max(origin),
};
Ok((readable_start, extent.partition_end.min(extent.input_end)))
}
pub(crate) fn direct_publication_batch<'a>(
&self,
partition: Range<usize>,
origin: usize,
source: &'a BatchCollection,
) -> Result<DirectPublicationBatch<'a>> {
Ok(DirectPublicationBatch {
readable: self.compact_extent(&partition, origin, source.num_rows(), None)?,
partition_start: partition.start,
partition_end: partition.end,
origin,
source,
})
}
#[inline]
fn validate_bound_winner(
&mut self,
match_id: u64,
selected: &CompactSelection<'_>,
readable: (usize, usize),
) -> Result<(i64, usize)> {
let validated = self
.encoder
.validate_compact_match(match_id, selected, readable)?;
checked_match_count_successor(self.matches_emitted)?;
#[cfg(test)]
self.fail_match_preparation_before_mutation()?;
Ok(validated)
}
#[inline]
pub(crate) fn can_append_direct_winner(&self) -> bool {
self.supports_compact_selected
&& self.output.rows_until_flush() > 1
&& match &self.finalizer {
OutputFinalizerRuntime::DirectCounts { summaries, .. } => {
!self.output.needs_compact_classifier()
&& summaries.len() <= (COARSE_WORK_BATCH_SIZE - 4) / 2
}
OutputFinalizerRuntime::Rows => self.encoder.emits_all_selected_rows(),
}
}
#[inline]
pub(crate) fn direct_winner_needs_flush(
&self,
selected: &CompactSelection<'_>,
) -> bool {
if self.is_empty() {
return false;
}
match self.finalizer {
OutputFinalizerRuntime::DirectCounts { .. } => {
self.output.rows_until_flush() <= 1
}
OutputFinalizerRuntime::Rows => {
let room = self.output.rows_until_flush().saturating_sub(1);
selected.expected_steps.as_u64() > room as u64
}
}
}
#[inline]
#[allow(clippy::too_many_arguments)]
pub(crate) fn try_publish_direct_winner(
&mut self,
match_id: u64,
selected: &CompactSelection<'_>,
partition: Range<usize>,
global_offset: usize,
batches: &BatchCollection,
governor: &mut WorkGovernor,
is_aborted: impl Fn() -> bool,
read_register: impl FnMut(
usize,
&datafusion::arrow::datatypes::DataType,
) -> Option<crate::execution::matching::WinningValue>,
) -> Result<bool> {
self.try_publish_bound_winner(
match_id,
selected,
|acc| acc.direct_publication_batch(partition, global_offset, batches),
|units| governor.record_completed(units, &is_aborted),
read_register,
)
}
#[inline]
pub(crate) fn try_publish_bound_winner<'a>(
&mut self,
match_id: u64,
selected: &CompactSelection<'_>,
bind: impl FnOnce(&Self) -> Result<DirectPublicationBatch<'a>>,
mut record_work: impl FnMut(usize) -> Result<()>,
mut read_register: impl FnMut(
usize,
&datafusion::arrow::datatypes::DataType,
)
-> Option<crate::execution::matching::WinningValue>,
) -> Result<bool> {
if !self.can_append_direct_winner() {
return Ok(false);
}
let rows = selected.expected_steps.as_u64();
let needs_reduction_pass = match &self.finalizer {
OutputFinalizerRuntime::DirectCounts {
summaries,
has_reductions,
has_offset_edges,
..
} => {
let needs_runs = summaries
.iter()
.any(|summary| selected.symbol_facts(summary.symbol_id()).is_none());
if *has_reductions || *has_offset_edges || needs_runs {
let Some(mut budget) =
COARSE_WORK_BATCH_SIZE.checked_sub(4 + 2 * summaries.len())
else {
return Ok(false);
};
let steps = usize::try_from(rows).unwrap_or(usize::MAX);
let runs_len = selected.runs.as_ref().map_or(0, |h| h.runs.len());
for summary in summaries.iter() {
let cost = if let Some(red) = summary.reduction() {
if red.managed_aggregate.is_some() {
1
} else {
selected
.symbol_facts(summary.symbol_id())
.map_or(steps, |f| {
usize::try_from(f.count).unwrap_or(usize::MAX)
})
}
} else if summary.edge().is_some_and(|e| e.logical_offset > 0) {
let mut words = 0usize;
if let Some(history) = &selected.runs {
for (index, run) in history.runs.iter().enumerate() {
let (_, period) =
history.edge_and_period(index, 0)?;
words = words.saturating_add(
period.min(run.steps().as_u64()) as usize,
);
if words > budget {
return Ok(false);
}
}
}
words.max(1)
} else if selected.symbol_facts(summary.symbol_id()).is_some() {
0
} else {
runs_len.max(1)
};
if cost > budget {
return Ok(false);
}
budget -= cost;
}
true
} else {
false
}
}
OutputFinalizerRuntime::Rows => {
if rows >= self.output.rows_until_flush() as u64 || rows > 256 {
return Ok(false);
}
if self
.output
.compact_segment_work(rows as usize)
.saturating_add(1)
> 256
{
return Ok(false);
}
if self.output.needs_compact_classifier() {
if rows > 64 {
return Ok(false);
}
let Some(history) = selected.runs.as_ref() else {
return Ok(false);
};
if history.runs.len() > 16 {
return Ok(false);
}
}
false
}
};
let batch = bind(self)?;
if selected.start.as_u64() < batch.readable.0 as u64 {
return Ok(false);
}
let (number, rows) =
self.validate_bound_winner(match_id, selected, batch.readable)?;
#[cfg(test)]
self.check_publication_cancellation()?;
let floor = absolute_row_to_usize(selected.start, "compact source floor")?;
if let OutputFinalizerRuntime::DirectCounts {
summaries,
scratch,
has_reductions,
needs_edge_finalization,
..
} = &mut self.finalizer
{
if *needs_edge_finalization && batch.partition_end > batch.readable.1 {
return Ok(false);
}
let result: Result<bool> = (|| {
let work_units = if needs_reduction_pass {
let mut state = CompactReductions::default();
let (finished, units) = state.advance(
&mut self.output,
summaries,
scratch,
selected,
batch.source,
batch.origin,
None,
&mut read_register,
&mut |_| Ok(()),
)?;
if !finished {
if *has_reductions {
self.output.reset_reductions();
}
scratch.fill(0);
record_work(units)?;
return Ok(false);
}
4 + units + summaries.len()
} else {
fill_summary_facts(selected, summaries, scratch, &mut || Ok(()))?;
4 + 2 * summaries.len()
};
let mut min_floor = floor;
let partition = batch.partition_start..batch.partition_end;
finalize_direct_edge_coords(
summaries,
scratch,
*needs_edge_finalization,
&partition,
&mut min_floor,
)?;
if min_floor < batch.readable.0 {
if *has_reductions {
self.output.reset_reductions();
}
scratch.fill(0);
record_work(work_units)?;
return Ok(false);
}
let row = self
.encoder
.compact_summary_representative(selected, number, false)?;
self.output.reserve_row(row)?;
self.output.reserve_summary(scratch.len())?;
record_work(work_units)?;
self.output.begin_reserved_row(row);
self.output.append_summary(scratch, &mut |_| Ok(()))?;
self.output.retain_source_floor(min_floor);
Ok(true)
})();
match result {
Ok(true) => {}
Ok(false) => return Ok(false),
Err(error) => {
if *has_reductions {
self.output.reset_reductions();
}
scratch.fill(0);
return Err(error);
}
}
} else if self.output.needs_compact_classifier() {
let history = selected.history()?;
let mut segments = [(0usize, 0usize, false); 16];
let mut seg_count = 0usize;
let mut total_class_bytes = 0usize;
for run_idx in 0..history.runs.len() {
let (edge, period) = history.edge_and_period(run_idx, 0)?;
if period != 1 {
return Ok(false);
}
let run_rows = history.runs[run_idx].steps().as_u64() as usize;
let classifier = self
.encoder
.classifier(Sym::from_index(edge.symbol_id.index()))?;
let bytes = run_rows.checked_mul(classifier.name.len()).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE classifier string buffer exceeds i32 offset limit"
.into(),
)
})?;
total_class_bytes =
total_class_bytes.checked_add(bytes).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE classifier byte count overflow".into(),
)
})?;
segments[seg_count] = (run_rows, edge.symbol_id.index(), edge.excluded);
seg_count += 1;
}
if self.output.needs_input_gather() {
let end = floor.checked_add(rows).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact source end exceeds usize".into(),
)
})?;
let _ = absolute_row_from_usize(floor, "compact source start")?;
let _ = absolute_row_from_usize(end, "compact source end")?;
}
let class_before = self.output.class_bytes();
self.output.reserve_compact_rows(rows, total_class_bytes)?;
let estimated_work = self.output.compact_segment_work(rows);
if let Err(error) = record_work(estimated_work + 1) {
self.output.rollback_class_bytes(class_before);
return Err(error);
}
let mut emitted = 0usize;
let mut populated_work = 0usize;
for &(run_rows, sym_idx, excluded) in &segments[..seg_count] {
let classifier = self.encoder.classifier(Sym::from_index(sym_idx))?;
populated_work += self.output.append_reserved_compact_segment(
run_rows,
floor + emitted,
Some(classifier),
number,
(emitted + 1) as i64,
excluded,
);
emitted += run_rows;
}
debug_assert_eq!(emitted, rows);
debug_assert_eq!(populated_work, estimated_work);
} else {
self.output.append_compact_rows(
rows,
floor,
None,
number,
1,
false,
&mut record_work,
)?;
}
self.matches_emitted += 1;
Ok(true)
}
#[cfg(test)]
pub(crate) fn prepare_compact_match_chunk(
&mut self,
progress: &mut CompactMatchPreparation,
selected: &CompactSelection<'_>,
emission: MatchEmissionContext<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<PreparedMatchEmission>> {
self.prepare_compact_match_chunk_with_registers(
progress,
selected,
emission,
&mut |_, _| None,
completed,
)
}
pub(super) fn prepare_compact_match_chunk_with_registers(
&mut self,
progress: &mut CompactMatchPreparation,
selected: &CompactSelection<'_>,
mut emission: MatchEmissionContext<'_>,
read_register: &mut ReadRegister<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<PreparedMatchEmission>> {
if progress.coordinates != (selected.start, selected.end, selected.acceptance) {
return internal_err!(
"MATCH_RECOGNIZE compact selected output identity changed"
);
}
if let Phase::Reductions(state) = &mut progress.phase {
let OutputFinalizerRuntime::DirectCounts {
summaries, scratch, ..
} = &mut self.finalizer
else {
unreachable!("bound selected reductions")
};
let (finished, _) = state.advance(
&mut self.output,
summaries,
scratch,
selected,
emission.batches,
emission.global_offset,
emission.history,
read_register,
completed,
)?;
if !finished {
return Ok(None);
}
progress.phase = Phase::Rows;
return Ok(None);
}
if progress.phase == Phase::Rows {
self.output.maybe_flush_with_work(
emission.batches,
emission.global_offset,
emission.history,
emission.pending_output,
completed,
)?;
if matches!(self.finalizer, OutputFinalizerRuntime::DirectCounts { .. }) {
let row = self.encoder.compact_summary_representative(
selected,
progress.match_number,
self.output.needs_compact_classifier(),
)?;
if let OutputFinalizerRuntime::DirectCounts { scratch, .. } =
&self.finalizer
{
self.output.reserve_summary(scratch.len())?;
}
self.output.reserve_row(row)?;
self.output.begin_reserved_row(row);
let mut work = CoarseWorkBatch::new(completed);
self.output.append_classifier_fields(
row.classifier_symbol().map(|symbol| symbol.to_index()),
&mut work,
)?;
work.complete_one()?;
work.finish()?;
progress.emitted_rows = 1;
} else {
let history = if self.output.needs_compact_classifier() {
Some(selected.history()?)
} else {
None
};
let mut budget = self.output.rows_until_flush();
let track_presence = self.encoder.tracks_unmatched_rows();
let source_start =
absolute_row_to_usize(selected.start, "compact source start")?;
while budget != 0 && progress.emitted_rows != progress.output_rows {
let mut rows =
(progress.output_rows - progress.emitted_rows).min(budget);
let (classifier, excluded) = if let Some(history) = history {
let (edge, period) = history
.edge_and_period(progress.run_index, progress.word_offset)?;
let remaining = history.runs[progress.run_index].steps().as_u64()
- progress.word_offset;
rows = rows.min(if period == 1 { remaining as usize } else { 1 });
(
Some(
self.encoder.classifier(Sym::from_index(
edge.symbol_id.index(),
))?,
),
edge.excluded,
)
} else {
(None, false)
};
let first_sequence = (progress.emitted_rows + 1) as i64;
let absolute = source_start
.checked_add(progress.emitted_rows)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact source row exceeds usize".into(),
)
})?;
if track_presence {
let mut work = CoarseWorkBatch::new(completed);
for offset in 0..rows {
let row = absolute_row_from_usize(
absolute + offset,
"compact matched row",
)?;
self.row_presence.mark_with_work(row, work.reporter())?;
work.complete_one()?;
}
work.finish()?;
}
self.output.append_compact_rows(
rows,
absolute,
classifier,
progress.match_number,
first_sequence,
excluded,
completed,
)?;
progress.emitted_rows += rows;
budget -= rows;
if let Some(history) = history {
progress.word_offset += rows as u64;
if progress.word_offset
== history.runs[progress.run_index].steps().as_u64()
{
progress.run_index += 1;
progress.word_offset = 0;
}
}
}
}
if progress.emitted_rows != progress.output_rows {
return Ok(None);
}
self.finish_direct_summaries(&emission.partition, completed)?;
let prepared = self.finalize_match(true, emission.reborrow(), completed)?;
progress.phase = Phase::Done;
return Ok(Some(prepared));
}
internal_err!("MATCH_RECOGNIZE completed compact output resumed")
}
}
fn fill_summary_facts(
selected: &CompactSelection<'_>,
summaries: &[ExecutableDirectCountSummary],
scratch: &mut [u64],
completed: &mut impl FnMut() -> Result<()>,
) -> Result<()> {
for (value, summary) in scratch.iter_mut().zip(summaries) {
*value = captured_summary(selected, summary)?.ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"MATCH_RECOGNIZE selected winner omitted a requested summary symbol"
)
})?;
completed()?;
}
Ok(())
}
#[inline]
pub(super) fn captured_summary(
selected: &CompactSelection<'_>,
summary: &ExecutableDirectCountSummary,
) -> Result<Option<u64>> {
if let Some(edge) = summary.edge()
&& edge.logical_offset > 0
{
let Some(facts) = selected.symbol_facts(summary.symbol_id()) else {
return Ok(None);
};
let lo = edge.logical_offset as u64;
if facts.count <= lo {
return Ok(Some(0));
}
if facts.last.as_u64() - facts.first.as_u64() + 1 == facts.count {
let row = if edge.last {
facts.last.as_u64() - lo
} else {
facts.first.as_u64() + lo
};
return Ok(Some(row + 1));
}
return Ok(None);
}
selected
.symbol_facts(summary.symbol_id())
.map(|facts| compact_fact(0, summary, facts, selected))
.transpose()
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct OffsetEdgeCursor {
position: u64,
matches: usize,
}
impl OffsetEdgeCursor {
pub(super) fn advance(
&mut self,
history: &LaneSelectedRuns<'_>,
run_idx: usize,
symbol: Option<crate::core::SymbolId>,
last: bool,
remaining_lo: &mut usize,
budget: usize,
) -> Result<(bool, Option<u64>, usize)> {
let run = history.runs[run_idx];
let first = run.first_row().as_u64();
let steps = run.steps().as_u64();
let (_, period) = history.edge_and_period(run_idx, 0)?;
let coordinate =
|position| first + if last { steps - 1 - position } else { position } + 1;
let Some(symbol) = symbol else {
let found = if (*remaining_lo as u64) < steps {
Some(coordinate(*remaining_lo as u64))
} else {
*remaining_lo -= steps as usize;
None
};
return Ok((true, found, 1));
};
let mut work = 0;
while self.position < steps && work < budget {
let offset = if last {
steps - 1 - self.position
} else {
self.position
};
let (edge, _) = history.edge_and_period(run_idx, offset)?;
work += 1;
self.position += 1;
if edge.symbol_id == symbol {
if *remaining_lo == 0 {
return Ok((true, Some(coordinate(self.position - 1)), work));
}
*remaining_lo -= 1;
self.matches += 1;
}
if self.position == period {
let cycles = (steps - self.position) / period;
let skip = remaining_lo
.checked_div(self.matches)
.map_or(cycles, |count| cycles.min(count as u64));
self.position += skip * period;
*remaining_lo -= skip as usize * self.matches;
}
}
Ok((self.position == steps, None, work))
}
}
fn compact_fact(
previous: u64,
summary: &ExecutableDirectCountSummary,
facts: SymbolFacts,
selected: &CompactSelection<'_>,
) -> Result<u64> {
if facts.count == 0 {
return Ok(0);
}
match summary.metadata() {
Some(MetadataEndpoint::Classifier { last }) => {
let symbol = if let Some(symbol) = summary.symbol_id() {
symbol
} else {
let history = selected.history()?;
let index = if last { history.runs.len() - 1 } else { 0 };
let offset = if last {
history.runs[index].steps().as_u64() - 1
} else {
0
};
history.edge_and_period(index, offset)?.0.symbol_id
};
Ok(symbol.index() as u64)
}
Some(MetadataEndpoint::Sequence { last, .. }) => {
let row = if last { facts.last } else { facts.first };
Ok(merge_edge(
previous,
last,
row.as_u64() - selected.start.as_u64() + 1,
))
}
None => merge_direct_summary(
previous,
summary,
facts.count,
(facts.first, facts.last),
),
}
}
pub(super) fn reduce_summary_words(
selected: &CompactSelection<'_>,
run_index: &mut usize,
word_offset: &mut u64,
summaries: &[ExecutableDirectCountSummary],
scratch: &mut [u64],
words: usize,
completed: &mut impl FnMut() -> Result<()>,
) -> Result<usize> {
let mut processed = 0;
let history = selected.history()?;
for _ in 0..words {
let Some(run) = history.runs.get(*run_index) else {
break;
};
let (edge, period) = history.edge_and_period(*run_index, *word_offset)?;
let multiplicity = 1 + (run.steps().as_u64() - 1 - *word_offset) / period;
let first = run.first_row().as_u64() + *word_offset;
let last = first + (multiplicity - 1) * period;
update_direct_summaries(
summaries,
scratch,
&mut [],
edge.symbol_id.index(),
|previous, summary, _| {
if summary.edge().is_some_and(|e| e.logical_offset > 0) {
return Ok(previous);
}
compact_fact(
previous,
summary,
SymbolFacts {
count: multiplicity,
first: AbsoluteRow::new(first),
last: AbsoluteRow::new(last),
},
selected,
)
},
completed,
)?;
processed += 1;
*word_offset += 1;
if *word_offset == period.min(run.steps().as_u64()) {
*run_index += 1;
*word_offset = 0;
}
}
Ok(processed)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{NormalizedPattern, Pattern, Symbol};
use crate::execution::common::memory::new_unbounded_state_memory;
use datafusion::arrow::array::{Array, Int32Array};
use datafusion::arrow::datatypes::{DataType, Field};
#[test]
fn cross_head_compact_winner_spans_history_into_current_batches() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int32, false)]));
let full = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int32Array::from(vec![10, 20, 30, 40, 50, 60]))],
)?;
let tail = BatchCollection::try_new(vec![full.slice(3, 3)], Arc::clone(&schema))?;
let mut history = SharedHistoryBuffer::new(
Arc::clone(&schema),
new_unbounded_state_memory().new_empty(),
);
history.append(full.slice(0, 2))?;
history.append(full.slice(2, 1))?;
let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let plan = ExecutableOutputPlan::try_rows(
schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![0], vec![], vec![]),
Arc::from([]),
RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
&compiled,
)?;
let selected = CompactSelection::from_extent(
AbsoluteRow::new(1),
AbsoluteRow::new(4),
AbsoluteRow::new(4),
)?;
let mut without_history = MatchAccumulator::try_new_unbounded(
Arc::clone(&schema),
Arc::clone(&compiled),
16,
Arc::clone(&plan),
)?;
let mut staged = PendingOutput::default();
let err = without_history
.begin_compact_match(
1,
&selected,
&MatchEmissionContext {
partition: 0..6,
global_offset: 3,
batches: &tail,
pending_output: &mut staged,
history: None,
},
&mut |_| Ok(()),
)
.err()
.expect("cross-head compact winner without history must fail");
assert!(err.to_string().contains("invalid physical bounds"));
for flush_threshold in [16, 2] {
let mut acc = MatchAccumulator::try_new_unbounded(
Arc::clone(&schema),
Arc::clone(&compiled),
flush_threshold,
Arc::clone(&plan),
)?;
let mut staged = PendingOutput::default();
let mut published = PendingOutput::default();
let mut progress = acc.begin_compact_match(
1,
&selected,
&MatchEmissionContext {
partition: 0..6,
global_offset: 3,
batches: &tail,
pending_output: &mut staged,
history: Some(&history),
},
&mut |_| Ok(()),
)?;
let mut governor = WorkGovernor::default();
let prepared = loop {
if let Some(done) = progress.advance(
&mut acc,
&selected,
MatchEmissionContext {
partition: 0..6,
global_offset: 3,
batches: &tail,
pending_output: &mut staged,
history: Some(&history),
},
&mut governor,
YieldPolicy::from_test_budget(1),
|| false,
)? {
break done;
}
};
acc.prepare_match_publication(&staged, &mut published)?;
acc.publish_prepared_match(prepared, &mut staged, &mut published);
let mut emitted = Vec::new();
while let Some(batch) = published.pop_front() {
let values = batch
.column(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap();
emitted.extend(values.values().iter().copied());
}
if let Some(batch) = acc.flush_collection(&tail, 3, Some(&history), false)? {
let values = batch
.column(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap();
emitted.extend(values.values().iter().copied());
}
assert_eq!(emitted, vec![20, 30, 40, 50]);
}
history.prune(2);
assert_eq!(history.head_index(), 2);
let mut after_prune = MatchAccumulator::try_new_unbounded(
Arc::clone(&schema),
Arc::clone(&compiled),
16,
Arc::clone(&plan),
)?;
let mut staged = PendingOutput::default();
let err = after_prune
.begin_compact_match(
1,
&selected,
&MatchEmissionContext {
partition: 0..6,
global_offset: 3,
batches: &tail,
pending_output: &mut staged,
history: Some(&history),
},
&mut |_| Ok(()),
)
.err()
.expect("pruned history start must fail");
assert!(err.to_string().contains("invalid physical bounds"));
Ok(())
}
#[test]
fn wide_direct_counts_without_summary_history_yield_and_poll_cancellation_in_chunks()
-> Result<()> {
use crate::config::CancellationPolicy;
use crate::core::MatchSummaryField;
use datafusion::arrow::array::Int64Array;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int64, true)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(vec![
Some(10),
Some(20),
Some(30),
Some(40),
]))],
)?;
let batches = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let summary_count = COARSE_WORK_BATCH_SIZE * 2 + 5;
let summaries = (0..summary_count)
.map(|index| {
let field = MatchSummaryField::new(
index,
Arc::new(Field::new(
format!("m{index}"),
DataType::Int64,
index % 3 != 0,
)),
);
if index % 3 == 0 {
ExecutableDirectCountSummary::new(field, None)
} else {
ExecutableDirectCountSummary::new_edge(field, None, 0, index % 3 == 2)
}
})
.collect();
let plan = ExecutableOutputPlan::try_direct_counts(
schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
summaries,
&compiled,
)?;
let selected = CompactSelection::from_extent(
AbsoluteRow::new(0),
AbsoluteRow::new(3),
AbsoluteRow::new(3),
)?;
let mut acc = MatchAccumulator::try_new_unbounded(
Arc::clone(&schema),
Arc::clone(&compiled),
16,
Arc::clone(&plan),
)?;
assert_eq!(acc.compact_demand(), ClassifierDemand::Symbols(0));
let mut staged = PendingOutput::default();
let mut published = PendingOutput::default();
let mut progress = acc.begin_compact_match(
1,
&selected,
&MatchEmissionContext {
partition: 0..4,
global_offset: 0,
batches: &batches,
pending_output: &mut staged,
history: None,
},
&mut |_| Ok(()),
)?;
assert!(matches!(progress.phase, Phase::Reductions(_)));
let mut intermediate_work = Vec::new();
let prepared = loop {
let mut chunk_work = 0;
let step = acc.prepare_compact_match_chunk(
&mut progress,
&selected,
MatchEmissionContext {
partition: 0..4,
global_offset: 0,
batches: &batches,
pending_output: &mut staged,
history: None,
},
&mut |units| {
chunk_work += units;
Ok(())
},
)?;
if let Some(done) = step {
break done;
}
intermediate_work.push(chunk_work);
};
assert_eq!(
intermediate_work,
vec![COARSE_WORK_BATCH_SIZE, COARSE_WORK_BATCH_SIZE, 5]
);
acc.prepare_match_publication(&staged, &mut published)?;
acc.publish_prepared_match(prepared, &mut staged, &mut published);
let output = acc
.flush_collection(&batches, 0, None, false)?
.expect("flushed wide direct-count summary row");
assert_eq!(output.num_rows(), 1);
assert_eq!(output.num_columns(), summary_count);
for index in 0..summary_count {
let values = output
.column(index)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let expected = match index % 3 {
0 => 4,
1 => 10,
_ => 40,
};
assert_eq!(values.value(0), expected, "summary column {index}");
}
let mut cancelling = MatchAccumulator::try_new_unbounded(
Arc::clone(&schema),
Arc::clone(&compiled),
16,
plan,
)?;
let mut staged = PendingOutput::default();
let mut preparation = cancelling.begin_compact_match(
1,
&selected,
&MatchEmissionContext {
partition: 0..4,
global_offset: 0,
batches: &batches,
pending_output: &mut staged,
history: None,
},
&mut |_| Ok(()),
)?;
let mut governor = WorkGovernor::default();
governor.bind_cancellation_policy(CancellationPolicy::try_from_configured(
COARSE_WORK_BATCH_SIZE,
0,
)?)?;
let aborted = AtomicBool::new(false);
let polls = AtomicUsize::new(0);
let check_abort = || {
polls.fetch_add(1, Ordering::Relaxed);
aborted.load(Ordering::Relaxed)
};
let first = preparation.advance(
&mut cancelling,
&selected,
MatchEmissionContext {
partition: 0..4,
global_offset: 0,
batches: &batches,
pending_output: &mut staged,
history: None,
},
&mut governor,
YieldPolicy::from_test_budget(COARSE_WORK_BATCH_SIZE),
check_abort,
)?;
assert!(first.is_none());
assert!(polls.load(Ordering::Relaxed) >= 1);
aborted.store(true, Ordering::Relaxed);
let err = preparation
.advance(
&mut cancelling,
&selected,
MatchEmissionContext {
partition: 0..4,
global_offset: 0,
batches: &batches,
pending_output: &mut staged,
history: None,
},
&mut governor,
YieldPolicy::from_test_budget(COARSE_WORK_BATCH_SIZE),
check_abort,
)
.err()
.expect("aborted wide summary preparation must fail during next chunk");
assert!(err.to_string().contains("cancelled"), "{err}");
Ok(())
}
#[test]
fn direct_edge_offset_shift_defaults_and_history_floor() -> Result<()> {
use crate::core::{
MatchSummaryField, NavigationOffsets, NormalizedPattern, Pattern,
RepetitionQuantifier, Symbol,
};
use crate::execution::matching::ExecutableEdge;
use datafusion::arrow::array::Int64Array;
use datafusion_common::ScalarValue;
let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int64, true)]));
let full = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(vec![
Some(10),
Some(20),
Some(30),
None,
Some(50),
Some(60),
Some(70),
Some(80),
]))],
)?;
let tail = BatchCollection::try_new(vec![full.slice(3, 5)], Arc::clone(&schema))?;
let mut history = SharedHistoryBuffer::new(
Arc::clone(&schema),
new_unbounded_state_memory().new_empty(),
);
history.append(full.slice(0, 3))?;
let pattern = NormalizedPattern::Ast(Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
RepetitionQuantifier::OneOrMore,
));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let mk_field = |id: usize, name: &str| {
MatchSummaryField::new(id, Arc::new(Field::new(name, DataType::Int64, true)))
};
let summaries = vec![
ExecutableDirectCountSummary::new_edge_spec(
mk_field(0, "first_1"),
None,
ExecutableEdge {
input_column: 0,
last: false,
logical_offset: 1,
physical_shift: 0,
default_value: None,
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(1, "last_2"),
None,
ExecutableEdge {
input_column: 0,
last: true,
logical_offset: 2,
physical_shift: 0,
default_value: None,
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(2, "prev_hist"),
None,
ExecutableEdge {
input_column: 0,
last: false,
logical_offset: 0,
physical_shift: -2,
default_value: Some(ScalarValue::Int64(Some(-1))),
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(3, "prev_in_bounds_null"),
None,
ExecutableEdge {
input_column: 0,
last: false,
logical_offset: 1,
physical_shift: -1,
default_value: Some(ScalarValue::Int64(Some(-1))),
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(4, "next_oob_default"),
None,
ExecutableEdge {
input_column: 0,
last: true,
logical_offset: 0,
physical_shift: 1,
default_value: Some(ScalarValue::Int64(Some(-9))),
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(5, "absent_default"),
None,
ExecutableEdge {
input_column: 0,
last: false,
logical_offset: 10,
physical_shift: 0,
default_value: Some(ScalarValue::Int64(Some(-7))),
},
),
];
let spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
vec![],
vec![],
vec![],
NavigationOffsets::try_from_raw(2, 1).unwrap(),
);
let plan = ExecutableOutputPlan::try_direct_counts(
schema.as_ref(),
spec,
Arc::from([]),
summaries,
&compiled,
)?;
assert!(!plan.stream().emits_navigation_buffer_rows());
let mut acc = MatchAccumulator::try_new_unbounded(
Arc::clone(&schema),
Arc::clone(&compiled),
16,
plan,
)?;
let selected = CompactSelection::from_extent(
AbsoluteRow::new(3),
AbsoluteRow::new(7),
AbsoluteRow::new(7),
)?;
let mut staged = PendingOutput::default();
let mut published = PendingOutput::default();
let mut progress = acc.begin_compact_match(
1,
&selected,
&MatchEmissionContext {
partition: 0..8,
global_offset: 3,
batches: &tail,
pending_output: &mut staged,
history: Some(&history),
},
&mut |_| Ok(()),
)?;
let mut governor = WorkGovernor::default();
let prepared = loop {
if let Some(done) = progress.advance(
&mut acc,
&selected,
MatchEmissionContext {
partition: 0..8,
global_offset: 3,
batches: &tail,
pending_output: &mut staged,
history: Some(&history),
},
&mut governor,
YieldPolicy::Disabled,
|| false,
)? {
break done;
}
};
acc.prepare_match_publication(&staged, &mut published)?;
acc.publish_prepared_match(prepared, &mut staged, &mut published);
assert_eq!(acc.min_buffered_row(), Some(1));
let out = acc
.flush_collection(&tail, 3, Some(&history), false)?
.expect("flushed direct-edge batch");
assert_eq!(out.num_rows(), 1);
let col = |i: usize| {
let a = out.column(i).as_any().downcast_ref::<Int64Array>().unwrap();
(!a.is_null(0)).then(|| a.value(0))
};
assert_eq!(col(0), Some(50));
assert_eq!(col(1), Some(60));
assert_eq!(col(2), Some(20));
assert_eq!(col(3), None);
assert_eq!(col(4), Some(-9));
assert_eq!(col(5), Some(-7));
Ok(())
}
#[test]
fn direct_winner_finalizes_shifted_edges_and_hands_off_evicted_history() -> Result<()>
{
use crate::core::{
MatchSummaryField, NavigationOffsets, NormalizedPattern, Pattern,
RepetitionQuantifier, Symbol,
};
use crate::execution::matching::ExecutableEdge;
use datafusion::arrow::array::Int64Array;
use datafusion_common::ScalarValue;
let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int64, true)]));
let full_batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(vec![
Some(10),
Some(20),
Some(30),
None,
Some(50),
Some(60),
Some(70),
Some(80),
]))],
)?;
let full =
BatchCollection::try_new(vec![full_batch.clone()], Arc::clone(&schema))?;
let tail =
BatchCollection::try_new(vec![full_batch.slice(3, 5)], Arc::clone(&schema))?;
let partial =
BatchCollection::try_new(vec![full_batch.slice(0, 7)], Arc::clone(&schema))?;
let pattern = NormalizedPattern::Ast(Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
RepetitionQuantifier::OneOrMore,
));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let mk_field = |id: usize, name: &str| {
MatchSummaryField::new(id, Arc::new(Field::new(name, DataType::Int64, true)))
};
let summaries = vec![
ExecutableDirectCountSummary::new_edge_spec(
mk_field(0, "prev_in_bounds"),
None,
ExecutableEdge {
input_column: 0,
last: false,
logical_offset: 0,
physical_shift: -2,
default_value: Some(ScalarValue::Int64(Some(-1))),
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(1, "prev_in_bounds_null"),
None,
ExecutableEdge {
input_column: 0,
last: false,
logical_offset: 1,
physical_shift: -1,
default_value: Some(ScalarValue::Int64(Some(-1))),
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(2, "next_oob_default"),
None,
ExecutableEdge {
input_column: 0,
last: true,
logical_offset: 0,
physical_shift: 1,
default_value: Some(ScalarValue::Int64(Some(-9))),
},
),
ExecutableDirectCountSummary::new_edge_spec(
mk_field(3, "absent_default"),
None,
ExecutableEdge {
input_column: 0,
last: false,
logical_offset: 10,
physical_shift: 0,
default_value: Some(ScalarValue::Int64(Some(-7))),
},
),
];
let spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
vec![],
vec![],
vec![],
NavigationOffsets::try_from_raw(2, 1).unwrap(),
);
let make_acc = || -> Result<MatchAccumulator> {
let plan = ExecutableOutputPlan::try_direct_counts(
schema.as_ref(),
spec.clone(),
Arc::from([]),
summaries.clone(),
&compiled,
)?;
MatchAccumulator::try_new_unbounded(
Arc::clone(&schema),
Arc::clone(&compiled),
16,
plan,
)
};
let selected = CompactSelection::from_extent(
AbsoluteRow::new(3),
AbsoluteRow::new(7),
AbsoluteRow::new(7),
)?;
let mut acc = make_acc()?;
assert!(acc.can_append_direct_winner());
let mut governor = WorkGovernor::default();
assert!(acc.try_publish_direct_winner(
1,
&selected,
0..8,
0,
&full,
&mut governor,
|| false,
|_, _| None,
)?);
assert_eq!(acc.min_buffered_row(), Some(1));
assert_eq!(acc.len(), 1);
let out = acc
.flush_collection(&full, 0, None, false)?
.expect("flushed direct batch");
let col = |i: usize| {
let a = out.column(i).as_any().downcast_ref::<Int64Array>().unwrap();
(!a.is_null(0)).then(|| a.value(0))
};
assert_eq!(col(0), Some(20));
assert_eq!(col(1), None);
assert_eq!(col(2), Some(-9));
assert_eq!(col(3), Some(-7));
let mut handoff_prev = make_acc()?;
assert!(!handoff_prev.try_publish_direct_winner(
1,
&selected,
0..8,
3,
&tail,
&mut governor,
|| false,
|_, _| None,
)?);
assert_eq!(handoff_prev.len(), 0);
assert_eq!(handoff_prev.matches_emitted, 0);
assert_eq!(handoff_prev.min_buffered_row(), None);
let shorter = CompactSelection::from_extent(
AbsoluteRow::new(3),
AbsoluteRow::new(6),
AbsoluteRow::new(6),
)?;
let mut handoff_next = make_acc()?;
assert!(!handoff_next.try_publish_direct_winner(
1,
&shorter,
0..8,
0,
&partial,
&mut governor,
|| false,
|_, _| None,
)?);
assert_eq!(handoff_next.len(), 0);
assert_eq!(handoff_next.matches_emitted, 0);
Ok(())
}
}