use std::ops::Range;
use crate::core::SymbolId;
use datafusion_common::{DataFusionError, Result};
use crate::execution::matching::graph::fallible_vec::reserved;
use crate::nfa::{AutomatonStateId, CompiledAutomaton};
#[derive(Debug, Clone, Copy)]
pub(crate) struct OrderedTransitionEdge {
pub(crate) source_state_id: AutomatonStateId,
pub(crate) symbol_id: SymbolId,
pub(crate) next_state_id: AutomatonStateId,
pub(crate) excluded: bool,
pub(crate) packed_shift: u8,
pub(crate) after_accept: bool,
symbol_dispatch: u8,
}
impl OrderedTransitionEdge {
const SHARES_SYMBOL: u8 = 1 << 7;
const NO_OFFSET: u8 = Self::SHARES_SYMBOL - 1;
pub(crate) fn shares_symbol(&self) -> bool {
self.symbol_dispatch & Self::SHARES_SYMBOL != 0
}
}
fn seal_symbol_offsets(ordered: &mut [OrderedTransitionEdge], required: u64) {
for offset in (0..ordered.len()).rev() {
let bit = 1u64 << ordered[offset].packed_shift;
let rank = (required & (bit - 1)).count_ones() as usize;
ordered[rank].symbol_dispatch = (ordered[rank].symbol_dispatch
& OrderedTransitionEdge::SHARES_SYMBOL)
| offset as u8;
}
}
#[derive(Debug)]
pub(crate) struct OrderedTransitionTable {
start_state: AutomatonStateId,
edges: Box<[OrderedTransitionEdge]>,
ranges: Box<[Range<usize>]>,
}
impl OrderedTransitionTable {
pub(crate) fn retained_size_bytes(&self) -> Result<usize> {
size_of::<Self>()
.checked_add(size_of_val(self.edges.as_ref()))
.and_then(|n| n.checked_add(size_of_val(self.ranges.as_ref())))
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE retained transition table exceeds usize".into(),
)
})
}
#[cfg(test)]
pub(crate) fn try_new(
compiled: &CompiledAutomaton,
publishers: &[SymbolId],
) -> Result<Self> {
let mut published_mask = 0u64;
for &symbol_id in publishers {
if symbol_id.index() >= compiled.num_symbols() || symbol_id.index() >= 64 {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE ordered symbol {symbol_id} exceeds bitmap domain"
)));
}
published_mask |= 1u64 << symbol_id.index();
}
Self::try_new_with_anchors(
compiled,
published_mask,
crate::execution::matching::row_loop::lane_scan::LaneBoundaryAnchors::None,
)
}
pub(crate) fn try_new_with_anchors(
compiled: &CompiledAutomaton,
published_mask: u64,
boundary_anchors: crate::execution::matching::row_loop::lane_scan::LaneBoundaryAnchors,
) -> Result<Self> {
let state_count = compiled.nfa().state_count();
let symbol_count = compiled.num_symbols();
let start_state = compiled.nfa().start_state();
if symbol_count > u64::BITS as usize {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE ordered transition table cannot represent {symbol_count} symbol slots"
)));
}
if symbol_count < 64 && published_mask >> symbol_count != 0 {
return Err(DataFusionError::Internal(
"MATCH_RECOGNIZE ordered transition mask exceeds the symbol domain"
.into(),
));
}
let mut edge_count = 0usize;
for (source_index, source) in compiled.nfa().states().enumerate() {
let source_state_id = compiled
.nfa()
.state_id(source_index)
.expect("sealed source state");
let dispatch_ids = match boundary_anchors
.dispatch_environment(source_state_id, start_state)
{
Some(env) => compiled.anchor_dispatch_closure(env, source_state_id),
None => source.unconditional_dispatch(),
};
for &dispatch_id in dispatch_ids {
let dispatch = compiled.nfa().state(dispatch_id);
let consumes = dispatch.transition_bitmap() & published_mask != 0;
let Some(total) = edge_count.checked_add(usize::from(consumes)) else {
return Err(DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE ordered transition edge count exceeds usize"
.into(),
));
};
edge_count = total;
}
}
let mut edges = reserved(edge_count, "ordered transition edges")?;
let mut ranges = reserved(state_count, "ordered transition ranges")?;
let accept_env = boundary_anchors.accept_environment();
for (source_index, source) in compiled.nfa().states().enumerate() {
let source_state_id = compiled
.nfa()
.state_id(source_index)
.expect("sealed source state");
let env = boundary_anchors.dispatch_environment(source_state_id, start_state);
let dispatch_ids = match env {
Some(env) => compiled.anchor_dispatch_closure(env, source_state_id),
None => source.unconditional_dispatch(),
};
let start = edges.len();
let accept = (!boundary_anchors.requires_partition_end())
.then(|| compiled.accepting_preference_rank(source_state_id, accept_env))
.flatten();
let mut symbols = 0u64;
let mut repeated = 0u64;
for (dispatch_offset, &nfa_state_id) in dispatch_ids.iter().enumerate() {
let dispatch = compiled.nfa().state(nfa_state_id);
let symbol_bit = dispatch.transition_bitmap() & published_mask;
if symbol_bit == 0 {
continue;
}
let symbol_id =
SymbolId::try_new(symbol_bit.trailing_zeros() as usize, symbol_count)
.expect("publication mask contains validated symbol IDs");
let &[next_state_id] = dispatch.transitions(symbol_id) else {
unreachable!("sealed dispatch state has one consuming target");
};
if compiled.id_to_symbol()[symbol_id.index()].is_none() {
return Err(DataFusionError::Internal(
"MATCH_RECOGNIZE consuming transition has no classifier".into(),
));
}
let preference_rank = compiled.dispatch_preference_rank(
source_state_id,
env,
dispatch_offset,
);
repeated |= symbols & symbol_bit;
symbols |= symbol_bit;
edges.push(OrderedTransitionEdge {
source_state_id,
symbol_id,
next_state_id,
excluded: dispatch.is_excluded(),
packed_shift: (symbol_id.index() - 1) as u8,
after_accept: accept.is_some_and(|rank| preference_rank > rank),
symbol_dispatch: OrderedTransitionEdge::NO_OFFSET,
});
}
if repeated != 0 {
for edge in &mut edges[start..] {
if repeated & (1u64 << edge.symbol_id.index()) != 0 {
edge.symbol_dispatch |= OrderedTransitionEdge::SHARES_SYMBOL;
}
}
}
let ordered = &mut edges[start..];
if ordered.len() <= usize::from(OrderedTransitionEdge::NO_OFFSET)
&& symbols.count_ones() > 1
&& symbols == compiled.closure_transition_bitmap(env, source_state_id)
{
seal_symbol_offsets(ordered, symbols >> 1);
}
ranges.push(start..edges.len());
}
debug_assert_eq!(edges.len(), edge_count);
Ok(Self {
start_state,
edges: edges.into_boxed_slice(),
ranges: ranges.into_boxed_slice(),
})
}
pub(crate) fn sealed_edge(&self, edge_id: usize) -> OrderedTransitionEdge {
self.edges[edge_id]
}
pub(crate) fn sealed_range(&self, state_id: AutomatonStateId) -> Range<usize> {
self.ranges[state_id.index()].clone()
}
#[inline]
pub(crate) fn first_enabled_edge(
&self,
range: Range<usize>,
required: u64,
enabled: u64,
) -> Option<usize> {
if enabled == 0 || range.is_empty() {
return None;
}
if enabled == required {
return Some(range.start);
}
if range.len() > 2 && enabled.is_power_of_two() {
let rank = (required & (enabled - 1)).count_ones() as usize;
if rank < range.len() {
let offset = self.edges[range.start + rank].symbol_dispatch
& OrderedTransitionEdge::NO_OFFSET;
if offset != OrderedTransitionEdge::NO_OFFSET {
return Some(range.start + usize::from(offset));
}
}
}
self.edges[range.clone()]
.iter()
.position(|edge| enabled & (1u64 << edge.packed_shift) != 0)
.map(|offset| range.start + offset)
}
pub(crate) fn sealed_edges_for_state(
&self,
state_id: AutomatonStateId,
) -> &[OrderedTransitionEdge] {
&self.edges[self.ranges[state_id.index()].clone()]
}
#[inline]
pub(crate) fn start_state(&self) -> AutomatonStateId {
self.start_state
}
#[inline]
pub(crate) const fn edge_count(&self) -> usize {
self.edges.len()
}
}
#[cfg(test)]
mod tests;