use super::decode::*;
use super::schema::{output_type_matches, validate_output_schema};
use super::*;
use crate::core::{
MatchMetadataColumn, MatchRecognizeOutputSpec, MatchSummaryField,
classifier_bits_col_name, is_reserved_internal_column_name,
};
use crate::planning::can_have_nulls_outside_bitmap;
use crate::planning::logical::{LogicalMatchOutput, LogicalSelectedMatchSummary};
use datafusion::common::ScalarValue;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::functions_aggregate::count::count_udaf;
use datafusion::logical_expr::{
ExprSchemable, Projection, SortExpr, TableType, WindowFrameBound,
};
use datafusion_substrait::logical_plan::consumer::{
DefaultSubstraitLambdaConsumer, from_scalar_function, from_substrait_func_args,
};
use std::collections::BTreeMap;
use std::ops::Range;
pub async fn from_substrait_plan_with_match_recognize(
state: &SessionState,
plan: &Plan,
) -> Result<LogicalPlan> {
let extensions = Extensions::try_from(&plan.extensions)?;
if !extensions.type_variations.is_empty() {
return not_impl_err!("Type variation extensions are not supported");
}
let consumer = MatchRecognizeSubstraitConsumer::new(&extensions, state);
from_substrait_plan_with_consumer(&consumer, plan).await
}
pub struct MatchRecognizeSubstraitConsumer<'a> {
extensions: &'a Extensions,
state: &'a SessionState,
outer_schemas: RwLock<Vec<Arc<DFSchema>>>,
lambda_consumer: DefaultSubstraitLambdaConsumer,
}
impl<'a> MatchRecognizeSubstraitConsumer<'a> {
pub fn new(extensions: &'a Extensions, state: &'a SessionState) -> Self {
Self {
extensions,
state,
outer_schemas: RwLock::new(Vec::new()),
lambda_consumer: DefaultSubstraitLambdaConsumer::new(),
}
}
}
#[async_trait]
impl SubstraitConsumer for MatchRecognizeSubstraitConsumer<'_> {
async fn resolve_table_ref(
&self,
table_ref: &TableReference,
) -> Result<Option<Arc<dyn TableProvider>>> {
let table = table_ref.table().to_string();
let schema = self.state.schema_for_ref(table_ref.clone())?;
let table_provider = schema.table(&table).await?;
Ok(table_provider)
}
fn get_extensions(&self) -> &Extensions {
self.extensions
}
fn get_function_registry(&self) -> &impl FunctionRegistry {
self.state
}
fn push_outer_schema(&self, schema: Arc<DFSchema>) {
self.outer_schemas.write().unwrap().push(schema);
}
fn pop_outer_schema(&self) {
self.outer_schemas.write().unwrap().pop();
}
fn get_outer_schema(&self, steps_out: usize) -> Option<Arc<DFSchema>> {
let schemas = self.outer_schemas.read().unwrap();
schemas
.len()
.checked_sub(steps_out)
.and_then(|idx| schemas.get(idx).cloned())
}
fn push_lambda_parameters(
&self,
parameters: &[proto::Type],
input_schema: &DFSchema,
) -> Result<Vec<String>> {
self.lambda_consumer
.push_lambda_parameters(self, parameters, input_schema)
}
fn pop_lambda_parameters(&self) {
self.lambda_consumer.pop_lambda_parameters();
}
fn lambda_variable(&self, steps_out: usize, field_idx: usize) -> Result<Expr> {
self.lambda_consumer.lambda_variable(steps_out, field_idx)
}
async fn consume_scalar_function(
&self,
function: &proto::expression::ScalarFunction,
input_schema: &DFSchema,
) -> Result<Expr> {
if self
.extensions
.functions
.get(&function.function_reference)
.is_some_and(|name| name == BUILTIN_SUBSTRING_NAME)
{
if !matches!(function.arguments.len(), 2 | 3) {
return plan_err!(
"MATCH_RECOGNIZE SUBSTRING expects two or three arguments"
);
}
let args =
from_substrait_func_args(self, &function.arguments, input_schema).await?;
return Ok(datafusion::functions::unicode::substr().call(args));
}
from_scalar_function(self, function, input_schema).await
}
async fn consume_window_function(
&self,
expr: &proto::expression::WindowFunction,
input_schema: &DFSchema,
) -> Result<Expr> {
window::decode_window_function(self, expr, input_schema).await
}
async fn consume_extension_single(
&self,
rel: &ExtensionSingleRel,
) -> Result<LogicalPlan> {
let detail = rel.detail.as_ref().ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"ExtensionSingleRel missing detail".to_string(),
)
})?;
if detail.type_url != MATCH_RECOGNIZE_TYPE_URL {
return plan_err!(
"MATCH_RECOGNIZE Substrait adapter rejected unknown ExtensionSingleRel type URL '{}'",
detail.type_url
);
}
if matches!(
rel.common
.as_ref()
.and_then(|common| common.emit_kind.as_ref()),
Some(EmitKind::Emit(_))
) {
return plan_err!(
"MATCH_RECOGNIZE Substrait extension does not support ExtensionSingleRel.common.emit"
);
}
let input_rel = rel.input.as_ref().ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE ExtensionSingleRel missing input".to_string(),
)
})?;
let input = self.consume_rel(input_rel).await?;
let (payload, capabilities, boundary) = decode_match_recognize_payload(detail)?;
let input = if boundary == MatchRecognizeBoundary::CompletePlan {
input
} else {
sanitize_semantic_node_input(input, &payload.symbols)?
};
let decoded = decode_match_recognize_detail_from_payload(
self,
payload,
capabilities,
boundary,
input.schema(),
)
.await?;
let mut planning_context = SubstraitPlanningContext { state: self.state };
validate_define_declaration(&mut planning_context, &input, &decoded)?;
let boundary = decoded.boundary;
let planned = match boundary {
MatchRecognizeBoundary::CompletePlan => {
plan_match_recognize_from_source_with_capabilities(
&mut planning_context,
input,
decoded.spec,
decoded.capabilities,
)?
}
MatchRecognizeBoundary::RowStreamNode => {
plan_match_recognize_node_from_source_with_capabilities(
&mut planning_context,
input,
decoded.spec,
decoded.capabilities,
)?
}
MatchRecognizeBoundary::OneRowNode => {
plan_match_recognize_native_one_row_node_from_source_with_capabilities(
&mut planning_context,
input,
decoded.spec,
decoded.capabilities,
)?
}
};
let expected = from_substrait_named_struct(self, &decoded.output_schema)?;
let expected_types = decoded
.output_schema
.r#struct
.as_ref()
.ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE output schema missing struct".to_string(),
)
})?
.types
.as_slice();
let planned = if boundary == MatchRecognizeBoundary::CompletePlan {
planned
} else {
align_semantic_output(
planned,
&expected,
expected_types,
&decoded.retained_passthrough_input_fields,
&decoded.prepared_output_fields,
&decoded.summary_output_fields,
)?
};
validate_output_schema(&planned, &expected, expected_types, boundary)?;
Ok(planned)
}
async fn consume_extension_leaf(
&self,
rel: &ExtensionLeafRel,
) -> Result<LogicalPlan> {
let Some(detail) = rel.detail.as_ref() else {
return substrait_err!("Unexpected empty detail in ExtensionLeafRel");
};
plan_err!(
"MATCH_RECOGNIZE Substrait adapter rejected unsupported ExtensionLeafRel type URL '{}'",
detail.type_url
)
}
async fn consume_extension_multi(
&self,
rel: &ExtensionMultiRel,
) -> Result<LogicalPlan> {
let Some(detail) = rel.detail.as_ref() else {
return substrait_err!("Unexpected empty detail in ExtensionMultiRel");
};
plan_err!(
"MATCH_RECOGNIZE Substrait adapter rejected unsupported ExtensionMultiRel type URL '{}'",
detail.type_url
)
}
}
struct PlannedSummary {
exact: DecodedSummaryAggregate,
folded: Option<DecodedSummaryAggregate>,
is_builtin_count: bool,
is_volatile: bool,
}
fn align_semantic_output(
plan: LogicalPlan,
expected: &DFSchema,
expected_types: &[proto::Type],
retained_input_fields: &[Column],
prepared_output_fields: &[(usize, Expr)],
summary_output_fields: &[(usize, DecodedSummaryAggregate)],
) -> Result<LogicalPlan> {
let LogicalPlan::Extension(extension) = &plan else {
return plan_err!(
"MATCH_RECOGNIZE native semantic-node planning did not return an extension node"
);
};
let Some(node) = extension.node.as_any().downcast_ref::<MatchRecognize>() else {
return plan_err!(
"MATCH_RECOGNIZE native semantic-node planning returned an unexpected extension node"
);
};
let source_input = node
.bound_source()
.ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE native semantic-node planning did not retain bound source"
.to_string(),
)
})?
.input();
let source_schema = source_input.schema();
let full = node.program().output();
let spec = full.spec();
let passthrough = spec.passthrough_input_indices();
let actual = node.schema();
let metadata_start = passthrough.len();
let classifier_start = metadata_start + spec.metadata_columns().len();
let summary_start = classifier_start + spec.classifier_bitset_symbols().len();
let ordinary_source_positions = passthrough
.iter()
.enumerate()
.filter_map(|(position, &index)| {
let (qualifier, field) = node.input().schema().qualified_field(index);
source_schema
.qualified_field_from_column(&Column::new(
qualifier.cloned(),
field.name(),
))
.is_ok()
.then_some(position)
})
.collect::<BTreeSet<_>>();
let mut retained = Vec::with_capacity(expected.fields().len());
let mut used = BTreeSet::new();
for column in retained_input_fields {
let input_index = node.input().schema().index_of_column(column)?;
let positions = passthrough
.iter()
.enumerate()
.filter(|(_, index)| **index == input_index)
.map(|(position, _)| position)
.collect::<Vec<_>>();
let [position] = positions.as_slice() else {
return plan_err!(
"MATCH_RECOGNIZE retained input column '{}' does not identify one passthrough output",
column
);
};
used.insert(*position);
retained.push(*position);
}
let mut prepared_windows = BTreeMap::new();
for (position, &index) in passthrough.iter().enumerate() {
if !ordinary_source_positions.contains(&position)
&& let Some(expression) =
producer::prepared_window_expr(node, index, source_schema)?
{
prepared_windows.insert(
position,
normalize_prepared_window_expr(expression, source_schema)?,
);
}
}
let prepared_output_fields = prepared_output_fields
.iter()
.map(|(position, expression)| {
Ok((
*position,
normalize_prepared_window_expr(expression.clone(), source_schema)?,
))
})
.collect::<Result<BTreeMap<_, _>>>()?;
let symbols = node
.program()
.symbols()
.iter()
.map(|symbol| symbol.name().to_string())
.collect::<Vec<_>>();
let builtin_count = count_udaf();
let (planned_summaries, expected_summaries) = if !full
.selected_match_summaries()
.is_empty()
|| !summary_output_fields.is_empty()
{
let summary_schema = summary_wire_decode_schema(source_schema, &symbols)?;
let source_len = source_schema.fields().len();
let planned_summaries = full
.selected_match_summaries()
.iter()
.map(|summary| {
let exact = planned_summary_identity(
summary,
node,
source_schema,
&summary_schema,
&symbols,
)?;
let is_builtin_count =
Arc::ptr_eq(summary.aggregate().func.inner(), builtin_count.inner());
let folded = is_builtin_count
.then(|| {
folded_required_count_identity(&exact, source_input, &symbols)
})
.flatten();
let is_volatile =
Expr::AggregateFunction(summary.aggregate().clone()).is_volatile();
Ok(PlannedSummary {
exact,
folded,
is_builtin_count,
is_volatile,
})
})
.collect::<Result<Vec<_>>>()?;
let expected_summaries = summary_output_fields
.iter()
.map(|(position, summary)| {
Ok((
*position,
normalize_decoded_summary(
summary,
&summary_schema,
source_len,
&symbols,
)?,
))
})
.collect::<Result<BTreeMap<_, _>>>()?;
(planned_summaries, expected_summaries)
} else {
(Vec::new(), BTreeMap::new())
};
let mut seen_non_volatile_summaries = Vec::new();
for (output_index, expected_field) in
expected.fields().iter().enumerate().skip(retained.len())
{
if let Some(expected_summary) = expected_summaries.get(&output_index) {
let mut exact_matches = Vec::new();
for (offset, planned) in planned_summaries.iter().enumerate() {
let position = summary_start + offset;
let field = actual.field(position);
if !used.contains(&position)
&& planned.exact == *expected_summary
&& field.is_nullable() == expected_field.is_nullable()
&& output_type_matches(
field.data_type(),
expected_field.data_type(),
&expected_types[output_index],
)?
{
exact_matches.push(offset);
}
}
if exact_matches.len() > 1 {
let by_name = exact_matches
.iter()
.copied()
.filter(|&offset| {
actual.field(summary_start + offset).name()
== expected_field.name()
})
.collect::<Vec<_>>();
exact_matches = if by_name.is_empty() {
vec![exact_matches[0]]
} else {
by_name
};
}
let (matched_offset, matched_exact) = match exact_matches.as_slice() {
[offset] => (*offset, true),
[] => {
if seen_non_volatile_summaries.contains(&expected_summary) {
return plan_err!(
"MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
expected_field.name()
);
}
let expected_folded = folded_required_count_identity(
expected_summary,
source_input,
&symbols,
);
let mut folded_matches = Vec::new();
for (offset, planned) in planned_summaries.iter().enumerate() {
let position = summary_start + offset;
let field = actual.field(position);
if !planned.is_volatile
&& planned.is_builtin_count
&& field.is_nullable() == expected_field.is_nullable()
&& output_type_matches(
field.data_type(),
expected_field.data_type(),
&expected_types[output_index],
)?
&& (expected_folded.as_ref() == Some(&planned.exact)
|| planned.folded.as_ref() == Some(expected_summary))
{
folded_matches.push(offset);
}
}
let Some(&offset) = folded_matches.first() else {
return plan_err!(
"MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
expected_field.name()
);
};
(offset, false)
}
_ => {
return plan_err!(
"MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
expected_field.name()
);
}
};
let position = summary_start + matched_offset;
if matched_exact {
used.insert(position);
}
if !planned_summaries[matched_offset].is_volatile
&& !seen_non_volatile_summaries.contains(&expected_summary)
{
seen_non_volatile_summaries.push(expected_summary);
}
retained.push(position);
continue;
}
let prepared = prepared_output_fields.get(&output_index);
let mut positions = Vec::new();
for (position, field) in actual.fields().iter().enumerate().take(summary_start) {
if !ordinary_source_positions.contains(&position)
&& !used.contains(&position)
&& match prepared {
Some(expression) => {
prepared_windows.get(&position) == Some(expression)
}
None => {
!prepared_windows.contains_key(&position)
&& field.name() == expected_field.name()
}
}
&& field.is_nullable() == expected_field.is_nullable()
&& output_type_matches(
field.data_type(),
expected_field.data_type(),
&expected_types[output_index],
)?
{
positions.push(position);
}
}
if positions.len() > 1
&& let Some(expression) = prepared
{
if expression.is_volatile() {
positions.retain(|&position| {
actual.field(position).name() == expected_field.name()
});
} else {
let by_name = positions
.iter()
.copied()
.filter(|&position| {
actual.field(position).name() == expected_field.name()
})
.collect::<Vec<_>>();
positions = if by_name.is_empty() {
vec![positions[0]]
} else {
by_name
};
}
}
let [position] = positions.as_slice() else {
return plan_err!(
"MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
expected_field.name()
);
};
used.insert(*position);
retained.push(*position);
}
let mut selected_passthrough = Vec::new();
let mut selected_metadata = Vec::new();
let mut selected_classifiers = Vec::new();
let mut selected_summaries = Vec::new();
let mut previous_group = 0;
for index in retained {
let group = if index < metadata_start {
selected_passthrough.push(passthrough[index]);
0
} else if index < classifier_start {
selected_metadata.push(spec.metadata_columns()[index - metadata_start]);
1
} else if index < summary_start {
selected_classifiers
.push(spec.classifier_bitset_symbols()[index - classifier_start].clone());
2
} else {
let summary = &full.selected_match_summaries()[index - summary_start];
let field = MatchSummaryField::new(
selected_summaries.len(),
summary.field().arrow_field(),
);
selected_summaries.push(LogicalSelectedMatchSummary::new(
field,
summary.aggregate().clone(),
));
3
};
if group < previous_group {
return plan_err!(
"MATCH_RECOGNIZE native semantic-node output fields are not in matcher output order"
);
}
previous_group = group;
}
let selected_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
selected_passthrough,
selected_metadata,
selected_classifiers,
spec.navigation_offsets(),
)
.with_partition_expr_inputs(spec.retains_partition_expr_inputs());
let output = match full {
LogicalMatchOutput::SelectedSummaries { input_spec, .. } => {
LogicalMatchOutput::selected_summaries(
selected_spec,
input_spec.clone(),
selected_summaries,
)
}
LogicalMatchOutput::Rows { rows_per_match, .. } => {
LogicalMatchOutput::rows(rows_per_match.clone(), selected_spec)
}
};
let aligned = node.rebuild_with_output(output)?;
if let Some(grouped) = aligned.grouped_output_plan()? {
return Ok(grouped);
}
Ok(LogicalPlan::Extension(Extension {
node: Arc::new(aligned),
}))
}
struct SubstraitPlanningContext<'a> {
state: &'a SessionState,
}
impl MatchRecognizePlanningContext for SubstraitPlanningContext<'_> {
fn options(&self) -> &datafusion_common::config::ConfigOptions {
self.state.config_options()
}
fn scalar_udf(&self, name: &str) -> Option<Arc<ScalarUDF>> {
self.state.udf(name).ok()
}
fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
self.state
.udaf(name)
.ok()
.or_else(|| self.options().aggregate_udf(name))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchRecognizeBoundary {
CompletePlan,
RowStreamNode,
OneRowNode,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DecodedSummaryAggregate {
pub function_name: String,
pub args: Vec<Expr>,
pub distinct: bool,
pub filter: Option<Expr>,
pub order_by: Vec<SortExpr>,
pub null_treatment: Option<expr::NullTreatment>,
}
#[derive(Clone, Debug)]
pub struct DecodedMatchRecognizeDetail {
pub spec: BoundMatchSpec,
pub capabilities: MatchRecognizePlanningCapabilities,
pub declares_match_aware_defines: bool,
pub output_schema: NamedStruct,
pub boundary: MatchRecognizeBoundary,
pub retained_passthrough_input_fields: Vec<Column>,
pub prepared_output_fields: Vec<(usize, Expr)>,
pub summary_output_fields: Vec<(usize, DecodedSummaryAggregate)>,
}
pub async fn decode_match_recognize_detail(
consumer: &impl SubstraitConsumer,
detail: &Any,
input_schema: &DFSchema,
) -> Result<DecodedMatchRecognizeDetail> {
let (payload, capabilities, boundary) = decode_match_recognize_payload(detail)?;
decode_match_recognize_detail_from_payload(
consumer,
payload,
capabilities,
boundary,
input_schema,
)
.await
}
fn decode_match_recognize_payload(
detail: &Any,
) -> Result<(
payload::MatchRecognizeRel,
MatchRecognizePlanningCapabilities,
MatchRecognizeBoundary,
)> {
if detail.type_url != MATCH_RECOGNIZE_TYPE_URL {
return plan_err!(
"unknown MATCH_RECOGNIZE detail type URL: {}",
detail.type_url
);
}
let payload = wire::decode_detail(detail.value.as_ref())?;
validate_schema_version(payload.schema_version)?;
let capabilities = decode_capabilities(&payload.required_features)?;
validate_payload_source_roles(&payload)?;
let boundary = decode_boundary(&payload)?;
Ok((payload, capabilities, boundary))
}
fn sanitize_semantic_node_input(
input: LogicalPlan,
symbols: &[String],
) -> Result<LogicalPlan> {
let pattern_symbols = symbols
.iter()
.map(|symbol| symbol.to_ascii_lowercase())
.collect::<BTreeSet<_>>();
let needs_sanitizing = input.schema().iter().any(|(qualifier, field)| {
field_needs_sanitizing(qualifier, field, &pattern_symbols)
});
if !needs_sanitizing {
return Ok(input);
}
let mut used_names = input
.schema()
.fields()
.iter()
.map(|field| field.name().to_ascii_lowercase())
.collect::<BTreeSet<_>>();
let mut exprs = Vec::with_capacity(input.schema().fields().len());
for (index, (qualifier, field)) in input.schema().iter().enumerate() {
let column = Expr::Column(Column::new(qualifier.cloned(), field.name()));
if field_needs_sanitizing(qualifier, field, &pattern_symbols) {
let mut candidate = format!("substrait_input_{index}");
let mut suffix = 0usize;
while !used_names.insert(candidate.to_ascii_lowercase()) {
candidate = format!("substrait_input_{index}_{suffix}");
suffix += 1;
}
exprs.push(column.alias(candidate));
} else {
exprs.push(column);
}
}
Ok(LogicalPlan::Projection(Projection::try_new(
exprs,
Arc::new(input),
)?))
}
fn field_needs_sanitizing(
qualifier: Option<&TableReference>,
field: &Field,
pattern_symbols: &BTreeSet<String>,
) -> bool {
is_reserved_internal_column_name(field.name())
|| qualifier.is_some_and(|relation| {
has_reserved_relation(relation)
|| pattern_symbols.contains(&relation.table().to_ascii_lowercase())
})
}
fn has_reserved_relation(relation: &TableReference) -> bool {
[
relation.catalog(),
relation.schema(),
Some(relation.table()),
]
.into_iter()
.flatten()
.any(is_reserved_internal_column_name)
}
async fn decode_match_recognize_detail_from_payload(
consumer: &impl SubstraitConsumer,
payload: payload::MatchRecognizeRel,
capabilities: MatchRecognizePlanningCapabilities,
boundary: MatchRecognizeBoundary,
input_schema: &DFSchema,
) -> Result<DecodedMatchRecognizeDetail> {
if boundary != MatchRecognizeBoundary::CompletePlan
&& !payload
.required_features
.iter()
.any(|feature| feature == DATAFUSION_WINDOW_MODIFIERS_FEATURE)
{
return plan_err!(
"semantic MATCH_RECOGNIZE Substrait payload missing required feature {}",
DATAFUSION_WINDOW_MODIFIERS_FEATURE
);
}
let declares_match_aware_defines = payload
.required_features
.iter()
.any(|feature| feature == MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE);
let mut seen = BTreeSet::new();
let retained_passthrough_input_fields = payload
.retained_passthrough_input_fields
.iter()
.map(|&index| {
if !seen.insert(index) {
return plan_err!(
"MATCH_RECOGNIZE retained_passthrough_input_fields contains duplicate input_field {}",
index
);
}
decode_input_field(input_schema, index)
})
.collect::<Result<Vec<_>>>()?;
let output_schema = payload.output_schema.ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE Substrait payload missing output_schema".to_string(),
)
})?;
let output_count = output_schema
.r#struct
.as_ref()
.map_or(0, |schema| schema.types.len());
let retained_prefix_len = retained_passthrough_input_fields.len();
if retained_prefix_len > output_count {
return plan_err!(
"MATCH_RECOGNIZE retained_passthrough_input_fields exceeds the output field count"
);
}
let prepared_output_fields = decode_prepared_output_fields(
consumer,
input_schema,
output_count,
retained_prefix_len,
&payload.prepared_output_fields,
)
.await?;
let pattern = decode_pattern(payload.pattern)?;
if has_reluctant_quantifier(&pattern)
&& !payload
.required_features
.iter()
.any(|feature| feature == MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE)
{
return plan_err!(
"MATCH_RECOGNIZE Substrait reluctant quantifier requires feature {}",
MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE
);
}
let spec = MatchRecognizeSpec {
partition_by: decode_exprs(consumer, input_schema, payload.partition_expressions)
.await?,
order_by: decode_source_sorts(consumer, input_schema, payload.sorts).await?,
source_rows_per_match: decode_rows_per_match(payload.rows_per_match)?,
after_match_skip: decode_after_match_skip(payload.after_match_skip)?,
pattern,
symbols: payload.symbols,
definitions: decode_definitions(consumer, input_schema, payload.definitions)
.await?,
measures: decode_measures(consumer, input_schema, payload.measures).await?,
output: decode_output_contract(consumer, input_schema, payload.output_contract)
.await?,
}
.try_new()
.map_err(|err| datafusion::common::DataFusionError::Plan(err.to_string()))?;
let (has_logical_offset, has_compound_navigation) = spec_navigation_features(&spec)?;
if has_logical_offset
&& !payload
.required_features
.iter()
.any(|feature| feature == MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE)
{
return plan_err!(
"MATCH_RECOGNIZE Substrait logical navigation offset requires feature {}",
MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE
);
}
if has_compound_navigation
&& !payload
.required_features
.iter()
.any(|feature| feature == MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE)
{
return plan_err!(
"MATCH_RECOGNIZE Substrait compound navigation requires feature {}",
MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE
);
}
let summary_output_fields = decode_summary_output_fields(
consumer,
input_schema,
&spec.symbols,
retained_prefix_len..output_count,
&prepared_output_fields,
&payload.summary_output_fields,
)
.await?;
Ok(DecodedMatchRecognizeDetail {
spec,
capabilities,
declares_match_aware_defines,
output_schema,
boundary,
retained_passthrough_input_fields,
prepared_output_fields,
summary_output_fields,
})
}
fn validate_define_declaration(
context: &mut impl MatchRecognizePlanningContext,
input: &LogicalPlan,
decoded: &DecodedMatchRecognizeDetail,
) -> Result<()> {
let requirements = analyze_match_recognize_requirements(
context,
input,
&decoded.spec,
decoded.capabilities,
)?;
if requirements.requires_match_aware_defines()
&& !decoded.declares_match_aware_defines
{
return plan_err!(
"MATCH_RECOGNIZE Substrait payload with match-aware DEFINEs is missing required feature {}",
MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE
);
}
Ok(())
}
async fn decode_prepared_output_fields(
consumer: &impl SubstraitConsumer,
input_schema: &DFSchema,
output_count: usize,
retained_prefix_len: usize,
fields: &[payload::PreparedOutputField],
) -> Result<Vec<(usize, Expr)>> {
let mut seen = BTreeSet::new();
let mut decoded = Vec::with_capacity(fields.len());
for field in fields {
let index = usize::try_from(field.output_field).map_err(|_| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE prepared output_field exceeds the addressable output"
.into(),
)
})?;
if index >= output_count {
return plan_err!(
"MATCH_RECOGNIZE prepared output_field {} is out of bounds for {} output fields",
index,
output_count
);
}
if index < retained_prefix_len {
return plan_err!(
"MATCH_RECOGNIZE prepared output_field {} overlaps the ordinary-source output prefix",
index
);
}
if !seen.insert(index) {
return plan_err!(
"MATCH_RECOGNIZE prepared_output_fields contains duplicate output_field {}",
index
);
}
let expression = field.expression.as_ref().ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE prepared output_field is missing expression".into(),
)
})?;
let expression = consumer
.consume_expression(expression, input_schema)
.await?;
if !matches!(expression, Expr::WindowFunction(_)) {
return plan_err!(
"MATCH_RECOGNIZE prepared output_field expression must be a window expression"
);
}
decoded.push((index, expression));
}
Ok(decoded)
}
async fn decode_summary_output_fields(
consumer: &impl SubstraitConsumer,
input_schema: &DFSchema,
symbols: &[String],
valid_outputs: Range<usize>,
prepared_output_fields: &[(usize, Expr)],
fields: &[payload::SummaryOutputField],
) -> Result<Vec<(usize, DecodedSummaryAggregate)>> {
if fields.is_empty() {
return Ok(Vec::new());
}
let summary_schema = summary_wire_decode_schema(input_schema, symbols)?;
let prepared_positions = prepared_output_fields
.iter()
.map(|(index, _)| *index)
.collect::<BTreeSet<_>>();
let mut seen = BTreeSet::new();
let mut decoded = Vec::with_capacity(fields.len());
for field in fields {
let index = usize::try_from(field.output_field).map_err(|_| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE summary output_field exceeds the addressable output"
.into(),
)
})?;
if index >= valid_outputs.end {
return plan_err!(
"MATCH_RECOGNIZE summary output_field {} is out of bounds for {} output fields",
index,
valid_outputs.end
);
}
if index < valid_outputs.start {
return plan_err!(
"MATCH_RECOGNIZE summary output_field {} overlaps the ordinary-source output prefix",
index
);
}
if prepared_positions.contains(&index) {
return plan_err!(
"MATCH_RECOGNIZE summary output_field {} overlaps prepared_output_fields",
index
);
}
if !seen.insert(index) {
return plan_err!(
"MATCH_RECOGNIZE summary_output_fields contains duplicate output_field {}",
index
);
}
if field.function_name.trim().is_empty() {
return plan_err!(
"MATCH_RECOGNIZE summary output_field {} is missing function_name",
index
);
}
let mut args = Vec::with_capacity(field.args.len());
for arg in &field.args {
args.push(consumer.consume_expression(arg, &summary_schema).await?);
}
let filter = match &field.filter {
Some(filter) => {
Some(consumer.consume_expression(filter, &summary_schema).await?)
}
None => None,
};
let mut order_by = Vec::with_capacity(field.order_by.len());
for sort in &field.order_by {
let expr = sort.expr.as_ref().ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE summary ORDER BY sort expression missing expr"
.into(),
)
})?;
let expr = consumer.consume_expression(expr, &summary_schema).await?;
let asc = matches!(
decode_sort_direction(sort.direction, "summary ORDER BY")?,
MatchRecognizeSortDirection::Asc
);
let nulls_first = matches!(
decode_null_ordering(sort.null_ordering, "summary ORDER BY")?,
MatchRecognizeNullOrdering::First
);
order_by.push(SortExpr::new(expr, asc, nulls_first));
}
let null_treatment = decode_null_treatment(field.null_treatment)?;
decoded.push((
index,
DecodedSummaryAggregate {
function_name: field.function_name.clone(),
args,
distinct: field.distinct,
filter,
order_by,
null_treatment,
},
));
}
Ok(decoded)
}
fn summary_wire_decode_schema(
input_schema: &DFSchema,
symbols: &[String],
) -> Result<DFSchemaRef> {
let input_schema_ref = Arc::new(input_schema.clone());
MatchRecognizeOutputSpec::full_from(&input_schema_ref, symbols)
.build_df_schema(input_schema)
}
fn normalize_decoded_summary(
summary: &DecodedSummaryAggregate,
summary_schema: &DFSchema,
source_len: usize,
symbols: &[String],
) -> Result<DecodedSummaryAggregate> {
let normalize = |expr: &Expr| {
normalize_summary_expr(expr.clone(), summary_schema, source_len, symbols)
};
Ok(DecodedSummaryAggregate {
function_name: summary.function_name.clone(),
args: summary
.args
.iter()
.map(normalize)
.collect::<Result<Vec<_>>>()?,
distinct: summary.distinct,
filter: summary.filter.as_ref().map(normalize).transpose()?,
order_by: summary
.order_by
.iter()
.map(|sort| {
Ok(SortExpr::new(
normalize(&sort.expr)?,
sort.asc,
sort.nulls_first,
))
})
.collect::<Result<Vec<_>>>()?,
null_treatment: summary.null_treatment,
})
}
fn planned_summary_identity(
summary: &LogicalSelectedMatchSummary,
node: &MatchRecognize,
source_schema: &DFSchema,
summary_schema: &DFSchema,
symbols: &[String],
) -> Result<DecodedSummaryAggregate> {
let source_len = source_schema.fields().len();
let normalize = |expr: &Expr| -> Result<Expr> {
let expanded =
producer::expand_prepared_source_exprs(expr.clone(), node, source_schema)?;
normalize_summary_expr(expanded, summary_schema, source_len, symbols)
};
let aggregate = summary.aggregate();
let params = &aggregate.params;
Ok(DecodedSummaryAggregate {
function_name: aggregate.func.name().to_string(),
args: params
.args
.iter()
.map(normalize)
.collect::<Result<Vec<_>>>()?,
distinct: params.distinct,
filter: params.filter.as_deref().map(normalize).transpose()?,
order_by: params
.order_by
.iter()
.map(|sort| {
Ok(SortExpr::new(
normalize(&sort.expr)?,
sort.asc,
sort.nulls_first,
))
})
.collect::<Result<Vec<_>>>()?,
null_treatment: params.null_treatment,
})
}
fn typed_null_identity(data_type: &DataType) -> Result<Expr> {
match ScalarValue::try_from(data_type)? {
ScalarValue::Date64(value) => Ok(Expr::Cast(expr::Cast::new(
Box::new(Expr::Literal(ScalarValue::Int64(value), None)),
DataType::Date64,
))),
value => Ok(Expr::Literal(value, None)),
}
}
fn is_date64_millis_cast(expr: &Expr) -> bool {
matches!(
expr,
Expr::Cast(cast)
if matches!(cast.expr.as_ref(), Expr::Literal(ScalarValue::Int64(_), _))
&& cast.field.as_ref() == &Field::new("", DataType::Date64, true)
)
}
fn is_wire_rewritten_inert_when(expr: &Expr) -> bool {
matches!(expr, Expr::Literal(value, _) if value.is_null())
|| is_date64_millis_cast(expr)
}
fn strip_wire_ambiguous_null_base_guard(
mut case: expr::Case,
schema: &DFSchema,
) -> Result<(expr::Case, bool)> {
if case.expr.is_some() || case.when_then_expr.len() < 2 {
return Ok((case, false));
}
let (Expr::IsNull(base), guard_then) = (
case.when_then_expr[0].0.as_ref(),
case.when_then_expr[0].1.as_ref(),
) else {
return Ok((case, false));
};
if base.is_volatile() || !base.nullable(schema)? {
return Ok((case, false));
}
let expected_guard_then = match &case.else_expr {
Some(else_expr) => else_expr.as_ref().clone(),
None => {
let result_type = case.when_then_expr[1].1.get_type(schema)?;
typed_null_identity(&result_type)?
}
};
if guard_then != &expected_guard_then {
return Ok((case, false));
}
let mut has_wire_rewritten = false;
for (when, _) in &case.when_then_expr[1..] {
let Expr::BinaryExpr(binary) = when.as_ref() else {
return Ok((case, false));
};
if binary.op != Operator::Eq || binary.left.as_ref() != base.as_ref() {
return Ok((case, false));
}
let right = binary.right.as_ref();
if is_wire_rewritten_inert_when(right) {
has_wire_rewritten = true;
} else if !matches!(right, Expr::Literal(..) | Expr::Column(_)) {
return Ok((case, false));
}
}
if !has_wire_rewritten {
return Ok((case, false));
}
case.when_then_expr.remove(0);
Ok((case, true))
}
pub(crate) fn normalize_summary_expr(
expression: Expr,
summary_schema: &DFSchema,
source_len: usize,
symbols: &[String],
) -> Result<Expr> {
let metadata = MatchMetadataColumn::public_output();
let classifier_start = source_len + metadata.len();
normalize_wire_expr(expression, summary_schema, |column| {
if column.relation.is_none()
&& let Some(offset) = metadata
.iter()
.position(|meta| meta.as_ref() == column.name.as_str())
{
let (qualifier, field) = summary_schema.qualified_field(source_len + offset);
Column::new(qualifier.cloned(), field.name())
} else if column.relation.is_none()
&& let Some(offset) = symbols
.iter()
.position(|symbol| classifier_bits_col_name(symbol) == column.name)
{
let (qualifier, field) =
summary_schema.qualified_field(classifier_start + offset);
Column::new(qualifier.cloned(), field.name())
} else if let Ok(index) = summary_schema.index_of_column(column) {
let (qualifier, field) = summary_schema.qualified_field(index);
Column::new(qualifier.cloned(), field.name())
} else {
column.clone()
}
})
}
fn normalize_prepared_window_expr(
expression: Expr,
source_schema: &DFSchema,
) -> Result<Expr> {
normalize_wire_expr(expression, source_schema, |column| {
if let Ok(index) = source_schema.index_of_column(column) {
let (qualifier, field) = source_schema.qualified_field(index);
Column::new(qualifier.cloned(), field.name())
} else {
column.clone()
}
})
}
fn normalize_wire_expr(
expression: Expr,
schema: &DFSchema,
resolve_column: impl Fn(&Column) -> Column,
) -> Result<Expr> {
let expression = expression
.transform_down(|expr| {
let Expr::Case(case) = expr else {
return Ok(Transformed::no(expr));
};
if !case.expr.as_deref().is_some_and(|base| !base.is_volatile()) {
return Ok(Transformed::no(Expr::Case(case)));
}
let base = case.expr.expect("checked Some above");
let when_operand_is_inert = |(when, _): &(Box<Expr>, Box<Expr>)| {
matches!(when.as_ref(), Expr::Literal(..) | Expr::Column(_))
};
let null_base_guard = !case.when_then_expr.iter().all(when_operand_is_inert)
&& base.nullable(schema)?;
let mut when_then_expr = Vec::with_capacity(
case.when_then_expr.len() + usize::from(null_base_guard),
);
if null_base_guard {
let then = match &case.else_expr {
Some(else_expr) => else_expr.as_ref().clone(),
None => match case.when_then_expr.first() {
Some((_, then)) => {
let result_type = then.get_type(schema)?;
typed_null_identity(&result_type)?
}
None => {
return Ok(Transformed::no(Expr::Case(expr::Case {
expr: Some(base),
when_then_expr: case.when_then_expr,
else_expr: case.else_expr,
})));
}
},
};
when_then_expr
.push((Box::new(base.as_ref().clone().is_null()), Box::new(then)));
}
for (when, then) in case.when_then_expr {
when_then_expr
.push((Box::new(Expr::eq(base.as_ref().clone(), *when)), then));
}
Ok(Transformed::yes(Expr::Case(expr::Case {
expr: None,
when_then_expr,
else_expr: case.else_expr,
})))
})?
.data;
Ok(expression
.transform_up(|expr| {
let mut changed = false;
let expr = match expr {
Expr::Alias(alias) => {
changed = true;
*alias.expr
}
Expr::Literal(value, Some(_)) => {
changed = true;
Expr::Literal(value, None)
}
other => other,
};
match expr {
Expr::WindowFunction(mut window) => {
for bound in [
&mut window.params.window_frame.start_bound,
&mut window.params.window_frame.end_bound,
] {
if let WindowFrameBound::Preceding(value)
| WindowFrameBound::Following(value) = bound
&& value.is_null()
&& *value != ScalarValue::Null
{
*value = ScalarValue::Null;
changed = true;
}
}
Ok(if changed {
Transformed::yes(Expr::WindowFunction(window))
} else {
Transformed::no(Expr::WindowFunction(window))
})
}
Expr::Column(column) => {
let resolved = resolve_column(&column);
Ok(if resolved != column {
Transformed::yes(Expr::Column(resolved))
} else if changed {
Transformed::yes(Expr::Column(column))
} else {
Transformed::no(Expr::Column(column))
})
}
Expr::Cast(cast)
if matches!(
cast.expr.as_ref(),
Expr::Literal(ScalarValue::Null, _)
) && cast.field.as_ref()
== &Field::new("", cast.field.data_type().clone(), true) =>
{
Ok(Transformed::yes(typed_null_identity(
cast.field.data_type(),
)?))
}
Expr::Literal(ScalarValue::Date64(value), _) => {
Ok(Transformed::yes(Expr::Cast(expr::Cast::new(
Box::new(Expr::Literal(ScalarValue::Int64(value), None)),
DataType::Date64,
))))
}
Expr::Between(between) => {
let expr = *between.expr;
let desugared = if between.negated {
Expr::or(
Expr::lt(expr.clone(), *between.low),
Expr::lt(*between.high, expr),
)
} else {
Expr::and(
Expr::lt_eq(*between.low, expr.clone()),
Expr::lt_eq(expr, *between.high),
)
};
Ok(Transformed::yes(desugared))
}
Expr::InList(mut in_list) if in_list.negated => {
in_list.negated = false;
Ok(Transformed::yes(Expr::Not(Box::new(Expr::InList(in_list)))))
}
Expr::Like(mut like) if like.negated => {
like.negated = false;
Ok(Transformed::yes(Expr::Not(Box::new(Expr::Like(like)))))
}
Expr::Case(case) if case.expr.is_none() => {
let (case, stripped) =
strip_wire_ambiguous_null_base_guard(case, schema)?;
Ok(if stripped || changed {
Transformed::yes(Expr::Case(case))
} else {
Transformed::no(Expr::Case(case))
})
}
other => Ok(if changed {
Transformed::yes(other)
} else {
Transformed::no(other)
}),
}
})?
.data)
}
fn folded_required_count_identity(
identity: &DecodedSummaryAggregate,
source_input: &LogicalPlan,
symbols: &[String],
) -> Option<DecodedSummaryAggregate> {
if identity.function_name != count_udaf().name()
|| identity.distinct
|| identity.null_treatment.is_some()
|| !identity.order_by.is_empty()
{
return None;
}
let [Expr::Column(column)] = identity.args.as_slice() else {
return None;
};
let source_schema = source_input.schema();
let index = source_schema.maybe_index_of_column(column)?;
let field = source_schema.field(index);
if is_reserved_internal_column_name(field.name())
|| field.is_nullable()
|| can_have_nulls_outside_bitmap(field.data_type())
|| !is_stored_source_column(source_input, index)
{
return None;
}
let filter = identity.filter.as_ref()?;
if !is_assigned_classifier_filter(filter, symbols) {
return None;
}
Some(DecodedSummaryAggregate {
function_name: identity.function_name.clone(),
args: vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)],
distinct: false,
filter: Some(filter.clone()),
order_by: Vec::new(),
null_treatment: None,
})
}
fn is_assigned_classifier_filter(filter: &Expr, symbols: &[String]) -> bool {
match filter {
Expr::IsNotNull(inner) => matches!(
inner.as_ref(),
Expr::Column(column)
if column.relation.is_none()
&& column.name == MatchMetadataColumn::Classifier.as_ref()
),
Expr::Column(column) => {
column.relation.is_none()
&& symbols
.iter()
.any(|symbol| classifier_bits_col_name(symbol) == column.name)
}
_ => false,
}
}
fn is_stored_source_column(mut input: &LogicalPlan, mut col_index: usize) -> bool {
loop {
match input {
LogicalPlan::SubqueryAlias(alias) => input = &alias.input,
LogicalPlan::Filter(filter) => input = &filter.input,
LogicalPlan::Projection(projection) => {
let Some(mut expr) = projection.expr.get(col_index) else {
return false;
};
while let Expr::Alias(alias) = expr {
expr = alias.expr.as_ref();
}
let Expr::Column(column) = expr else {
return false;
};
let Some(next_index) =
projection.input.schema().maybe_index_of_column(column)
else {
return false;
};
input = &projection.input;
col_index = next_index;
}
LogicalPlan::TableScan(scan) => {
return scan.source.table_type() == TableType::Base
&& scan.source.get_logical_plan().is_none();
}
_ => return false,
}
}
}
fn decode_boundary(
payload: &payload::MatchRecognizeRel,
) -> Result<MatchRecognizeBoundary> {
let finalizes_one_row = payload
.required_features
.iter()
.any(|feature| feature == DATAFUSION_SEMANTIC_ONE_ROW_FEATURE);
if payload.semantic_node_finalizes_one_row != finalizes_one_row {
return plan_err!(
"MATCH_RECOGNIZE Substrait semantic_node_finalizes_one_row must agree with required feature {}",
DATAFUSION_SEMANTIC_ONE_ROW_FEATURE
);
}
match (
payload.semantic_node,
payload.semantic_node_finalizes_one_row,
) {
(false, false) => Ok(MatchRecognizeBoundary::CompletePlan),
(true, false) => Ok(MatchRecognizeBoundary::RowStreamNode),
(true, true) => Ok(MatchRecognizeBoundary::OneRowNode),
(false, true) => plan_err!(
"MATCH_RECOGNIZE Substrait native ONE ROW finalization requires semantic_node=true"
),
}
}
pub(super) fn validate_schema_version(schema_version: Option<u32>) -> Result<()> {
let Some(schema_version) = schema_version else {
return plan_err!("MATCH_RECOGNIZE Substrait payload missing schema_version");
};
if schema_version == MATCH_RECOGNIZE_SCHEMA_VERSION {
return Ok(());
}
plan_err!(
"unsupported MATCH_RECOGNIZE Substrait payload schema_version {}; expected {}",
schema_version,
MATCH_RECOGNIZE_SCHEMA_VERSION
)
}
pub(super) fn decode_capabilities(
features: &[String],
) -> Result<MatchRecognizePlanningCapabilities> {
let features = features.iter().map(String::as_str).collect::<BTreeSet<_>>();
if !features.contains(MATCH_RECOGNIZE_EXTENSION_FEATURE) {
return plan_err!(
"MATCH_RECOGNIZE Substrait payload missing required feature {}",
MATCH_RECOGNIZE_EXTENSION_FEATURE
);
}
if !features.contains(MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE) {
return plan_err!(
"MATCH_RECOGNIZE Substrait payload missing required feature {}",
MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE
);
}
for &feature in &features {
match feature {
MATCH_RECOGNIZE_EXTENSION_FEATURE
| MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE
| MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE
| MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE
| MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE
| MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE
| DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE
| DATAFUSION_EXCLUDED_FEATURE
| DATAFUSION_WINDOW_MODIFIERS_FEATURE
| DATAFUSION_SEMANTIC_ONE_ROW_FEATURE => {}
_ => {
return plan_err!(
"unknown MATCH_RECOGNIZE Substrait required feature {}",
feature
);
}
}
}
Ok(MatchRecognizePlanningCapabilities::restricted(
features.contains(DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE),
features.contains(DATAFUSION_EXCLUDED_FEATURE),
))
}
pub(super) fn decode_input_field(input_schema: &DFSchema, index: u32) -> Result<Column> {
let index = usize::try_from(index).map_err(|_| {
datafusion::common::DataFusionError::Plan(
"MATCH_RECOGNIZE Substrait input_field exceeds the addressable input".into(),
)
})?;
if index >= input_schema.fields().len() {
return plan_err!(
"MATCH_RECOGNIZE Substrait input_field {} is out of bounds for {} input fields",
index,
input_schema.fields().len()
);
}
let (qualifier, field) = input_schema.qualified_field(index);
let column = Column::new(qualifier.cloned(), field.name());
let identities = input_schema
.iter()
.filter(|(candidate_qualifier, candidate)| {
*candidate_qualifier == qualifier && candidate.name() == field.name()
})
.count();
if identities != 1 || input_schema.index_of_column(&column)? != index {
return plan_err!(
"MATCH_RECOGNIZE Substrait input_field {} does not identify an unambiguous input column",
index
);
}
Ok(column)
}