use crate::execution::matching::row_loop::types::{
PackedNavigationLayout, PackedNavigationUpdate,
};
use std::fmt;
use std::sync::Arc;
use crate::core::MatchMetadataColumn;
use crate::core::vm::{
AggregateKind, MAX_INLINE_REGISTERS, MAX_NAV_SLOTS, MAX_PREV_BUFFERS, MAX_REGISTERS,
MAX_VM_ROW_VALUES, NavigationLayout, NavigationUpdate, RegisterLayout,
RegisterWriter, SlotValueType, VmTier, is_retained_row_extrema_type,
is_temporal_word_type,
};
use crate::planning::{ManagedAggregateBackend, ManagedAggregateBackendSet};
use datafusion::arrow::datatypes::Schema;
use datafusion::physical_plan::PhysicalExpr;
use datafusion::physical_plan::expressions::Column;
use datafusion_common::{DataFusionError, Result};
use crate::execution::matching::row_loop::row_data::{
ResolvedRowBindings, RowInputBinding, RowInputType, resolve_optional_column,
};
use crate::execution::matching::row_loop::vm_scratch::{
BoundStateCell, BoundStateSource,
};
use crate::execution::matching::{
ExecutableAggregateStateProgram, ExecutableIncrementalEvaluator,
ExecutableSymbolEvaluator, ExecutableSymbolProgram, SymbolProgram,
};
fn physical_expr_references_column(expr: &Arc<dyn PhysicalExpr>, index: usize) -> bool {
expr.downcast_ref::<Column>()
.is_some_and(|column| column.index() == index)
|| expr
.children()
.iter()
.any(|child| physical_expr_references_column(child, index))
}
pub(in crate::execution::matching) fn symbol_programs_reference_metadata_column(
schema: &Schema,
programs: &[SymbolProgram],
column: MatchMetadataColumn,
) -> bool {
let Some(index) = resolve_optional_column(schema, column.as_ref()) else {
return false;
};
let index = index.index();
let mut guard_roots = Vec::new();
programs.iter().any(|program| {
program
.local_predicate()
.is_some_and(|expr| physical_expr_references_column(expr, index))
|| program.hybrid_guard().is_some_and(|guard| {
guard_roots.clear();
guard.append_physical_expr_roots(&mut guard_roots);
guard_roots
.iter()
.any(|expr| physical_expr_references_column(expr, index))
})
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct VmIndex<const CAPACITY: usize>(u8);
impl<const CAPACITY: usize> VmIndex<CAPACITY> {
#[inline(always)]
pub(crate) const fn index(self) -> usize {
self.0 as usize
}
pub(in crate::execution::matching) fn from_validated(raw: usize) -> Self {
debug_assert!(raw < CAPACITY && u8::try_from(raw).is_ok());
Self(raw as u8)
}
pub(in crate::execution::matching) fn try_bind(
raw: usize,
width: usize,
cardinality: usize,
domain: &str,
) -> Result<Self> {
if width == 0
|| !raw
.checked_add(width)
.is_some_and(|end| end <= cardinality && end <= CAPACITY)
|| u8::try_from(raw).is_err()
{
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE executable {domain} binding is out of bounds: index={raw}, width={width}, cardinality={cardinality}, capacity={CAPACITY}"
)));
}
Ok(Self(raw as u8))
}
}
pub(crate) type RegisterId = VmIndex<MAX_REGISTERS>;
pub(crate) type NavigationSlotId = VmIndex<MAX_NAV_SLOTS>;
pub(crate) type PreviousBufferId = VmIndex<MAX_PREV_BUFFERS>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WordUpdate {
Add,
AddF64,
Min,
Max,
MinU64,
MaxU64,
MinF32,
MaxF32,
MinF64,
MaxF64,
UpdateVariance,
BoolAnd,
BoolOr,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DecimalUpdate {
Add,
Min,
Max,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RetainedRowUpdate {
Min,
Max,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RegisterUpdate {
Inc,
Word(WordUpdate),
Decimal(DecimalUpdate),
RetainedRow(RetainedRowUpdate),
}
impl RegisterUpdate {
pub(in crate::execution::matching) fn bind_input<'a>(
self,
input: usize,
bindings: &'a ResolvedRowBindings,
register_layout: &RegisterLayout,
) -> Result<&'a RowInputBinding> {
use RowInputType as T;
use WordUpdate as W;
if input >= register_layout.num_row_inputs() || input >= MAX_VM_ROW_VALUES {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE register writer input is out of bounds: index={input}, cardinality={}, capacity={MAX_VM_ROW_VALUES}",
register_layout.num_row_inputs()
)));
}
let (expected, context): (&[T], _) = match self {
RegisterUpdate::Inc => (&[], "nullable COUNT"),
RegisterUpdate::Decimal(_) => (&[T::Decimal128], "Decimal128 accumulation"),
RegisterUpdate::RetainedRow(_) => {
(&[T::RetainedRow], "retained-row MIN/MAX accumulation")
}
RegisterUpdate::Word(kernel) => match kernel {
W::MinF32 | W::MaxF32 => (&[T::Float32], "Float32 accumulation"),
W::MinU64 | W::MaxU64 => {
(&[T::UInt64, T::SmallUnsigned], "UInt64 accumulation")
}
W::MinF64 | W::MaxF64 | W::AddF64 => {
(&[T::Float64], "Float64 accumulation")
}
W::UpdateVariance => (&[T::Float64], "Float64 statistical accumulation"),
W::Add => (
&[T::Int64, T::UInt64, T::SmallUnsigned],
"primitive addition",
),
W::Min | W::Max => (
&[T::Int64, T::SmallUnsigned, T::Temporal],
"signed minimum/maximum",
),
W::BoolAnd | W::BoolOr => (&[T::Boolean], "Boolean accumulation"),
},
};
let binding = bindings.row_inputs.get(input).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE VM row input value index {input} is out of bounds for {} resolved bindings (columns={:?})",
bindings.row_inputs.len(), register_layout.row_input_names()
))
})?;
let domain = if matches!(self, RegisterUpdate::Word(..)) && binding.force_float {
T::Float64
} else {
binding.column_type
};
if !expected.is_empty() && !expected.contains(&domain) {
let name = ®ister_layout.row_input_names()[input];
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE VM row input column '{name}' has resolved domain {domain:?}, incompatible with {context}"
)));
}
Ok(binding)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BoundRegisterWriter {
pub(crate) column: usize,
pub(crate) input: usize,
pub(crate) force_float: bool,
pub(crate) nullable: bool,
pub(crate) slot: RegisterId,
pub(crate) update: RegisterUpdate,
pub(crate) nonnull_count: Option<RegisterId>,
}
impl BoundRegisterWriter {
pub(crate) const fn may_overflow_decimal_precision(&self) -> bool {
matches!(self.update, RegisterUpdate::Decimal(DecimalUpdate::Add))
}
}
impl fmt::Display for BoundRegisterWriter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let slot = self.slot.index();
match self.update {
RegisterUpdate::Inc => write!(f, "Inc r{slot}")?,
RegisterUpdate::Word(kernel) => {
write!(f, "{kernel:?} r{slot} <- value[{}]", self.input)?;
}
RegisterUpdate::Decimal(kernel) => {
write!(f, "{kernel:?}D128 r{slot} <- decimal[{}]", self.input)?;
}
RegisterUpdate::RetainedRow(kernel) => {
write!(f, "{kernel:?}Row r{slot} <- row[{}]", self.input)?;
}
}
if let Some(count) = self.nonnull_count {
write!(f, ", count r{}", count.index())?;
}
if self.nullable {
write!(f, " if value[{}] is valid", self.input)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct ExecutableAccumulationProgram {
ops: Vec<BoundRegisterWriter>,
has_retained_row_updates: bool,
}
impl ExecutableAccumulationProgram {
#[inline]
pub(crate) fn ops(&self) -> &[BoundRegisterWriter] {
&self.ops
}
#[inline]
pub(crate) const fn has_retained_row_updates(&self) -> bool {
self.has_retained_row_updates
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct ExecutableNavigationProgram {
ops: Vec<NavigationUpdate>,
resolved: Vec<BoundNavigationUpdate>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct BoundNavigationUpdate {
pub(crate) target: PackedNavigationUpdate,
pub(crate) domain: crate::core::vm::NavigationValueDomain,
pub(crate) column: Option<usize>,
}
impl ExecutableNavigationProgram {
fn bind(
ops: Vec<NavigationUpdate>,
packed: &PackedNavigationLayout,
rows: &ResolvedRowBindings,
) -> Result<Self> {
if ops.is_empty() {
return Ok(Self::default());
}
let mut resolved = ops
.iter()
.map(|&op| {
use crate::core::vm::NavigationValueDomain;
let column = match op.domain {
NavigationValueDomain::Primitive => {
Some(rows.nav_columns[usize::from(op.value_idx)].index())
}
NavigationValueDomain::Decimal128 => {
Some(rows.nav_d128_columns[usize::from(op.value_idx)].index())
}
NavigationValueDomain::Classifier => None,
};
Ok(BoundNavigationUpdate {
target: packed.resolve_update(op)?,
domain: op.domain,
column,
})
})
.collect::<Result<Vec<_>>>()?;
resolved.sort_by_key(|s| {
(
match s.domain {
crate::core::vm::NavigationValueDomain::Primitive => 0,
crate::core::vm::NavigationValueDomain::Decimal128 => 1,
crate::core::vm::NavigationValueDomain::Classifier => 2,
},
s.column,
)
});
Ok(Self { ops, resolved })
}
#[inline]
pub(crate) fn ops(&self) -> &[NavigationUpdate] {
&self.ops
}
#[inline]
pub(crate) fn resolved(&self) -> &[BoundNavigationUpdate] {
&self.resolved
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExecutableEvaluatorKernel {
Static,
Typed,
Unsupported,
}
pub(super) fn bind_register_writer(
layout: &RegisterLayout,
row_bindings: &ResolvedRowBindings,
writer: RegisterWriter,
) -> Result<BoundRegisterWriter> {
use AggregateKind as K;
use RegisterUpdate::{Decimal, Word};
use SlotValueType as V;
let owner = writer.aggregate();
let aggregate = layout.aggregates().get(owner).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE register writer has no managed aggregate {owner}"
))
})?;
let info = aggregate.slot.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {owner} has no register allocation"
))
})?;
let slot = RegisterId::from_validated(info.start_slot);
let input = match writer {
RegisterWriter::Count { input, .. } => input,
RegisterWriter::Accumulate { input, .. } => Some(input),
};
let mut count = aggregate.nonnull_count_slot;
let update = match writer {
RegisterWriter::Count { .. } => {
if info.agg_kind != K::Additive
|| info.value_type != V::Int64
|| count.is_some()
{
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE COUNT writer has incompatible allocation for aggregate {owner}"
)));
}
RegisterUpdate::Inc
}
RegisterWriter::Accumulate { .. } => {
if info.agg_kind == K::Additive && count.is_none() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE SUM writer requires a non-null tracker for aggregate {owner}"
)));
}
if info.agg_kind == K::Avg {
count = Some(info.start_slot + info.value_type.slot_count());
}
match (info.agg_kind, info.value_type) {
(K::Additive | K::Avg, V::Decimal128) => Decimal(DecimalUpdate::Add),
(K::Additive | K::Avg, V::Float64) => Word(WordUpdate::AddF64),
(K::Additive, V::Int64 | V::UInt64) => Word(WordUpdate::Add),
(K::Avg, V::Int64 | V::UInt64) => {
return Err(DataFusionError::Internal(
"MATCH_RECOGNIZE non-Decimal128 AVG requires a Float64 register"
.into(),
));
}
(K::Additive | K::Avg, V::Float32) => {
return Err(DataFusionError::Internal(
"MATCH_RECOGNIZE floating SUM/AVG requires a widened Float64 register".into(),
));
}
(K::Min, V::Int64) => Word(WordUpdate::Min),
(K::Max, V::Int64) => Word(WordUpdate::Max),
(K::Min, V::UInt64) => Word(WordUpdate::MinU64),
(K::Max, V::UInt64) => Word(WordUpdate::MaxU64),
(K::Min, V::Float32) => Word(WordUpdate::MinF32),
(K::Max, V::Float32) => Word(WordUpdate::MaxF32),
(K::Min, V::Float64) => Word(WordUpdate::MinF64),
(K::Max, V::Float64) => Word(WordUpdate::MaxF64),
(K::Min, V::Decimal128) => Decimal(DecimalUpdate::Min),
(K::Max, V::Decimal128) => Decimal(DecimalUpdate::Max),
(K::Min | K::Max, V::RetainedRow) => {
if count.is_none() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE retained-row MIN/MAX writer requires a non-null tracker for aggregate {owner}"
)));
}
let op = if info.agg_kind == K::Min {
RetainedRowUpdate::Min
} else {
RetainedRowUpdate::Max
};
RegisterUpdate::RetainedRow(op)
}
(_, V::RetainedRow) => {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE retained-row register is valid only for MIN/MAX (aggregate {owner}, kind {:?})",
info.agg_kind
)));
}
(K::Variance, _) => Word(WordUpdate::UpdateVariance),
(K::BoolAnd, _) => Word(WordUpdate::BoolAnd),
(K::BoolOr, _) => Word(WordUpdate::BoolOr),
}
}
};
let binding = input
.map(|input| update.bind_input(input, row_bindings, layout))
.transpose()?;
Ok(BoundRegisterWriter {
column: binding.map_or(0, |binding| binding.column.index()),
input: input.unwrap_or(0),
force_float: binding.is_some_and(|binding| binding.force_float),
slot,
nullable: writer.null_input().is_some(),
update,
nonnull_count: count.map(RegisterId::from_validated),
})
}
pub(super) fn bind_update_program(
layout: &RegisterLayout,
packed: &PackedNavigationLayout,
row_bindings: &ResolvedRowBindings,
schema: &Schema,
bound_state_cells: &[BoundStateCell],
requests: &[RegisterWriter],
logical_symbol: usize,
) -> Result<ExecutableAggregateStateProgram> {
let mut ops = Vec::with_capacity(requests.len());
let mut has_retained_row_updates = false;
for &writer in requests {
let bound = bind_register_writer(layout, row_bindings, writer)?;
validate_extrema_output_type(schema, layout, bound_state_cells, writer, &bound)?;
has_retained_row_updates |=
matches!(bound.update, RegisterUpdate::RetainedRow(..));
ops.push(bound);
}
Ok(ExecutableAggregateStateProgram::new(
ExecutableAccumulationProgram {
ops,
has_retained_row_updates,
},
ExecutableNavigationProgram::bind(
layout.navigation_writers(logical_symbol),
packed,
row_bindings,
)?,
))
}
#[cfg(test)]
pub(crate) fn bind_test_update_program(
requests: &[RegisterWriter],
layout: &RegisterLayout,
) -> Result<ExecutableAggregateStateProgram> {
let schema = Schema::new(
layout
.row_input_names()
.iter()
.map(|name| {
datafusion::arrow::datatypes::Field::new(
name,
datafusion::arrow::datatypes::DataType::Int64,
true,
)
})
.collect::<Vec<_>>(),
);
let bindings = ResolvedRowBindings::try_new_with_static_inputs(
&schema,
layout,
Default::default(),
)?;
let packed = PackedNavigationLayout::try_new(
layout
.navigation_layout()
.unwrap_or(&NavigationLayout::default()),
)?;
bind_update_program(layout, &packed, &bindings, &schema, &[], requests, 0)
}
fn validate_extrema_output_type(
schema: &Schema,
register_layout: &RegisterLayout,
bound_state_cells: &[BoundStateCell],
writer: RegisterWriter,
bound: &BoundRegisterWriter,
) -> Result<()> {
let RegisterWriter::Accumulate {
aggregate: aggregate_index,
..
} = writer
else {
return Ok(());
};
let Some(slot) = register_layout.aggregates()[aggregate_index].slot else {
return Ok(());
};
if !matches!(slot.agg_kind, AggregateKind::Min | AggregateKind::Max) {
return Ok(());
}
let cell = &bound_state_cells[aggregate_index];
let output_type = cell.output_type();
let input_type = schema.field(bound.column).data_type();
if slot.value_type == SlotValueType::Int64 {
if input_type != output_type
&& (is_temporal_word_type(input_type) || is_temporal_word_type(output_type))
{
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {aggregate_index} MIN/MAX input type {input_type} does not match its output type {output_type}"
)));
}
} else if slot.value_type == SlotValueType::RetainedRow {
if input_type != output_type || !is_retained_row_extrema_type(input_type) {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {aggregate_index} retained-row MIN/MAX input type {input_type} does not match its output type {output_type}"
)));
}
if !matches!(
cell.source(),
BoundStateSource::RetainedRow { column: read_col, .. }
if read_col.index() == bound.column
) {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {aggregate_index} retained-row MIN/MAX writer column does not match its bound reader column"
)));
}
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RuntimeVmLayout {
initial_registers: [u64; MAX_REGISTERS],
register_slot_count: usize,
tier: VmTier,
}
impl RuntimeVmLayout {
pub(super) fn from_layout(layout: &RegisterLayout) -> Self {
Self {
initial_registers: layout.initial_registers(),
register_slot_count: layout.num_slots(),
tier: layout.vm_tier(),
}
}
#[inline]
pub(crate) const fn initial_registers(&self) -> [u64; MAX_REGISTERS] {
self.initial_registers
}
#[inline]
pub(crate) fn initial_inline_registers(&self) -> [u64; MAX_INLINE_REGISTERS] {
let mut inline = [0u64; MAX_INLINE_REGISTERS];
inline.copy_from_slice(&self.initial_registers[..MAX_INLINE_REGISTERS]);
inline
}
#[inline]
pub(crate) fn initial_registers_slice(&self) -> &[u64] {
&self.initial_registers[..self.register_slot_count]
}
#[inline]
pub(crate) const fn needs_register_spill(&self) -> bool {
self.register_slot_count > MAX_INLINE_REGISTERS
}
#[inline]
pub(crate) const fn register_slot_count(&self) -> usize {
self.register_slot_count
}
#[inline]
pub(crate) const fn tier(&self) -> VmTier {
self.tier
}
}
#[derive(Clone)]
pub(crate) struct ValidatedVmProgram {
pub(super) symbol_programs: Arc<[ExecutableSymbolProgram]>,
pub(super) runtime_layout: RuntimeVmLayout,
pub(super) navigation_layout: Option<Arc<NavigationLayout>>,
pub(super) packed_navigation_layout: Arc<PackedNavigationLayout>,
pub(super) row_bindings: ResolvedRowBindings,
pub(super) bound_state_cells: Arc<[BoundStateCell]>,
pub(super) aggregate_backend_set: ManagedAggregateBackendSet,
}
impl ValidatedVmProgram {
pub(super) fn validate_exact_backend_ownership(
aggregate_backends: &[ManagedAggregateBackend],
bound_state_cells: &[BoundStateCell],
) -> Result<()> {
for (aggregate_index, (backend, cell)) in
aggregate_backends.iter().zip(bound_state_cells).enumerate()
{
let bound_backend = if cell.is_state_owned() {
ManagedAggregateBackend::Registers
} else {
ManagedAggregateBackend::Accumulator
};
if *backend != bound_backend {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {aggregate_index} planned backend {backend:?} does not match its validated state source ({bound_backend:?})"
)));
}
}
Ok(())
}
#[inline]
pub(crate) fn symbol_programs(&self) -> &[ExecutableSymbolProgram] {
&self.symbol_programs
}
#[inline]
pub(crate) fn symbol_programs_arc(&self) -> Arc<[ExecutableSymbolProgram]> {
Arc::clone(&self.symbol_programs)
}
#[inline]
pub(crate) fn runtime_layout(&self) -> &RuntimeVmLayout {
&self.runtime_layout
}
#[inline]
pub(crate) fn packed_navigation_layout(&self) -> &Arc<PackedNavigationLayout> {
&self.packed_navigation_layout
}
pub(crate) fn navigation_layout(&self) -> Option<&NavigationLayout> {
self.navigation_layout.as_deref()
}
#[inline]
pub(crate) fn row_bindings(&self) -> &ResolvedRowBindings {
&self.row_bindings
}
#[inline]
pub(crate) fn bound_state_cells(&self) -> &[BoundStateCell] {
&self.bound_state_cells
}
pub(crate) fn visit_bound_input_columns(&self, mut visit: impl FnMut(usize)) {
let b = &self.row_bindings;
for column in b
.row_inputs
.iter()
.map(|b| b.column.index())
.chain(
b.static_scalar_columns
.iter()
.flatten()
.map(|b| b.column.index()),
)
.chain(b.nav_columns.iter().map(|b| b.index()))
.chain(b.nav_d128_columns.iter().map(|b| b.index()))
{
visit(column);
}
for cell in self.bound_state_cells.iter() {
match cell.source() {
BoundStateSource::CandidateStart { column }
| BoundStateSource::RetainedRow { column, .. } => visit(column.index()),
_ => {}
}
}
self.visit_direct_predicate_columns(visit);
}
pub(crate) fn visit_direct_predicate_columns(&self, mut visit: impl FnMut(usize)) {
for user in self
.symbol_programs
.iter()
.filter_map(ExecutableSymbolProgram::user)
{
if let ExecutableSymbolEvaluator::Incremental(
ExecutableIncrementalEvaluator::Direct { predicate, .. },
) = user.evaluator()
{
for column in &predicate.row_value_bindings.batch_columns {
visit(column.index());
}
}
}
}
#[inline]
pub(crate) const fn aggregate_backend_set(&self) -> ManagedAggregateBackendSet {
self.aggregate_backend_set
}
}
#[cfg(test)]
mod tests {
use super::{
NavigationSlotId, PreviousBufferId, RegisterId, RegisterUpdate,
ValidatedVmProgram, WordUpdate, bind_test_update_program,
};
use crate::core::vm::{
AggregateKind, AggregateLayout, AggregateValueSource, MAX_NAV_SLOTS,
MAX_PREV_BUFFERS, MAX_REGISTERS, NavSlotInfo, NavigationLayout,
NavigationValueDomain, RegisterLayout, RegisterWriter, SlotInfo, SlotValueType,
StatisticalPopulation, VarianceProjection, VmTier,
};
use crate::core::{SymbolEvalMode, SymbolId};
use crate::execution::matching::program::contracts::{
ResolvedVmStaticInputs, SymbolProgram, UserSymbolProgram,
};
use crate::execution::matching::{DefineCachePolicy, program::build::ProgramBuilder};
use crate::planning::{ManagedAggregateBackend, ManagedAggregateBackendSet};
use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use datafusion_common::Result;
fn additive_layout(track_nonnull: bool) -> RegisterLayout {
RegisterLayout::builder(
1 + usize::from(track_nonnull),
vec![AggregateLayout {
slot: Some(SlotInfo::int64(0)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: track_nonnull.then_some(1),
}],
)
.row_inputs(vec!["value".to_string()], vec![false])
.try_build()
.unwrap()
}
fn layout_with_min_and_max(value_type: SlotValueType) -> RegisterLayout {
RegisterLayout::builder(
4,
vec![
AggregateLayout {
slot: Some(SlotInfo::with_kind(0, value_type, 0, AggregateKind::Min)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: Some(1),
},
AggregateLayout {
slot: Some(SlotInfo::with_kind(2, value_type, 0, AggregateKind::Max)),
value_source: AggregateValueSource::Register { slot: 2 },
nonnull_count_slot: Some(3),
},
],
)
.row_inputs(vec!["value".to_string()], vec![false])
.try_build()
.unwrap()
}
#[test]
fn register_binding_checks_reserved_and_dense_symbol_slots() {
let error = try_empty_program(vec![]).unwrap_err();
assert!(
error.to_string().contains("reserved Empty slot zero"),
"{error}"
);
let error = try_program(
vec![SymbolProgram::User(
UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
SymbolEvalMode::Static,
None,
None,
vec![RegisterWriter::Count {
aggregate: 0,
input: None,
}],
None,
)
.unwrap(),
)],
&Schema::empty(),
RegisterLayout::builder(1, Vec::new()).try_build().unwrap(),
&[],
&[],
)
.err()
.expect("slot-0 register writer must fail");
assert!(
error.to_string().contains("reserved Empty slot zero"),
"{error}"
);
try_empty_program(static_source_programs(3)).unwrap();
for (left, right, fragment) in [
(0, 1, "out of order at dense index 0"),
(1, 2, "out of order at dense index 1"),
] {
let mut programs = static_source_programs(3);
programs.swap(left, right);
let error = try_empty_program(programs)
.expect_err("malformed input symbol table must fail");
assert!(error.to_string().contains(fragment), "{error}");
}
}
#[test]
fn register_writer_binds_guard_mutation_and_tracker_to_the_same_owner() {
let layout = additive_layout(true);
let make = |aggregate, input| RegisterWriter::Accumulate {
aggregate,
input,
nullable: true,
};
let program = bind_test_update_program(&[make(0, 0)], &layout).unwrap();
let [w] = program.accumulation.ops() else {
panic!("expected one writer")
};
assert!(w.nullable);
assert_eq!(w.column, 0);
assert_eq!(w.nonnull_count.unwrap().index(), 1);
assert!(matches!(w.update, RegisterUpdate::Word(WordUpdate::Add)));
assert_eq!(w.slot.index(), 0);
for request in [
make(1, 0),
make(0, 1),
RegisterWriter::Count {
aggregate: 0,
input: None,
},
] {
assert!(bind_test_update_program(&[request], &layout).is_err());
}
}
#[test]
fn extrema_binding_preserves_numeric_domain_and_indices() {
for domain in [SlotValueType::Float32, SlotValueType::UInt64] {
let layout = layout_with_min_and_max(domain);
let schema = Schema::new(vec![Field::new(
"value",
match domain {
SlotValueType::Float32 => DataType::Float32,
SlotValueType::UInt64 => DataType::UInt64,
_ => unreachable!(),
},
true,
)]);
let program = try_program(
vec![
SymbolProgram::Empty,
SymbolProgram::User(
UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
SymbolEvalMode::Static,
None,
None,
(0..2)
.map(|aggregate| RegisterWriter::Accumulate {
aggregate,
input: 0,
nullable: false,
})
.collect(),
None,
)
.unwrap(),
),
],
&schema,
layout,
&[
schema.field(0).data_type().clone(),
schema.field(0).data_type().clone(),
],
&[ManagedAggregateBackend::Registers; 2],
)
.unwrap();
let ops = program.symbol_programs()[1]
.user()
.unwrap()
.accumulation_program()
.ops();
let (min, max) = match domain {
SlotValueType::Float32 => (WordUpdate::MinF32, WordUpdate::MaxF32),
SlotValueType::UInt64 => (WordUpdate::MinU64, WordUpdate::MaxU64),
_ => unreachable!(),
};
for (writer, kernel, slot) in [(&ops[0], min, 0), (&ops[1], max, 2)] {
assert_eq!(writer.slot.index(), slot);
assert_eq!(writer.column, 0);
assert!(
matches!(writer.update, RegisterUpdate::Word(actual) if actual == kernel)
);
}
}
}
#[test]
fn variance_binding_preserves_distinct_state_and_input_indices() {
let slot =
SlotInfo::with_kind(1, SlotValueType::Float64, 0, AggregateKind::Variance);
let layout = RegisterLayout::builder(
4,
vec![AggregateLayout {
slot: Some(slot),
value_source: AggregateValueSource::Variance {
state_slot: 1,
projection: VarianceProjection::Variance(
StatisticalPopulation::Sample,
),
},
nonnull_count_slot: None,
}],
)
.row_inputs(vec!["value".into()], vec![true])
.try_build()
.unwrap();
let program = bind_test_update_program(
&[RegisterWriter::Accumulate {
aggregate: 0,
input: 0,
nullable: false,
}],
&layout,
)
.unwrap();
assert!(matches!(program.accumulation.ops(),
[super::BoundRegisterWriter {slot: state_slot, column: 0, update: RegisterUpdate::Word(WordUpdate::UpdateVariance), ..}]
if state_slot.index() == 1
));
}
#[test]
fn typed_handles_respect_logical_width_and_physical_boundaries() {
macro_rules! capacity {
($handle:ident, $limit:expr) => {{
let limit = $limit;
assert_eq!(
$handle::try_bind(limit - 1, 1, limit, stringify!($handle))
.unwrap()
.index(),
limit - 1
);
assert!(
$handle::try_bind(limit, 1, limit + 1, stringify!($handle)).is_err()
);
}};
}
capacity!(RegisterId, MAX_REGISTERS);
capacity!(NavigationSlotId, MAX_NAV_SLOTS);
capacity!(PreviousBufferId, MAX_PREV_BUFFERS);
let error = NavigationSlotId::try_bind(1, 2, 2, "navigation slot").unwrap_err();
assert!(error.to_string().contains("width=2"));
}
#[test]
fn resolved_navigation_groups_repeated_sources_without_changing_writes() -> Result<()>
{
use super::{
ExecutableNavigationProgram, PackedNavigationLayout, ResolvedRowBindings,
};
use crate::core::vm::PrevBufferInfo;
let slot = |nav_slot, value_idx| NavSlotInfo {
symbol_idx: Some(0),
nav_slot,
value_idx,
domain: NavigationValueDomain::Primitive,
};
let navigation = NavigationLayout {
num_nav_slots: 5,
num_prev_buffers: 1,
first_slots: vec![slot(0, 0), slot(1, 1)],
first_offsets: vec![1, 0],
last_slots: vec![slot(2, 0), slot(3, 1), slot(4, 0)],
prev_slots: vec![slot(4, 0)],
prev_buffer_slots: vec![PrevBufferInfo {
symbol_idx: Some(0),
depth: 3,
buffer_idx: 0,
value_idx: 0,
domain: NavigationValueDomain::Primitive,
}],
};
let packed = PackedNavigationLayout::try_new(&navigation)?;
let layout = RegisterLayout::builder(0, vec![])
.navigation_inputs(vec!["x".into(), "y".into()], vec![], Some(navigation))
.try_build()
.unwrap();
let schema = Schema::new(vec![
Field::new("x", DataType::Int64, true),
Field::new("y", DataType::Int64, true),
]);
let rows = ResolvedRowBindings::try_new_with_static_inputs(
&schema,
&layout,
Default::default(),
)?;
let program = ExecutableNavigationProgram::bind(
layout.navigation_writers(0),
&packed,
&rows,
)?;
assert_eq!(
program
.resolved()
.iter()
.map(|s| s.column.unwrap())
.collect::<Vec<_>>(),
[0, 0, 0, 0, 1, 1]
);
let mut logical = vec![0; packed.frame_words()];
let mut resolved = logical.clone();
for row in 0..5 {
for &update in program.ops() {
let column = usize::from(update.value_idx);
packed.view_mut(&mut logical)?.apply_update(
update,
[row + column as u64, 0],
row == 2 && column == 0,
)?;
}
for store in program.resolved() {
let column = store.column.unwrap();
store.target.apply(
&mut resolved,
[row + column as u64, 0],
row == 2 && column == 0,
);
}
assert_eq!(resolved, logical);
}
Ok(())
}
#[test]
fn scoped_navigation_is_independent_of_a_nullable_register_writer() {
let navigation_layout = NavigationLayout {
num_nav_slots: 1,
last_slots: vec![NavSlotInfo {
symbol_idx: Some(0),
nav_slot: 0,
value_idx: 0,
domain: NavigationValueDomain::Primitive,
}],
..Default::default()
};
let layout = RegisterLayout::builder(
1,
vec![AggregateLayout {
slot: Some(SlotInfo::int64(0)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: None,
}],
)
.row_inputs(vec!["value".into()], vec![false])
.navigation_inputs(vec!["value".into()], vec![], Some(navigation_layout))
.try_build()
.unwrap();
let requests = vec![RegisterWriter::Count {
aggregate: 0,
input: Some(0),
}];
let program = bind_test_update_program(&requests, &layout).unwrap();
let [writer] = program.accumulation.ops() else {
panic!("expected one COUNT")
};
assert!(writer.nullable);
assert_eq!(writer.column, 0);
assert_eq!(program.navigation.ops().len(), 1);
let accumulation_only = bind_test_update_program(
&[RegisterWriter::Count {
aggregate: 0,
input: None,
}],
&additive_layout(false),
)
.unwrap();
assert!(accumulation_only.navigation.ops().is_empty());
}
fn try_program(
symbols: Vec<SymbolProgram>,
schema: &Schema,
register_layout: RegisterLayout,
aggregate_output_types: &[DataType],
aggregate_backends: &[ManagedAggregateBackend],
) -> Result<ValidatedVmProgram> {
let prechecks = vec![Default::default(); symbols.len()];
ProgramBuilder::bind_vm(
schema,
symbols,
register_layout,
ResolvedVmStaticInputs::default(),
aggregate_output_types,
aggregate_backends,
DefineCachePolicy::Disabled,
prechecks,
)
}
fn static_source_programs(symbol_count: usize) -> Vec<SymbolProgram> {
let mut programs = Vec::with_capacity(symbol_count);
programs.push(SymbolProgram::Empty);
programs.extend((1..symbol_count).map(|dense_index| {
SymbolProgram::User(
UserSymbolProgram::try_new(
SymbolId::try_new(dense_index, symbol_count).unwrap(),
SymbolEvalMode::Static,
None,
None,
Vec::new(),
None,
)
.unwrap(),
)
}));
programs
}
fn check_int64_layout(
symbol_count: usize,
register_layout: RegisterLayout,
aggregate_backends: &[ManagedAggregateBackend],
) -> Result<()> {
let aggregate_output_types = vec![DataType::Int64; aggregate_backends.len()];
try_program(
static_source_programs(symbol_count),
&Schema::empty(),
register_layout,
&aggregate_output_types,
aggregate_backends,
)
.map(drop)
}
fn check_extrema_layout(
input_type: DataType,
output_type: DataType,
minimum: bool,
) -> Result<()> {
let unsigned = matches!(input_type, DataType::UInt64);
let slot_type = if unsigned {
SlotValueType::UInt64
} else {
SlotValueType::Int64
};
let kind = if minimum {
AggregateKind::Min
} else {
AggregateKind::Max
};
let state_width = slot_type.slot_count();
let layout = RegisterLayout::builder(
state_width + 1,
vec![AggregateLayout {
slot: Some(SlotInfo::with_kind(0, slot_type, 0, kind)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: Some(state_width),
}],
)
.row_inputs(vec!["VALUE".into()], vec![false])
.try_build()
.unwrap();
let programs = vec![
SymbolProgram::Empty,
SymbolProgram::User(
UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
SymbolEvalMode::Static,
None,
None,
vec![RegisterWriter::Accumulate {
aggregate: 0,
input: 0,
nullable: true,
}],
None,
)
.unwrap(),
),
];
try_program(
programs,
&Schema::new(vec![Field::new("value", input_type, true)]),
layout,
&[output_type],
&[ManagedAggregateBackend::Registers],
)
.map(drop)
}
#[test]
fn register_extrema_reject_binary_and_accept_uint64() {
for minimum in [true, false] {
assert!(
check_extrema_layout(
DataType::FixedSizeBinary(8),
DataType::FixedSizeBinary(8),
minimum
)
.is_err()
);
check_extrema_layout(DataType::UInt64, DataType::UInt64, minimum).unwrap();
}
}
#[test]
fn draft_extrema_preserve_exact_temporal_metadata() {
let temporal_types = [
DataType::Date32,
DataType::Date64,
DataType::Time32(TimeUnit::Second),
DataType::Time32(TimeUnit::Millisecond),
DataType::Time64(TimeUnit::Microsecond),
DataType::Time64(TimeUnit::Nanosecond),
DataType::Duration(TimeUnit::Second),
DataType::Duration(TimeUnit::Millisecond),
DataType::Duration(TimeUnit::Microsecond),
DataType::Duration(TimeUnit::Nanosecond),
DataType::Timestamp(TimeUnit::Second, None),
DataType::Timestamp(TimeUnit::Millisecond, None),
DataType::Timestamp(TimeUnit::Microsecond, None),
DataType::Timestamp(TimeUnit::Nanosecond, None),
DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
DataType::Timestamp(TimeUnit::Nanosecond, Some("Europe/Berlin".into())),
];
for minimum in [true, false] {
for input in &temporal_types {
check_extrema_layout(input.clone(), input.clone(), minimum).unwrap();
}
for (input, output) in [
(DataType::Date32, DataType::Date64),
(
DataType::Time32(TimeUnit::Second),
DataType::Time32(TimeUnit::Millisecond),
),
(
DataType::Time64(TimeUnit::Microsecond),
DataType::Time64(TimeUnit::Nanosecond),
),
(
DataType::Duration(TimeUnit::Second),
DataType::Duration(TimeUnit::Millisecond),
),
(
DataType::Timestamp(TimeUnit::Second, None),
DataType::Timestamp(TimeUnit::Nanosecond, None),
),
(
DataType::Timestamp(TimeUnit::Nanosecond, None),
DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
),
(
DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
DataType::Timestamp(
TimeUnit::Nanosecond,
Some("Europe/Berlin".into()),
),
),
(DataType::Date32, DataType::Int64),
(DataType::Int64, DataType::Date32),
] {
let error = check_extrema_layout(input, output, minimum).unwrap_err();
assert!(error.to_string().contains("MIN/MAX input type"), "{error}");
}
}
}
fn try_empty_program(symbol_programs: Vec<SymbolProgram>) -> Result<()> {
try_program(
symbol_programs,
&Schema::empty(),
RegisterLayout::default(),
&[],
&[],
)
.map(drop)
}
#[test]
fn final_program_precomputes_register_initializers_and_aggregate_backends() {
let schema = Schema::new(vec![Field::new("value", DataType::Int64, true)]);
let register_layout = RegisterLayout::builder(
2,
vec![AggregateLayout {
slot: Some(SlotInfo::with_kind(
0,
SlotValueType::Int64,
0,
AggregateKind::Min,
)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: Some(1),
}],
)
.row_inputs(vec!["value".to_string()], vec![false])
.vm_tier(VmTier::Standard)
.try_build()
.unwrap();
for (layout, backend, expected_backend, minimum_initializer) in [
(
register_layout,
ManagedAggregateBackend::Registers,
ManagedAggregateBackendSet::RegistersOnly,
true,
),
(
RegisterLayout::empty_compact(1),
ManagedAggregateBackend::Accumulator,
ManagedAggregateBackendSet::HasAccumulator,
false,
),
] {
let program = try_program(
static_source_programs(3),
&schema,
layout,
&[DataType::Int64],
&[backend],
)
.unwrap();
let mut expected = [0; MAX_REGISTERS];
if minimum_initializer {
expected[0] = i64::MAX as u64;
}
assert_eq!(program.runtime_layout().initial_registers(), expected);
assert_eq!(program.aggregate_backend_set(), expected_backend);
assert_eq!(
program.runtime_layout().tier(),
if minimum_initializer {
VmTier::Standard
} else {
VmTier::Compact
}
);
}
}
#[test]
fn binding_resolves_writer_columns_coercions_and_domains_together() {
for (input_type, force_float, expected_error) in [
(DataType::Int64, true, None),
(DataType::Float32, true, None),
(DataType::Float64, false, None),
(DataType::Decimal128(18, 2), true, None),
(
DataType::Int64,
false,
Some(
"MATCH_RECOGNIZE VM row input column 'VALUE' has resolved domain Int64, incompatible with Float64 accumulation",
),
),
(
DataType::Utf8,
true,
Some(
"MATCH_RECOGNIZE VM floating-point input column 'VALUE' has type Utf8, expected a numeric column",
),
),
] {
let schema = Schema::new(vec![
Field::new("label", DataType::Utf8, true),
Field::new("unused", DataType::Boolean, false),
Field::new("value", input_type, true),
]);
let layout = RegisterLayout::builder(
3,
vec![
AggregateLayout {
slot: Some(SlotInfo::with_kind(
0,
SlotValueType::Float64,
0,
AggregateKind::Additive,
)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: Some(1),
},
AggregateLayout {
slot: Some(SlotInfo::int64(2)),
value_source: AggregateValueSource::Register { slot: 2 },
nonnull_count_slot: None,
},
],
)
.row_inputs(
vec!["VALUE".into(), "label".into()],
vec![force_float, false],
)
.try_build()
.unwrap();
let symbols = vec![
SymbolProgram::Empty,
SymbolProgram::User(
UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
SymbolEvalMode::Static,
None,
None,
vec![
RegisterWriter::Accumulate {
aggregate: 0,
input: 0,
nullable: true,
},
RegisterWriter::Count {
aggregate: 1,
input: Some(1),
},
RegisterWriter::Count {
aggregate: 1,
input: None,
},
],
None,
)
.unwrap(),
),
];
let result = try_program(
symbols,
&schema,
layout,
&[DataType::Float64, DataType::Int64],
&[ManagedAggregateBackend::Registers; 2],
);
if let Some(expected) = expected_error {
let Err(datafusion_common::DataFusionError::Internal(message)) = result
else {
panic!("expected Internal domain rejection");
};
assert_eq!(message, expected);
} else {
let program = result.unwrap();
let ops = program.symbol_programs()[1]
.user()
.unwrap()
.accumulation_program()
.ops();
assert_eq!(
ops.iter()
.map(|writer| (writer.column, writer.force_float))
.collect::<Vec<_>>(),
vec![(2, force_float), (0, false), (0, false)]
);
assert!(ops[0].nullable);
assert!(ops[1].nullable);
assert!(!ops[2].nullable);
}
}
}
#[test]
fn row_bindings_use_the_program_layout() {
let layout = RegisterLayout::builder(0, vec![])
.row_inputs(vec!["missing".to_string()], vec![])
.try_build()
.unwrap();
let symbol_count = 3;
let error = check_int64_layout(symbol_count, layout, &[])
.expect_err("the zero-aggregate layout must reject its missing layout input");
assert!(error.to_string().contains("missing"));
}
#[test]
fn aggregate_cardinality_requires_exact_alignment() {
for (aggregates, backends, valid) in [
(0, vec![], true),
(1, vec![ManagedAggregateBackend::Accumulator], true),
(1, vec![], false),
(0, vec![ManagedAggregateBackend::Accumulator], false),
] {
let result = check_int64_layout(
3,
RegisterLayout::empty_compact(aggregates),
&backends,
);
if valid {
result.unwrap();
} else {
assert!(
result
.unwrap_err()
.to_string()
.contains("VM scratch metadata is not aligned")
);
}
}
}
#[test]
fn binding_checks_each_aggregate_backend() {
let layout = RegisterLayout::builder(
1,
vec![
AggregateLayout {
slot: Some(SlotInfo::int64(0)),
value_source: AggregateValueSource::Register { slot: 0 },
nonnull_count_slot: None,
},
AggregateLayout::default(),
],
)
.try_build()
.unwrap();
let symbol_count = 3;
let error = check_int64_layout(
symbol_count,
layout,
&[
ManagedAggregateBackend::Accumulator,
ManagedAggregateBackend::Registers,
],
)
.expect_err("a collapsed HasAccumulator set must not hide swapped routes");
assert!(error.to_string().contains("managed aggregate 0"));
assert!(error.to_string().contains("planned backend Accumulator"));
assert!(error.to_string().contains("Registers"));
}
#[test]
fn retained_row_extrema_require_matching_writer_and_reader_columns() {
let schema = Schema::new(vec![
Field::new("value", DataType::Utf8, true),
Field::new("other", DataType::Utf8, true),
]);
for kind in [AggregateKind::Min, AggregateKind::Max] {
for (reader_col, should_succeed) in [("value", true), ("other", false)] {
let layout = RegisterLayout::builder(
2,
vec![AggregateLayout {
slot: Some(SlotInfo::with_kind(
0,
SlotValueType::RetainedRow,
0,
kind,
)),
value_source: AggregateValueSource::RetainedRow {
slot: 0,
column: reader_col.into(),
},
nonnull_count_slot: Some(1),
}],
)
.row_inputs(vec!["value".into()], vec![false])
.try_build()
.unwrap();
let programs = vec![
SymbolProgram::Empty,
SymbolProgram::User(
UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
SymbolEvalMode::Static,
None,
None,
vec![RegisterWriter::Accumulate {
aggregate: 0,
input: 0,
nullable: true,
}],
None,
)
.unwrap(),
),
];
let result = try_program(
programs,
&schema,
layout,
&[DataType::Utf8],
&[ManagedAggregateBackend::Registers],
);
if should_succeed {
assert!(result.is_ok());
} else {
let Err(error) = result else {
panic!(
"mismatched retained-row writer and reader columns must fail"
);
};
assert!(
error.to_string().contains("writer column does not match"),
"{error}"
);
}
}
}
}
#[test]
fn hybrid_guard_excluded_reference_resolves_local_excluded_binding() {
use super::{Column, MatchMetadataColumn};
use crate::execution::matching::program::contracts::PhysicalHybridGuardExpr;
use datafusion::common::ScalarValue;
use datafusion::physical_expr::PhysicalExpr;
use datafusion::physical_expr::expressions::Literal;
use std::sync::Arc;
let schema = Schema::new(vec![Field::new(
MatchMetadataColumn::Excluded.as_ref(),
DataType::Boolean,
true,
)]);
let true_local: Arc<dyn PhysicalExpr> =
Arc::new(Literal::new(ScalarValue::Boolean(Some(true))));
let hybrid_with_excluded = UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
SymbolEvalMode::Hybrid,
Some(Arc::clone(&true_local)),
Some(PhysicalHybridGuardExpr::And(
Box::new(PhysicalHybridGuardExpr::Local(Arc::new(Column::new(
MatchMetadataColumn::Excluded.as_ref(),
0,
)))),
Box::new(PhysicalHybridGuardExpr::Unknown),
)),
vec![],
None,
)
.unwrap();
let bound = try_program(
vec![
SymbolProgram::Empty,
SymbolProgram::User(hybrid_with_excluded),
],
&schema,
RegisterLayout::default(),
&[],
&[],
)
.unwrap();
assert_eq!(
bound
.row_bindings()
.excluded_column
.map(|column| column.index()),
Some(0)
);
let hybrid_without_excluded = UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
SymbolEvalMode::Hybrid,
Some(true_local),
Some(PhysicalHybridGuardExpr::Unknown),
vec![],
None,
)
.unwrap();
let unbound = try_program(
vec![
SymbolProgram::Empty,
SymbolProgram::User(hybrid_without_excluded),
],
&schema,
RegisterLayout::default(),
&[],
&[],
)
.unwrap();
assert!(unbound.row_bindings().excluded_column.is_none());
}
}