use super::BestMatch;
use super::*;
use super::{EpsilonSource, ResumeFrame, TransitionLoopState};
use crate::config::MatchRecognizeConfig;
use crate::core::{
AbsoluteRow, NormalizedPattern, Pattern, PhysicalExtent, Symbol, SymbolId,
};
use crate::execution::common::memory::try_reserve_accounted;
use crate::execution::identity::{ExecutionPartitionId, MatchPartitionId};
use crate::execution::matching::build_test_matcher;
use crate::execution::matching::path::{PathNode, PathStep, Sym};
use crate::execution::matching::row_loop::continuation::{
NextMatchCursor, ScanFrontiers, ScanResources,
};
use crate::execution::matching::row_loop::types::{
AccountedCowSlice, ActiveNFAState, ActiveThread, SharedNavigationFrame,
};
use crate::execution::matching::{owned_partition_key, shared_empty_partition_key};
use crate::execution::test_support::test_automaton_state_id;
use crate::nfa::CompiledAutomaton;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::DataFusionError;
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};
use datafusion::scalar::ScalarValue;
use std::sync::Arc;
fn test_path_node(prev: Option<u32>) -> PathNode {
PathNode {
step: PathStep {
row: AbsoluteRow::ZERO,
sym: Sym::Empty,
excluded: false,
},
prev,
depth: 0,
}
}
fn test_matcher() -> crate::execution::matching::PatternMatcher {
let normalized_pattern =
NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
let compiled = Arc::new(
CompiledAutomaton::compile(&normalized_pattern, &["A".into()])
.expect("compiled automaton should build"),
);
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
]));
build_test_matcher(
schema,
normalized_pattern,
compiled,
&MatchRecognizeConfig::default(),
|_| {},
)
.expect("matcher should build")
}
fn seeded_partition_context() -> (crate::execution::matching::PatternMatcher, ScanContext)
{
let matcher = test_matcher();
let mut context = ScanContext::new(3, 2, 1);
context.partition.logical = Some(LogicalPartitionBinding {
partition_id: MatchPartitionId::new(41),
key: owned_partition_key(vec![ScalarValue::Int32(Some(7))]).into(),
});
context.partition.next_match_number = 23;
context.partition.global_row_offset = 80;
context.partition.partition_start_row = 4;
context.partition.partition_end_row = 12;
context
.bind_execution_identity(ExecutionPartitionId::new(3), matcher.program_id())
.expect("test identity should bind");
activate_test_program(&mut context, &matcher);
(matcher, context)
}
fn activate_test_program(
context: &mut ScanContext,
matcher: &crate::execution::matching::PatternMatcher,
) {
context
.install_active_variant(
crate::execution::matching::row_loop::continuation::ActiveVariant::base(
matcher.program.base_variant(),
),
)
.expect("test active variant generation should allocate");
}
fn activate_compact_test_program(
context: &mut ScanContext,
matcher: &crate::execution::matching::PatternMatcher,
) {
activate_test_program(context, matcher);
context
.thread_store
.select_tier(
ActiveTier::Compact,
matcher.automaton_arc().nfa().state_count(),
)
.expect("test program should fit the compact thread tier");
}
fn test_lifted_state(match_start_row: AbsoluteRow, path: Option<u32>) -> ActiveThread {
ActiveThread {
navigation: None,
register_spill: None,
accumulators: None,
inner: ActiveNFAState {
state_id: test_automaton_state_id(0),
path,
match_start_row,
registers: [0; 16],
deferred_history_fingerprint: 0,
},
position_tracking: None,
labeled_position_tracking: None,
primitive_values: None,
is_consumed: false,
}
}
fn seed_initial_state(context: &mut ScanContext, match_start: AbsoluteRow) {
let next_generation = context.thread_store.active_generation.next();
let buffers = context
.thread_store
.buffers
.as_mut()
.expect("expected active buffers");
assert!(buffers.active.is_empty());
buffers.active.push(test_lifted_state(match_start, None));
context.thread_store.active_generation = next_generation;
}
fn begin_test_transitions(
context: &mut ScanContext,
define_cache_generation: u32,
matched_bitmap: u64,
) {
context.aggregation.define_cache_state.define_cache_gen = define_cache_generation;
let active_generation = context.thread_store.active_generation;
context
.scan_state
.resume
.begin_transitions(define_cache_generation, matched_bitmap, active_generation)
.expect("test transition payload should publish");
}
fn begin_test_candidate(
context: &mut ScanContext,
candidate_start: AbsoluteRow,
provider_end: AbsoluteRow,
) -> datafusion::common::Result<()> {
context.begin_continuation(candidate_start, AbsoluteRow::ZERO, provider_end, 0, false)
}
fn bind_test_partition(context: &mut ScanContext, partition_id: MatchPartitionId) {
context.partition.logical = Some(LogicalPartitionBinding {
partition_id,
key: shared_empty_partition_key().into(),
});
}
fn begin_zero_continuation(context: &mut ScanContext) -> datafusion::common::Result<()> {
begin_test_candidate(context, AbsoluteRow::ZERO, AbsoluteRow::ZERO)
}
struct LiveContextBuilder {
matcher: crate::execution::matching::PatternMatcher,
context: ScanContext,
}
impl LiveContextBuilder {
fn new(
matcher: crate::execution::matching::PatternMatcher,
nfa_states: usize,
symbol_count: usize,
) -> Self {
let mut context = ScanContext::new(nfa_states, symbol_count, 1);
bind_test_partition(&mut context, MatchPartitionId::new(7));
Self { matcher, context }
}
fn configure(mut self, configure: impl FnOnce(&mut ScanContext)) -> Self {
configure(&mut self.context);
self
}
fn bind_identity(&mut self) {
let program_id = self.matcher.program_id();
self.context
.bind_execution_identity(ExecutionPartitionId::new(0), program_id)
.unwrap();
}
fn compact(mut self, scan_start: usize, match_start: AbsoluteRow) -> Self {
self.bind_identity();
activate_compact_test_program(&mut self.context, &self.matcher);
self.context.scan_state.reset(scan_start);
seed_initial_state(&mut self.context, match_start);
self
}
fn begin(
mut self,
candidate_start: AbsoluteRow,
provider_origin: AbsoluteRow,
provider_end: AbsoluteRow,
max_prev_offset: usize,
final_flush: bool,
) -> ScanContext {
self.context
.begin_continuation(
candidate_start,
provider_origin,
provider_end,
max_prev_offset,
final_flush,
)
.unwrap();
self.context
}
}
#[test]
fn outer_cursor_retention_does_not_fabricate_live_scan_frontiers() {
let mut context = ScanContext::new(1, 1, 1);
context.partition.absolute_partition_start = 100;
context.cursor.row_idx = 115;
assert!(context.scan_frontiers(3).unwrap().is_none());
assert_eq!(context.min_retained_input_row(0).unwrap(), 115);
assert_eq!(context.min_retained_input_row(3).unwrap(), 112);
assert_eq!(context.min_retained_input_row(20).unwrap(), 100);
}
#[test]
fn continuation_start_rejects_missing_identity_atomically() {
let matcher = test_matcher();
let mut context = ScanContext::new(1, 1, 1);
activate_compact_test_program(&mut context, &matcher);
let error = begin_zero_continuation(&mut context)
.expect_err("a continuation without execution identity must be rejected");
assert!(error.to_string().contains("execution partition identity"));
assert!(!context.has_live_continuation());
context
.bind_execution_identity(ExecutionPartitionId::new(0), matcher.program_id())
.unwrap();
let error = begin_zero_continuation(&mut context)
.expect_err("a continuation without logical partition identity must be rejected");
assert!(error.to_string().contains("logical partition identity"));
bind_test_partition(&mut context, MatchPartitionId::new(7));
seed_initial_state(&mut context, AbsoluteRow::ZERO);
begin_zero_continuation(&mut context)
.expect("a corrected identity should start the first continuation");
}
#[test]
fn continuation_start_rejects_a_misaligned_provider_without_publishing_a_continuation() {
let matcher = test_matcher();
let mut context = ScanContext::new(1, 1, 1);
bind_test_partition(&mut context, MatchPartitionId::new(7));
context
.bind_execution_identity(ExecutionPartitionId::new(0), matcher.program_id())
.unwrap();
activate_test_program(&mut context, &matcher);
context
.thread_store
.select_tier(ActiveTier::Compact, 1)
.unwrap();
seed_initial_state(&mut context, AbsoluteRow::ZERO);
context.scan_state.current_row = 1;
let error =
begin_test_candidate(&mut context, AbsoluteRow::ZERO, AbsoluteRow::new(1))
.expect_err("the provider cursor must address the continuation frontier");
assert!(error.to_string().contains("does not address expected row"));
context.scan_state.reset(0);
begin_zero_continuation(&mut context)
.expect("all failed starts must leave the resources idle and reusable");
}
pub(super) fn live_head_binding_context() -> ScanContext {
let mut context = LiveContextBuilder::new(test_matcher(), 1, 1)
.configure(|context| {
context.partition.absolute_partition_start = 100;
context.partition.logical.as_mut().unwrap().key =
owned_partition_key(vec![ScalarValue::Int32(Some(7))]).into();
})
.compact(6, AbsoluteRow::new(110))
.begin(
AbsoluteRow::new(110),
AbsoluteRow::new(104),
AbsoluteRow::new(120),
3,
false,
);
context.scan_state.current_row = 11;
context.checkpoint_continuation().unwrap();
context
}
#[test]
fn suspended_history_belongs_to_one_candidate_across_heads() {
use crate::core::MatchMetadataColumn;
use crate::execution::deferred::{
DeferredEvaluatorFactory, DeferredMetadataColumnOwner, DeferredPredicateProgram,
DeferredSchemaColumnPlan, HistorySource,
};
let mut context = live_head_binding_context();
let history = DeferredSchemaColumnPlan::try_new_history(
Arc::new(Schema::new(vec![MatchMetadataColumn::PathId.arrow_field()])),
vec![HistorySource::Encoded(
DeferredMetadataColumnOwner::Metadata(MatchMetadataColumn::PathId),
)],
)
.unwrap();
let factory = DeferredEvaluatorFactory::try_new(
history,
Vec::new(),
DeferredPredicateProgram {
expressions: vec![None],
schema: Arc::new(Schema::empty()),
extra_columns: vec![],
},
&[None],
)
.unwrap();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(64 * 1024));
let memory = MemoryConsumer::new("candidate history lifetime").register(&pool);
let mut history = factory.candidate_history(&memory).unwrap();
assert!(pool.reserved() > 0);
let symbol = SymbolId::try_new(1, 2).unwrap();
history.begin(0, symbol, 1).unwrap();
context.candidate_history = Some(Box::new(history));
context.bind_continuation_head(105, 121, false).unwrap();
let error = context
.candidate_history
.as_mut()
.unwrap()
.begin(0, symbol, 1)
.unwrap_err();
assert!(error.to_string().contains("already active"), "{error}");
context.discard_candidate_scan();
assert_eq!(pool.reserved(), 0);
context.prepare_next_start().unwrap();
assert!(context.candidate_history.is_none());
}
fn continuation_snapshot(
context: &ScanContext,
) -> (ScanFrontiers, PhysicalExtent, usize, &'static str) {
(
context.scan_frontiers(3).unwrap().unwrap(),
context.continuation_provider().unwrap(),
context.scan_state.current_row,
context.scan_state.resume.name(),
)
}
#[test]
fn continuation_head_binding_rejects_mismatches_without_mutation() {
for value in [8, 7] {
let mut context = live_head_binding_context();
let before = continuation_snapshot(&context);
let canonical = Arc::clone(
context
.partition
.logical()
.unwrap()
.key
.canonical()
.unwrap(),
);
context.partition.logical.as_mut().unwrap().key =
owned_partition_key(vec![ScalarValue::Int32(Some(value))]).into();
let error = context.bind_continuation_head(104, 120, false).unwrap_err();
assert!(error.to_string().contains("canonical ownership"), "{error}");
context.partition.logical.as_mut().unwrap().key = canonical.into();
assert_eq!(continuation_snapshot(&context), before);
}
for (partition, start, origin, end, fragment) in [
(8, 100, 104, 120, "owner changed"),
(7, 101, 104, 120, "partition start changed"),
(7, 100, 108, 120, "after retained input floor"),
(7, 100, 104, 114, "after provider end"),
(7, 100, 120, 119, "precedes origin"),
] {
let mut context = live_head_binding_context();
let before = continuation_snapshot(&context);
context.partition.logical.as_mut().unwrap().partition_id =
MatchPartitionId::new(partition);
context.partition.absolute_partition_start = start;
let error = context
.bind_continuation_head(origin, end, false)
.unwrap_err();
assert!(error.to_string().contains(fragment), "{error}");
context.partition.logical.as_mut().unwrap().partition_id =
MatchPartitionId::new(7);
context.partition.absolute_partition_start = 100;
assert_eq!(continuation_snapshot(&context), before);
}
assert_eq!(
live_head_binding_context()
.bind_continuation_head(104, 114, true)
.unwrap(),
11
);
}
#[test]
fn continuation_head_binding_preserves_only_legal_frames() {
let mut context = live_head_binding_context();
begin_test_transitions(&mut context, 7, 0x12);
context
.scan_state
.resume
.transition_mut()
.unwrap()
.loops_mut()
.active_idx = 2;
assert_eq!(context.bind_continuation_head(104, 121, false).unwrap(), 11);
assert!(context.scan_state.resume.is_transitions());
assert_eq!(
context
.scan_state
.resume
.transition()
.unwrap()
.loops()
.active_idx,
2
);
let before_changed_origin = continuation_snapshot(&context);
let error = context
.bind_continuation_head(105, 121, false)
.expect_err("a changed provider cannot carry a transition frame");
assert!(error.to_string().contains("Transitions"));
assert_eq!(continuation_snapshot(&context), before_changed_origin);
assert_eq!(
context
.scan_state
.resume
.transition()
.unwrap()
.loops()
.active_idx,
2
);
context.scan_state.resume.finish_row().unwrap();
assert_eq!(context.bind_continuation_head(105, 121, false).unwrap(), 10);
assert!(context.scan_state.resume.is_start_row());
}
#[test]
fn live_scan_frontiers_rebase_next_unread_and_preserve_prev_retention() {
let context = live_head_binding_context();
let frontiers = context.scan_frontiers(3).unwrap().unwrap();
assert_eq!(frontiers.candidate_start_abs(), AbsoluteRow::new(110));
assert_eq!(frontiers.next_unread_abs(), AbsoluteRow::new(115));
assert_eq!(frontiers.replay_start_abs(), AbsoluteRow::new(111));
assert_eq!(frontiers.min_retained_input_abs(), AbsoluteRow::new(107));
}
#[test]
fn live_end_anchor_retains_candidate_representative() {
let normalized_pattern = NormalizedPattern::Ast(Pattern::Alternation(vec![
Pattern::Symbol(Symbol::End),
Pattern::Symbol(Symbol::Named("A".into())),
]));
let compiled =
Arc::new(CompiledAutomaton::compile(&normalized_pattern, &["A".into()]).unwrap());
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
]));
let matcher = build_test_matcher(
schema,
normalized_pattern,
Arc::clone(&compiled),
&MatchRecognizeConfig::default(),
|_| {},
)
.unwrap();
let mut context = LiveContextBuilder::new(matcher, compiled.nfa().state_count(), 1)
.configure(|context| {
context.partition.absolute_partition_start = 100;
context.cursor.row_idx = 110;
})
.compact(10, AbsoluteRow::new(110))
.begin(
AbsoluteRow::new(110),
AbsoluteRow::new(100),
AbsoluteRow::new(120),
0,
false,
);
context.scan_state.current_row = 15;
begin_test_transitions(&mut context, 1, 0);
context.checkpoint_continuation().unwrap();
assert_eq!(
context
.scan_frontiers(0)
.unwrap()
.unwrap()
.min_retained_input_abs(),
AbsoluteRow::new(110)
);
}
fn test_incumbent(row: AbsoluteRow, start: AbsoluteRow) -> AcceptingCandidate {
AcceptingCandidate {
best_match: BestMatch {
path_end: 0,
state_id: test_automaton_state_id(1),
row,
match_start_row: start,
},
end_row: row,
}
}
#[test]
fn selection_frontier_distinguishes_real_work_owners_from_closed_incumbent() {
let mut context = LiveContextBuilder::new(test_matcher(), 3, 2)
.compact(0, AbsoluteRow::ZERO)
.begin(
AbsoluteRow::ZERO,
AbsoluteRow::ZERO,
AbsoluteRow::ZERO,
0,
false,
);
assert!(context.selection_is_open() && context.has_live_continuation());
context.thread_store.discard_scan();
context
.thread_store
.node_arena
.extend_for_test([test_path_node(None)]);
context.scan_state.incumbent =
Some(test_incumbent(AbsoluteRow::ZERO, AbsoluteRow::ZERO));
assert!(!context.selection_is_open());
}
#[test]
fn candidate_discard_clears_local_state_and_preserves_reusable_owners() {
let (matcher, mut context) = seeded_partition_context();
context
.thread_store
.select_tier(
ActiveTier::Compact,
matcher.automaton_arc().nfa().state_count(),
)
.unwrap();
seed_initial_state(&mut context, AbsoluteRow::ZERO);
begin_zero_continuation(&mut context).expect("test continuation should allocate");
context.scan_state.current_row = 17;
begin_test_transitions(&mut context, 5, 2);
context.scan_state.incumbent =
Some(test_incumbent(AbsoluteRow::new(12), AbsoluteRow::new(10)));
context
.scan_state
.resume
.transition_mut()
.unwrap()
.loops_mut()
.active_idx = 2;
context
.scan_state
.governor
.set_work_since_yield_for_test(37);
context.cursor = NextMatchCursor { row_idx: 99 };
context.traversal.tmp.push(test_automaton_state_id(1));
context.traversal.stack.push(
crate::execution::matching::epsilon::ClosureStackEntry::state(
test_automaton_state_id(3),
),
);
context.symbols.pre_checks[1] = false;
context.symbols.or_passes[1] = true;
context
.symbols
.matched_ids
.push(SymbolId::try_new(1, 2).unwrap());
let engine = &mut context.aggregation;
engine
.scratch
.scratch_agg_results
.push(ScalarValue::Int32(Some(5)));
let mut arguments = Vec::with_capacity(3);
arguments.push(ScalarValue::Int32(Some(5)).to_array().unwrap());
engine.scratch.pre_evaluated_aggs.push(arguments);
engine.evaluation.current_match_sequence_number = 44;
context
.thread_store
.node_arena
.extend_for_test([test_path_node(None)]);
let Some(buffers) = &mut context.thread_store.buffers else {
panic!("expected compact buffers");
};
assert_eq!(buffers.tier, ActiveTier::Compact);
buffers.active[0].set_path(Some(0));
let specialized_variant = Arc::clone(
context
.active_variant
.as_ref()
.expect("test active executable variant should exist")
.resolve(matcher.program.base_variant()),
);
context.discard_candidate_scan();
assert_eq!(context.scan_state.current_row, 17);
assert!(context.scan_state.resume.is_start_row());
assert!(context.scan_state.incumbent.is_none());
assert!(context.scan_state.resume.transition().is_none());
assert_eq!(context.scan_state.governor.work_since_yield_for_test(), 37);
assert_eq!(context.cursor.row_idx, 99);
assert!(!context.has_live_continuation());
assert!(context.traversal.tmp.is_empty());
assert!(context.traversal.stack.is_empty());
assert!(context.symbols.pre_checks[1]);
assert!(!context.symbols.or_passes[1]);
assert!(context.symbols.matched_ids.is_empty());
let engine = &context.aggregation;
assert!(engine.scratch.scratch_agg_results.is_empty());
let argument_buffers = &engine.scratch.pre_evaluated_aggs;
assert_eq!(argument_buffers.len(), 1);
assert!(argument_buffers[0].is_empty());
assert_eq!(argument_buffers[0].capacity(), 3);
assert_eq!(engine.evaluation.current_match_sequence_number, 1);
assert!(context.thread_store.node_arena.is_empty());
let Some(buffers) = &context.thread_store.buffers else {
panic!("expected compact buffers");
};
assert_eq!(buffers.tier, ActiveTier::Compact);
assert!(buffers.active.is_empty());
let partition = context.partition.logical().unwrap();
assert_eq!(partition.partition_id, MatchPartitionId::new(41));
assert_eq!(
partition.key.canonical().unwrap().scalar_values().unwrap(),
&[ScalarValue::Int32(Some(7))]
);
assert_eq!(
context.partition.execution,
Some(ExecutionBinding {
execution_partition_id: ExecutionPartitionId::new(3),
program_id: matcher.program_id(),
})
);
assert_eq!(context.partition.next_match_number, 23);
assert!(Arc::ptr_eq(
context
.active_variant
.as_ref()
.expect("candidate discard must retain the active executable variant")
.resolve(matcher.program.base_variant()),
&specialized_variant
));
context.scan_state.reset(99);
seed_initial_state(&mut context, AbsoluteRow::new(99));
begin_test_candidate(&mut context, AbsoluteRow::new(99), AbsoluteRow::new(100))
.expect("a later candidate should allocate the next continuation");
}
#[test]
fn candidate_discard_reuses_pathological_high_water_without_leaking_owners() {
const HIGH_WATER: usize = 128;
const SMALL_SCANS: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct RetainedStorage {
active_capacity: usize,
}
let matcher = test_matcher();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(64 * 1024 * 1024));
let state_memory =
Arc::new(MemoryConsumer::new("candidate-discard-reuse-test").register(&pool));
let mut context = ScanContext::new_with_state_memory(HIGH_WATER, 2, 1, state_memory);
let stable_resource_reservation = pool.reserved();
bind_test_partition(&mut context, MatchPartitionId::new(41));
context
.bind_execution_identity(ExecutionPartitionId::new(3), matcher.program_id())
.expect("test context identity should bind");
activate_test_program(&mut context, &matcher);
context
.thread_store
.select_tier(ActiveTier::Standard, HIGH_WATER)
.expect("standard tier should fit in the test pool");
seed_initial_state(&mut context, AbsoluteRow::ZERO);
begin_zero_continuation(&mut context)
.expect("pathological scan should allocate a continuation");
let Some(buffers) = &mut context.thread_store.buffers else {
panic!("expected standard buffers");
};
assert_eq!(buffers.tier, ActiveTier::Standard);
try_reserve_accounted(
&mut buffers.active,
&buffers.memory,
HIGH_WATER - 1,
"active",
)
.unwrap();
for _ in 1..HIGH_WATER {
let mut state = test_lifted_state(AbsoluteRow::ZERO, None);
state.navigation = Some(SharedNavigationFrame(
AccountedCowSlice::try_zeroed(8, &buffers.memory).unwrap(),
));
buffers.active.push(state);
}
let frame_bytes = (HIGH_WATER - 1) * 8 * size_of::<u64>();
let before_discard = pool.reserved();
context.thread_store.active_generation =
context.thread_store.active_generation.next();
context.discard_candidate_scan();
assert_eq!(pool.reserved(), before_discard - frame_bytes);
let retained_storage = |context: &ScanContext| {
let Some(buffers) = &context.thread_store.buffers else {
panic!("expected standard buffers");
};
assert_eq!(buffers.tier, ActiveTier::Standard);
RetainedStorage {
active_capacity: buffers.active.capacity(),
}
};
let high_water_storage = retained_storage(&context);
let high_water_reservation = pool.reserved();
assert!(high_water_storage.active_capacity >= HIGH_WATER);
let Some(buffers) = &context.thread_store.buffers else {
panic!("expected standard buffers");
};
assert_eq!(buffers.tier, ActiveTier::Standard);
assert_eq!(
high_water_reservation,
stable_resource_reservation
+ buffers.memory.size()
+ buffers.overflow_index.retained_bytes()
);
for _ in 0..SMALL_SCANS {
context
.thread_store
.select_tier(ActiveTier::Standard, 1)
.expect("small scan should reuse the standard tier");
seed_initial_state(&mut context, AbsoluteRow::ZERO);
begin_zero_continuation(&mut context)
.expect("small scan should allocate a continuation");
context.discard_candidate_scan();
assert!(context.candidate_history.is_none());
assert!(!context.has_live_continuation());
let Some(buffers) = &context.thread_store.buffers else {
panic!("expected standard buffers");
};
assert_eq!(buffers.tier, ActiveTier::Standard);
assert!(buffers.active.is_empty());
assert!(buffers.next_active.is_empty());
assert_eq!(retained_storage(&context), high_water_storage);
assert_eq!(pool.reserved(), high_water_reservation);
}
drop(context);
assert_eq!(pool.reserved(), 0);
}
#[test]
fn collection_and_partition_reset_have_explicit_owner_and_generation_scopes() {
for new_partition in [false, true] {
let (matcher, mut context) = seeded_partition_context();
context
.thread_store
.select_tier(ActiveTier::Standard, 3)
.unwrap();
seed_initial_state(&mut context, AbsoluteRow::ZERO);
context
.thread_store
.node_arena
.extend_for_test([test_path_node(None)]);
let Some(buffers) = &mut context.thread_store.buffers else {
unreachable!();
};
buffers.active[0].set_path(Some(0));
begin_test_candidate(&mut context, AbsoluteRow::ZERO, AbsoluteRow::new(20))
.unwrap();
context
.publish_collection_binding(CollectionHeadGeneration::new(2), 0, 20, false)
.unwrap();
let provider = Arc::downgrade(&context.collection.provider_backing().unwrap());
let key = Arc::clone(
context
.partition
.logical()
.unwrap()
.key
.canonical()
.unwrap(),
);
let traversal = &mut context.traversal;
traversal.reserve_visited(3).unwrap();
traversal.visited.fill(7);
traversal.generation.advance(&mut traversal.visited);
let traversal_generation = context.traversal.generation.current();
context.symbols.matched_seen.fill(7);
context.symbols.matched_seen_gen = 7;
context.scan_state.current_row = 9;
begin_test_transitions(&mut context, 7, 0b10);
context
.scan_state
.governor
.set_work_since_yield_for_test(37);
context.cursor = NextMatchCursor { row_idx: 12 };
let visited_len = context.traversal.visited.len();
let matched_seen_len = context.symbols.matched_seen.len();
assert!(visited_len > 0);
assert!(matched_seen_len > 0);
if new_partition {
context.reset_for_partition(200, 31);
} else {
context.prepare_collection_start(100);
}
assert_eq!(
context.partition.execution,
Some(ExecutionBinding {
execution_partition_id: ExecutionPartitionId::new(3),
program_id: matcher.program_id()
})
);
assert_eq!(context.scan_state.governor.work_since_yield_for_test(), 37);
assert_eq!(
(
context.partition.global_row_offset,
context.partition.partition_start_row,
context.partition.partition_end_row,
context.partition.absolute_partition_start,
context.partition.next_match_number
),
if new_partition {
(0, 0, 0, 200, 31)
} else {
(80, 4, 12, 100, 23)
}
);
if new_partition {
assert!(context.partition.logical.is_none());
} else {
let logical = context.partition.logical().unwrap();
assert_eq!(logical.partition_id, MatchPartitionId::new(41));
assert!(Arc::ptr_eq(logical.key.canonical().unwrap(), &key));
assert_eq!(
logical.key.canonical().unwrap().scalar_values().unwrap(),
&[ScalarValue::Int32(Some(7))]
);
}
assert_eq!(
(
context.scan_state.current_row,
context.scan_state.resume.name(),
context.cursor
),
(0, "StartRow", NextMatchCursor::default())
);
assert!(!context.has_live_continuation() && !context.has_active_states());
assert!(context.thread_store.node_arena.is_empty());
assert!(
context.collection.bound_partition_id().is_none()
&& context.collection.provider_backing().is_none()
&& context.active_variant.is_none()
);
assert!(provider.upgrade().is_none());
assert_eq!(context.traversal.visited.len(), visited_len);
assert_eq!(context.symbols.matched_seen.len(), matched_seen_len);
let stamp = if new_partition { 0 } else { 7 };
assert!(
context
.traversal
.visited
.iter()
.all(|&value| value == stamp)
);
assert!(
context
.symbols
.matched_seen
.iter()
.all(|&value| value == stamp)
);
assert_eq!(
context.traversal.generation.current(),
if new_partition {
1
} else {
traversal_generation
}
);
assert_eq!(
context.symbols.matched_seen_gen,
if new_partition { 1 } else { 7 }
);
assert_eq!(context.thread_store.navigation_frame_count(), 0);
}
}
#[test]
fn stable_scan_resources_are_pool_accounted_and_creation_is_failure_atomic() {
const STATES: usize = 128;
let resource_bytes = size_of::<ScanResources>();
let state_buffer_bytes = STATES * size_of::<u32>();
let symbol_buffer_bytes =
2 * (2 * size_of::<bool>() + size_of::<u32>()) + 8 * size_of::<SymbolId>();
let total_bytes = resource_bytes + state_buffer_bytes + symbol_buffer_bytes;
for capacity in [resource_bytes - 1, resource_bytes, total_bytes - 1] {
let denied_pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(capacity));
let denied_memory = Arc::new(
MemoryConsumer::new("stable-scan-resource-denial-test")
.register(&denied_pool),
);
let denied = ScanContext::try_new_with_state_memory(STATES, 2, 1, denied_memory);
let Err(error) = denied else {
panic!("an undersized pool must reject stable scan-resource creation");
};
assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
assert_eq!(denied_pool.reserved(), 0);
}
let accounted_pool: Arc<dyn MemoryPool> =
Arc::new(GreedyMemoryPool::new(total_bytes));
let accounted_memory = Arc::new(
MemoryConsumer::new("stable-scan-resource-accounting-test")
.register(&accounted_pool),
);
let context = ScanContext::try_new_with_state_memory(STATES, 2, 1, accounted_memory)
.expect("the stable-resource reservation should succeed");
assert_eq!(accounted_pool.reserved(), total_bytes);
drop(context);
assert_eq!(accounted_pool.reserved(), 0);
}
#[test]
fn transition_loop_state_binds_and_validates_active_identity() {
let first = ActiveResumeIdentity::new(
0,
ActiveContainerGeneration::new(3),
test_automaton_state_id(11),
Some(5),
);
let different_index = ActiveResumeIdentity::new(
1,
ActiveContainerGeneration::new(3),
test_automaton_state_id(11),
Some(5),
);
let different_generation = ActiveResumeIdentity::new(
0,
ActiveContainerGeneration::new(4),
test_automaton_state_id(11),
Some(5),
);
let mut loops = TransitionLoopState::default();
assert!(
loops
.cached_active_match_sequence()
.expect_err("an unbound cursor must not expose cached metadata")
.to_string()
.contains("unbound active cursor")
);
loops.bind_or_validate_active_identity(first).unwrap();
loops.bind_or_validate_active_identity(first).unwrap();
assert_eq!(loops.active_identity(), Some(first));
assert_eq!(loops.cached_active_match_sequence().unwrap(), None);
loops.publish_active_match_sequence(17).unwrap();
loops.publish_active_match_sequence(17).unwrap();
let cache_error = loops
.publish_active_match_sequence(18)
.expect_err("one active identity cannot publish two sequence values");
assert!(
cache_error
.to_string()
.contains("match-sequence cache conflict")
);
assert_eq!(loops.cached_active_match_sequence().unwrap(), Some(17));
for different in [different_index, different_generation] {
let error = loops
.bind_or_validate_active_identity(different)
.expect_err("a resumed cursor must not silently bind another instance");
assert!(
error
.to_string()
.contains("active cursor identity mismatch")
);
assert_eq!(
(
loops.active_identity(),
loops.cached_active_match_sequence().unwrap()
),
(Some(first), Some(17))
);
}
loops.advance_active_state();
assert!(loops.active_identity().is_none());
loops
.bind_or_validate_active_identity(different_index)
.unwrap();
assert_eq!(loops.cached_active_match_sequence().unwrap(), None);
let mut frame = ResumeFrame::StartRow;
assert!(
frame
.begin_transitions(1, 0, ActiveContainerGeneration::default())
.is_err()
);
frame
.begin_transitions(1, 0, ActiveContainerGeneration::new(3))
.unwrap();
let transition = frame.transition().unwrap();
transition
.validate_active_generation(ActiveContainerGeneration::new(3))
.unwrap();
assert!(
transition
.validate_active_generation(ActiveContainerGeneration::new(4))
.is_err()
);
assert_eq!(
ActiveContainerGeneration::new(u64::MAX).next(),
ActiveContainerGeneration::new(1)
);
}
#[test]
fn publishing_transitions_twice_preserves_the_prepared_frame() {
let mut frame = ResumeFrame::default();
frame
.begin_transitions(17, 0b10, ActiveContainerGeneration::new(3))
.unwrap();
let before = format!("{frame:?}");
let error = frame
.begin_transitions(1, 1, ActiveContainerGeneration::new(4))
.unwrap_err();
assert!(
error.to_string().contains("cannot begin transitions"),
"{error}"
);
assert_eq!(format!("{frame:?}"), before);
}
#[test]
fn transition_loop_state_advancement_preserves_expected_boundaries() {
type Advance = fn(&mut TransitionLoopState);
use EpsilonSource::{Precomputed, Unbound};
for (advance, expected) in [
(
TransitionLoopState::advance_next_idx as Advance,
(2, 1, 3, 5, 5, Precomputed),
),
(
TransitionLoopState::advance_regular_symbol,
(2, 1, 4, 0, 5, Precomputed),
),
(
TransitionLoopState::advance_match_aware_symbol,
(2, 1, 3, 0, 6, Precomputed),
),
(
TransitionLoopState::advance_epsilon_state,
(2, 2, 0, 0, 0, Precomputed),
),
(
TransitionLoopState::advance_active_state,
(3, 0, 0, 0, 0, Unbound),
),
(
|loops| loops.mark_epsilon_ready(Precomputed),
(2, 0, 3, 4, 5, Precomputed),
),
] {
let mut loops = TransitionLoopState {
active_idx: 2,
eps_idx: 1,
sym_idx: 3,
next_idx: 4,
epsilon_source: Precomputed,
match_aware_sym_idx: 5,
..Default::default()
};
advance(&mut loops);
assert_eq!(
(
loops.active_idx,
loops.eps_idx,
loops.sym_idx,
loops.next_idx,
loops.match_aware_sym_idx,
loops.epsilon_source()
),
expected
);
}
}