use super::*;
#[test]
fn compact_classifier_demand_is_bound_at_construction() {
let (test_case, _) = compact_cycle_harness(4, 0);
let b = SymbolId::try_new(2, 3).unwrap();
let bits_only = ExecutableOutputPlan::try_rows(
test_case.schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![], vec![], vec!["B".into()]),
Arc::from([b]),
test_case.rows_per_match.clone(),
&test_case.compiled,
)
.unwrap();
let requested = direct_count_output(
&test_case.schema,
&test_case.compiled,
vec![],
vec![None, Some(b), Some(b)],
);
let no_labels =
direct_count_output(&test_case.schema, &test_case.compiled, vec![], vec![None]);
let reservation = crate::execution::common::memory::new_unbounded_state_memory();
for (output, demand) in [
(bits_only, ClassifierDemand::All),
(requested, ClassifierDemand::Symbols(2)),
(no_labels, ClassifierDemand::Symbols(0)),
] {
let accumulator = MatchAccumulator::try_new(
Arc::clone(&test_case.compiled),
16,
output,
reservation.new_empty(),
reservation.new_empty(),
)
.unwrap();
assert_eq!(accumulator.compact_demand(), demand);
}
}
#[test]
fn compact_cycle_output_matches_checked_rows_counts_and_metadata() {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CaseName {
CardinalityRows,
MetadataRows,
CountsWithMetadata,
CountsWithInputAndMetadata,
InputWithoutCounts,
PartitionKeyAndCount,
WideCountsWithInput,
WideUnqualifiedSummaries,
InputRows,
InputRowsWithMetadata,
WithUnmatchedRows,
}
struct Case {
name: CaseName,
output: Arc<ExecutableOutputPlan>,
flush_threshold: usize,
first_chunk_work: Option<usize>,
expected_rows: usize,
}
use CaseName::*;
const ROWS: usize = 600;
const ORIGIN: usize = 41;
let (mut test_case, scan) =
compact_cycle_harness_with_cycle(ROWS, ORIGIN, &["A", "A", "B"]);
let mut fields = test_case.schema.fields().to_vec();
fields.extend([
Arc::new(Field::new("nullable_key", DataType::Int64, true)),
Arc::new(Field::new("modulo_key", DataType::Int64, false)),
Arc::new(Field::new("partition_key", DataType::Int64, false)),
]);
let mut columns = test_case.batches.batch(0).columns().to_vec();
columns.extend([
Arc::new(Int64Array::from(
(0..ROWS)
.map(|row| (row != 0).then_some(7))
.collect::<Vec<_>>(),
)) as ArrayRef,
Arc::new(Int64Array::from_iter_values(
(0..ROWS as i64).map(|row| row % 2),
)),
Arc::new(Int64Array::from(vec![37; ROWS])),
]);
test_case.schema = Arc::new(Schema::new(fields));
let batch = RecordBatch::try_new(Arc::clone(&test_case.schema), columns).unwrap();
test_case.batches = BatchCollection::try_new(
vec![batch.slice(0, 113), batch.slice(113, ROWS - 113)],
Arc::clone(&test_case.schema),
)
.unwrap();
let path = scan.materialize_selected().unwrap();
let ids = [
SymbolId::try_new(1, 3).unwrap(),
SymbolId::try_new(2, 3).unwrap(),
];
let metadata = MatchRecognizeOutputSpec::new(
vec![],
vec![
MatchMetadataColumn::Classifier,
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::MatchSequenceNumber,
MatchMetadataColumn::Excluded,
],
vec!["A".into(), "B".into()],
);
let counts = direct_count_output(
&test_case.schema,
&test_case.compiled,
vec![],
vec![None, Some(ids[0]), Some(ids[1])],
);
let ExecutableOutputFinalizer::DirectCounts { summaries } = counts.finalizer() else {
unreachable!()
};
let counts_with_metadata = ExecutableOutputPlan::try_direct_counts(
test_case.schema.as_ref(),
metadata.clone(),
Arc::from(ids),
summaries.to_vec(),
&test_case.compiled,
)
.unwrap();
let counts_with_input = ExecutableOutputPlan::try_direct_counts(
test_case.schema.as_ref(),
metadata
.clone()
.with_passthrough_input_indices(vec![0, 2, 3]),
Arc::from(ids),
summaries.to_vec(),
&test_case.compiled,
)
.unwrap();
let empty_counts_with_input = direct_count_output(
&test_case.schema,
&test_case.compiled,
vec![0, 2, 3],
vec![],
);
let wide_counts_with_input = direct_count_output(
&test_case.schema,
&test_case.compiled,
vec![0, 2, 3],
(0..=COARSE_WORK_BATCH_SIZE)
.map(|index| [None, Some(ids[0]), Some(ids[1])][index % 3])
.collect(),
);
let wide_unqualified = ExecutableOutputPlan::try_direct_counts(
test_case.schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
(0..=COARSE_WORK_BATCH_SIZE)
.map(|index| {
let field = MatchSummaryField::new(
index,
Arc::new(Field::new("measure", DataType::Int64, index % 3 != 0)),
);
if index % 3 == 0 {
ExecutableDirectCountSummary::new(field, None)
} else {
ExecutableDirectCountSummary::new_edge(field, None, 2, index % 3 == 2)
}
})
.collect(),
&test_case.compiled,
)
.unwrap();
let cases = [
Case {
name: CardinalityRows,
output: ExecutableOutputPlan::try_rows(
test_case.schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
test_case.rows_per_match.clone(),
&test_case.compiled,
)
.unwrap(),
flush_threshold: 17,
first_chunk_work: None,
expected_rows: ROWS,
},
Case {
name: MetadataRows,
output: ExecutableOutputPlan::try_rows(
test_case.schema.as_ref(),
metadata.clone(),
Arc::from(ids),
test_case.rows_per_match.clone(),
&test_case.compiled,
)
.unwrap(),
flush_threshold: 17,
first_chunk_work: None,
expected_rows: ROWS,
},
Case {
name: CountsWithMetadata,
output: counts_with_metadata,
flush_threshold: 17,
first_chunk_work: None,
expected_rows: 1,
},
Case {
name: CountsWithInputAndMetadata,
output: counts_with_input,
flush_threshold: 17,
first_chunk_work: None,
expected_rows: 1,
},
Case {
name: PartitionKeyAndCount,
output: direct_count_output(
&test_case.schema,
&test_case.compiled,
vec![4],
vec![None],
),
flush_threshold: 17,
first_chunk_work: None,
expected_rows: 1,
},
Case {
name: InputWithoutCounts,
output: empty_counts_with_input,
flush_threshold: 17,
first_chunk_work: None,
expected_rows: 1,
},
Case {
name: WideCountsWithInput,
output: wide_counts_with_input,
flush_threshold: 17,
first_chunk_work: Some(COARSE_WORK_BATCH_SIZE),
expected_rows: 1,
},
Case {
name: WideUnqualifiedSummaries,
output: wide_unqualified,
flush_threshold: 17,
first_chunk_work: None,
expected_rows: 1,
},
Case {
name: InputRows,
output: ExecutableOutputPlan::try_rows(
test_case.schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![0, 2, 3], vec![], vec![]),
Arc::from([]),
test_case.rows_per_match.clone(),
&test_case.compiled,
)
.unwrap(),
flush_threshold: 512,
first_chunk_work: Some(513),
expected_rows: ROWS,
},
Case {
name: WithUnmatchedRows,
output: ExecutableOutputPlan::try_rows(
test_case.schema.as_ref(),
metadata.clone().with_passthrough_input_indices(vec![0]),
Arc::from(ids),
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
&test_case.compiled,
)
.unwrap(),
flush_threshold: 17,
first_chunk_work: None,
expected_rows: ROWS,
},
Case {
name: InputRowsWithMetadata,
output: ExecutableOutputPlan::try_rows(
test_case.schema.as_ref(),
metadata.with_passthrough_input_indices(vec![0, 2, 3]),
Arc::from(ids),
test_case.rows_per_match.clone(),
&test_case.compiled,
)
.unwrap(),
flush_threshold: 17,
first_chunk_work: None,
expected_rows: ROWS,
},
];
for Case {
name,
output,
flush_threshold,
first_chunk_work,
expected_rows,
} in cases
{
let mut compact = MatchAccumulator::try_new_unbounded(
Arc::clone(&test_case.compiled),
flush_threshold,
Arc::clone(&output),
)
.unwrap();
let mut selected = scan.selected_runs().unwrap().unwrap();
let demand = match name {
CardinalityRows
| InputRows
| WideUnqualifiedSummaries
| InputWithoutCounts
| PartitionKeyAndCount => ClassifierDemand::Symbols(0),
WideCountsWithInput => ClassifierDemand::Symbols(3),
_ => ClassifierDemand::All,
};
assert_eq!(compact.compact_demand(), demand, "{name:?}");
if demand == ClassifierDemand::Symbols(0) {
selected.runs = None;
}
let mut reference = MatchAccumulator::try_new_unbounded(
Arc::clone(&test_case.compiled),
flush_threshold,
output,
)
.unwrap();
let mut staged = PendingOutput::default();
if matches!(name, WideCountsWithInput | WideUnqualifiedSummaries) {
assert!(!compact.can_append_direct_winner());
assert!(compact.output.is_empty());
}
let mut actual = PendingOutput::default();
let mut expected = PendingOutput::default();
let mut progress = compact
.begin_compact_match(
7,
&selected,
&test_case.emission_context(ORIGIN..ORIGIN + ROWS, ORIGIN, &mut staged),
&mut |_| Ok(()),
)
.unwrap();
let mut chunks = 0;
let mut governor = crate::execution::common::work::WorkGovernor::default();
let prepared = loop {
chunks += 1;
let mut completed = 0;
let step = compact
.prepare_compact_match_chunk(
&mut progress,
&selected,
test_case.emission_context(
ORIGIN..ORIGIN + ROWS,
ORIGIN,
&mut staged,
),
&mut |units| {
completed += units;
governor.record_completed(units, || false)
},
)
.unwrap();
assert!(actual.is_empty());
assert_eq!(compact.matches_emitted, 0);
if matches!(name, WideCountsWithInput | WideUnqualifiedSummaries)
&& step.is_none()
{
assert!(
completed <= COARSE_WORK_BATCH_SIZE,
"{name:?} chunk {chunks} reported {completed} work units"
);
}
if chunks == 1
&& let Some(expected_work) = first_chunk_work
{
assert!(step.is_none(), "{name:?} must split its first work chunk");
assert_eq!(completed, expected_work, "{name:?}");
}
if let Some(prepared) = step {
break prepared;
}
};
if expected_rows == ROWS {
assert_eq!(chunks, ROWS.div_ceil(flush_threshold), "{name:?}");
} else if !matches!(name, WideCountsWithInput | WideUnqualifiedSummaries) {
assert_eq!(chunks, 1, "bounded summary {name:?}");
}
compact
.prepare_match_publication(&staged, &mut actual)
.unwrap();
compact.publish_prepared_match(prepared, &mut staged, &mut actual);
if name == WithUnmatchedRows {
for row in ORIGIN - 1..=ORIGIN + ROWS {
assert_eq!(
compact.row_presence.contains(AbsoluteRow::new(row as u64)),
(ORIGIN..ORIGIN + ROWS).contains(&row)
);
}
}
reference
.record_test_match(
7,
&path,
test_case.emission_context(ORIGIN..ORIGIN + ROWS, ORIGIN, &mut expected),
)
.unwrap();
for (accumulator, pending) in
[(&mut compact, &mut actual), (&mut reference, &mut expected)]
{
if let Some(tail) = accumulator
.flush_collection(&test_case.batches, ORIGIN, None, false)
.unwrap()
{
pending.push_back(tail).unwrap();
}
assert_eq!(accumulator.take_matches_total(), 1);
}
let values = |pending: &PendingOutput| {
pending
.iter()
.flat_map(|batch| {
(0..batch.num_rows())
.map(|row| {
batch
.columns()
.iter()
.map(|column| {
ScalarValue::try_from_array(column, row).unwrap()
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()
};
let expected_schema = expected.iter().next().unwrap().schema();
assert!(actual.iter().all(|batch| batch.schema() == expected_schema));
let actual = values(&actual);
assert_eq!(actual, values(&expected));
assert_eq!(actual.len(), expected_rows, "{name:?}");
if name == MetadataRows {
assert_eq!(actual[0][3], ScalarValue::Boolean(Some(true)));
}
if matches!(name, CountsWithMetadata | CountsWithInputAndMetadata) {
assert_eq!(
&actual[0][actual[0].len() - 3..],
&[
ScalarValue::Int64(Some(600)),
ScalarValue::Int64(Some(400)),
ScalarValue::Int64(Some(200))
]
);
}
if matches!(
name,
CountsWithInputAndMetadata | InputWithoutCounts | WideCountsWithInput
) {
assert_eq!(
&actual[0][..3],
&[
ScalarValue::Int64(Some(0)),
ScalarValue::Int64(None),
ScalarValue::Int64(Some(0)),
]
);
}
if name == PartitionKeyAndCount {
assert_eq!(
actual[0],
[ScalarValue::Int64(Some(37)), ScalarValue::Int64(Some(600))]
);
}
if name == WideCountsWithInput {
assert_eq!(actual[0][3..].len(), COARSE_WORK_BATCH_SIZE + 1);
for (index, count) in actual[0][3..].iter().enumerate() {
let expected = [600, 400, 200][index % 3];
assert_eq!(count, &ScalarValue::Int64(Some(expected)));
}
}
}
}
#[test]
fn compact_all_rows_cardinality_uses_the_entire_selected_span() {
let (test_case, scan) = compact_cycle_harness(20, 0);
let selected = scan.selected_runs().unwrap().unwrap();
let layout = ExecutableOutputPlan::try_rows(
test_case.schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
&test_case.compiled,
)
.unwrap();
let mut acc =
MatchAccumulator::try_new_unbounded(Arc::clone(&test_case.compiled), 40, layout)
.unwrap();
let mut governor = crate::execution::common::work::WorkGovernor::default();
assert!(
acc.try_publish_direct_winner(
1,
&selected,
0..20,
0,
&test_case.batches,
&mut governor,
|| false,
|_, _| None,
)
.unwrap()
);
assert_eq!(acc.output.len(), 20);
assert_eq!(acc.matches_emitted, 1);
assert!(
!acc.try_publish_direct_winner(
2,
&selected,
0..20,
0,
&test_case.batches,
&mut governor,
|| false,
|_, _| None,
)
.unwrap()
);
assert_eq!(
acc.output.len(),
20,
"flush boundary leaves the winner untouched"
);
}
#[test]
fn compact_cardinality_keeps_validation_flush_and_publication_boundaries() {
let (test_case, scan) = compact_cycle_harness(20, 0);
let selected = scan.selected_runs().unwrap().unwrap();
let output =
direct_count_output(&test_case.schema, &test_case.compiled, vec![], vec![]);
let mut accumulator =
MatchAccumulator::try_new_unbounded(Arc::clone(&test_case.compiled), 3, output)
.unwrap();
let mut staged = PendingOutput::default();
let mut pending = PendingOutput::default();
for (id, range) in [(1, 0..19), (i64::MAX as u64 + 1, 0..20)] {
assert!(
prepare_compact_test(
&mut accumulator,
id,
&selected,
test_case.emission_context(range, 0, &mut staged),
&mut |_, _| None
)
.is_err()
);
assert!(accumulator.output.is_empty());
}
for id in 1..=2 {
let prepared = prepare_compact_test(
&mut accumulator,
id,
&selected,
test_case.emission_context(0..20, 0, &mut staged),
&mut |_, _| None,
)
.unwrap();
assert!(staged.is_empty() && pending.is_empty());
assert_eq!(accumulator.matches_emitted, id as usize - 1);
accumulator.cancel_next_match_publication();
assert!(
accumulator
.prepare_match_publication(&staged, &mut pending)
.is_err()
);
assert_eq!(accumulator.matches_emitted, id as usize - 1);
accumulator
.prepare_match_publication(&staged, &mut pending)
.unwrap();
accumulator.publish_prepared_match(prepared, &mut staged, &mut pending);
}
assert!(!accumulator.can_append_direct_winner());
let mut progress = accumulator
.begin_compact_match(
3,
&selected,
&test_case.emission_context(0..20, 0, &mut staged),
&mut |_| Ok(()),
)
.unwrap();
let prepared = loop {
if let Some(prepared) = accumulator
.prepare_compact_match_chunk(
&mut progress,
&selected,
test_case.emission_context(0..20, 0, &mut staged),
&mut |_| Ok(()),
)
.unwrap()
{
break prepared;
}
};
accumulator
.prepare_match_publication(&staged, &mut pending)
.unwrap();
accumulator.publish_prepared_match(prepared, &mut staged, &mut pending);
assert_eq!(accumulator.take_matches_total(), 3);
assert_eq!(pending.len(), 1);
assert_eq!(pending.iter().next().unwrap().num_rows(), 3);
assert_eq!(pending.iter().next().unwrap().num_columns(), 0);
}
fn metadata_summary(
id: usize,
symbol: Option<SymbolId>,
endpoint: MetadataEndpoint,
) -> ExecutableDirectCountSummary {
let field = MatchSummaryField::new(
id,
Arc::new(Field::new("measure", endpoint.column().data_type(), true)),
);
ExecutableDirectCountSummary::new_metadata(field, symbol, endpoint)
}
#[test]
fn expanded_metadata_respects_sequence_gaps_and_absent_symbols() -> Result<()> {
let (test_case, _) = compact_cycle_harness(4, 0);
let b = Some(SymbolId::try_new(2, 3).unwrap());
let last = MetadataEndpoint::Sequence {
last: true,
include_empty: false,
};
let plan = ExecutableOutputPlan::try_direct_counts(
&test_case.schema,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
vec![
metadata_summary(0, None, last),
metadata_summary(1, b, last),
metadata_summary(2, b, MetadataEndpoint::Classifier { last: false }),
],
&test_case.compiled,
)?;
let mut acc =
MatchAccumulator::try_new_unbounded(Arc::clone(&test_case.compiled), 1, plan)?;
let mut pending = PendingOutput::default();
let a = Sym::from_index(1);
acc.record_test_match(
1,
&[path_step(1, a), path_step(1, a), path_step(2, a)],
test_case.emission_context(0..4, 0, &mut pending),
)?;
let batch = pending.pop_front().unwrap();
assert_eq!(batch.num_rows(), 1);
assert_eq!(
ScalarValue::try_from_array(batch.column(0), 0)?,
ScalarValue::Int64(Some(3))
);
assert!(batch.column(1).is_null(0));
assert!(batch.column(2).is_null(0));
Ok(())
}
#[test]
fn compact_summary_preparation_preserves_named_cycle_edges_across_yield_and_flush()
-> Result<()> {
use crate::config::YieldPolicy;
use crate::execution::common::work::WorkGovernor;
for (long_cycle, named) in [(false, false), (false, true), (true, true)] {
let mut cycle = vec!["A"; if long_cycle { 300 } else { 2 }];
*cycle.last_mut().unwrap() = "B";
let rows = 2 * cycle.len();
let (mut test_case, scan) = compact_cycle_harness_with_cycle(rows, 0, &cycle);
let values = if long_cycle {
Int64Array::from_iter_values(0..rows as i64)
} else {
Int64Array::from(vec![None, Some(7), Some(8), Some(19)])
};
(test_case.schema, test_case.batches) =
single_column_input(Field::new("v", DataType::Int64, true), Arc::new(values));
let selected = scan.selected_runs()?.unwrap();
let b = SymbolId::try_new(2, 3).unwrap();
let symbol = named.then_some(b);
let expected = if long_cycle {
[Some(2), Some(299), Some(599)]
} else if named {
[Some(2), Some(7), Some(19)]
} else {
[Some(4), None, Some(19)]
};
let field = |id, name, nullable| {
MatchSummaryField::new(
id,
Arc::new(Field::new(name, DataType::Int64, nullable)),
)
};
let plan = ExecutableOutputPlan::try_direct_counts(
&test_case.schema,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
vec![
ExecutableDirectCountSummary::new(field(0, "count", false), symbol),
ExecutableDirectCountSummary::new_edge(
field(1, "first", true),
symbol,
0,
false,
),
ExecutableDirectCountSummary::new_edge(
field(2, "last", true),
symbol,
0,
true,
),
metadata_summary(3, symbol, MetadataEndpoint::Classifier { last: false }),
metadata_summary(4, symbol, MetadataEndpoint::Classifier { last: true }),
metadata_summary(
5,
symbol,
MetadataEndpoint::Sequence {
last: false,
include_empty: false,
},
),
metadata_summary(
6,
symbol,
MetadataEndpoint::Sequence {
last: true,
include_empty: false,
},
),
],
&test_case.compiled,
)?;
for (threshold, slice) in [1, 2]
.into_iter()
.flat_map(|threshold| [0, 1, 2, 3, 7].map(|budget| (threshold, budget)))
{
let mut acc = MatchAccumulator::try_new_unbounded(
Arc::clone(&test_case.compiled),
threshold,
Arc::clone(&plan),
)?;
let mut staged = PendingOutput::default();
let mut governor = WorkGovernor::default();
let mut progress = acc.begin_compact_match(
1,
&selected,
&test_case.emission_context(0..rows, 0, &mut staged),
&mut |units| governor.record_completed(units, || false),
)?;
let mut yielded = false;
let prepared = loop {
let prepared = progress.advance(
&mut acc,
&selected,
test_case.emission_context(0..rows, 0, &mut staged),
&mut governor,
YieldPolicy::from_test_budget(slice),
|| false,
)?;
assert_eq!(acc.matches_emitted, 0);
if let Some(prepared) = prepared {
break prepared;
}
yielded = true;
};
if long_cycle && slice > 0 {
assert!(yielded, "long cycle must suspend before publication");
}
if threshold == 1 {
assert_eq!(
staged.len(),
1,
"threshold flush publishes a complete batch"
);
}
if !long_cycle && threshold == 2 && symbol.is_some() {
assert!(!yielded, "bounded summaries finish without suspension");
assert!(staged.is_empty());
assert_eq!(acc.output.len(), 1);
let history = selected.history()?;
let mut positions = 0;
for (i, run) in history.runs.iter().enumerate() {
let (_, period) = history.edge_and_period(i, 0)?;
positions += period.min(run.steps().as_u64());
}
assert_eq!(governor.progress_epoch_for_observation(), 7 * positions + 8);
}
let mut pending = PendingOutput::default();
acc.prepare_match_publication(&staged, &mut pending)?;
acc.publish_prepared_match(prepared, &mut staged, &mut pending);
if let Some(tail) =
acc.flush_collection(&test_case.batches, 0, None, false)?
{
pending.push_back(tail)?;
}
assert_eq!(pending.len(), 1);
let batch = pending.iter().next().unwrap();
assert_eq!(batch.num_rows(), 1);
let values = [0, 1, 2].map(|id| {
let name = format!("__mr_count_summary_{id}");
output_column::<Int64Array>(batch, &name)
.iter()
.next()
.unwrap()
});
assert_eq!(values, expected);
let expected_first = if symbol.is_some() { "B" } else { "A" };
assert_eq!(
ScalarValue::try_from_array(batch.column(3), 0)?,
ScalarValue::Utf8(Some(expected_first.into()))
);
assert_eq!(
ScalarValue::try_from_array(batch.column(4), 0)?,
ScalarValue::Utf8(Some("B".into()))
);
assert_eq!(
ScalarValue::try_from_array(batch.column(5), 0)?,
ScalarValue::Int64(Some(if symbol.is_some() {
cycle.len() as i64
} else {
1
}))
);
assert_eq!(
ScalarValue::try_from_array(batch.column(6), 0)?,
ScalarValue::Int64(Some(rows as i64))
);
}
}
Ok(())
}
#[test]
fn compact_count_words_finish_bounded_summaries_and_chunk_long_cycles() -> Result<()> {
use crate::config::{CancellationPolicy, YieldPolicy};
use crate::execution::common::work::WorkGovernor;
use crate::execution::matching::row_loop::lane_scan::LaneSelectedRuns;
for period in [2, 300] {
let mut cycle = vec!["A"; period];
cycle[period - 1] = "B";
let rows = 2 * period;
let (test_case, scan) = compact_cycle_harness_with_cycle(rows, 0, &cycle);
let selected = scan.selected_runs()?.unwrap();
assert!(selected.history()?.runs.len() <= LaneSelectedRuns::MAX_ATOMIC_RUNS);
let b = SymbolId::try_new(2, 3).unwrap();
let plan = direct_count_output(
&test_case.schema,
&test_case.compiled,
vec![],
vec![Some(b)],
);
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::matching::{
ResolvedAfterMatchSkip,
path::{SelectedStepSources, SelectedSteps},
};
for last in [false, true] {
let skip = if last {
ResolvedAfterMatchSkip::ToLast {
name: "B".into(),
symbol_id: b,
}
} else {
ResolvedAfterMatchSkip::ToFirst {
name: "B".into(),
symbol_id: b,
}
};
assert_eq!(selected.can_skip_atomically(&skip)?, period == 2);
for cancel in [false, true] {
let acc = MatchAccumulator::try_new_unbounded(
test_case.compiled.clone(),
8,
plan.clone(),
)?;
let mut fill = SelectedPathFill::new(
SelectedSteps::lane(selected.expected_steps)?,
selected.start,
selected.end,
selected.acceptance,
);
let memory =
crate::execution::common::memory::new_unbounded_state_memory();
fill.steps.reserve(Vec::new(), &mut memory.new_empty())?;
let mut governor = WorkGovernor::default();
governor.bind_cancellation_policy(
CancellationPolicy::try_from_configured(1, 0)?,
)?;
let mut staged = PendingOutput::default();
let mut chunks = 0;
let result = loop {
let mut work = 0;
let result = fill.advance(
&acc,
&test_case.compiled,
&skip,
&test_case.emission_context(0..rows, 0, &mut staged),
|_| {
Ok((
SelectedStepSources {
lane: Some(scan.path_cursor()),
..Default::default()
},
COARSE_WORK_BATCH_SIZE,
))
},
&mut |units| {
work += units;
governor.record_completed(units, || cancel)
},
);
assert!(work <= COARSE_WORK_BATCH_SIZE);
chunks += 1;
match result {
Ok(Some(validator)) => {
break fill.finish(validator).map(|(_, target)| target);
}
Ok(None) => {
assert!(chunks <= rows.div_ceil(COARSE_WORK_BATCH_SIZE))
}
Err(error) => break Err(error),
}
};
if cancel {
assert!(result.unwrap_err().to_string().contains("cancelled"));
} else {
assert_eq!(
result?,
Some(AbsoluteRow::new(
(if last { rows } else { period } - 1) as u64
))
);
assert_eq!(chunks, rows.div_ceil(COARSE_WORK_BATCH_SIZE));
}
assert!(staged.is_empty());
assert!(acc.is_empty());
}
}
for cancel in [false, true] {
let mut acc = MatchAccumulator::try_new_unbounded(
test_case.compiled.clone(),
8,
plan.clone(),
)?;
let mut staged = PendingOutput::default();
let mut governor = WorkGovernor::default();
governor.bind_cancellation_policy(
CancellationPolicy::try_from_configured(1, 0)?,
)?;
let result = (|| -> Result<usize> {
let mut progress = acc.begin_compact_match(
1,
&selected,
&test_case.emission_context(0..rows, 0, &mut staged),
&mut |units| governor.record_completed(units, || cancel),
)?;
let mut chunks = 1;
loop {
if progress
.advance(
&mut acc,
&selected,
test_case.emission_context(0..rows, 0, &mut staged),
&mut governor,
YieldPolicy::from_test_budget(1),
|| cancel,
)?
.is_some()
{
return Ok(chunks);
}
assert_eq!(acc.matches_emitted, 0);
assert!(staged.is_empty());
chunks += 1;
}
})();
if cancel {
assert!(result.unwrap_err().to_string().contains("cancelled"));
assert!(acc.is_empty());
assert_eq!(acc.matches_emitted, 0);
assert!(staged.is_empty());
} else {
assert_eq!(result? > 1, period > LaneSelectedRuns::MAX_ATOMIC_RUNS);
let output = acc
.flush_collection(&test_case.batches, 0, None, false)?
.unwrap();
assert_eq!(output.num_rows(), 1);
assert_eq!(
output
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.value(0),
2
);
}
}
}
Ok(())
}