Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
252 changes: 232 additions & 20 deletions datafusion/optimizer/src/extract_leaf_expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ use std::sync::Arc;
use datafusion_common::alias::AliasGenerator;
use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion_common::{Column, DFSchema, Result, qualified_name};
use datafusion_expr::expr::Alias;
use datafusion_expr::logical_plan::LogicalPlan;
use datafusion_expr::{Expr, ExpressionPlacement, Projection};

Expand All @@ -71,12 +72,42 @@ use crate::{OptimizerConfig, OptimizerRule};

/// Prefix for aliases generated by the extraction optimizer passes.
///
/// This prefix is **reserved for internal optimizer use**. User-defined aliases
/// starting with this prefix may be misidentified as optimizer-generated
/// extraction aliases, leading to unexpected behavior. Do not use this prefix
/// in user queries.
/// Aliases starting with this prefix are classified as extraction aliases when
/// their inner expression is eligible for leaf pushdown
/// ([`ExpressionPlacement::should_push_to_leaves`]). Numeric suffixes below
/// `usize::MAX` are parsed solely to seed [`AliasGenerator`]; user aliases with
/// this prefix that wrap pushable expressions may still be treated as
/// extraction aliases.
const EXTRACTED_EXPR_PREFIX: &str = "__datafusion_extracted";

/// Parses numeric IDs (`0..usize::MAX`) for seeding [`AliasGenerator`] in
/// [`advance_generator_past_existing`].
///
/// Extraction alias classification uses [`is_extracted_alias`] instead so
/// generated `usize::MAX` (and wrapped `0`) aliases are accepted while
/// non-pushable user aliases with numeric suffixes are rejected.
fn extracted_expr_id(name: &str) -> Option<usize> {
let id = name
.strip_prefix(EXTRACTED_EXPR_PREFIX)?
.strip_prefix('_')?
.parse::<usize>()
.ok()?;
// update_min_id adds one, so the maximum value has no usable successor.
(id < usize::MAX).then_some(id)
Comment thread
mattsu2020 marked this conversation as resolved.
Resolved
Comment thread
mattsu2020 marked this conversation as resolved.
Resolved
}

/// Returns `true` if `alias` carries the extraction prefix and wraps an
/// expression eligible for leaf pushdown (`MoveTowardsLeafNodes` or `Column`).
///
/// Checking expression placement prevents user-defined aliases with canonical
/// names (such as `10 / id AS __datafusion_extracted_1`) from being hoisted
/// below filters, while accepting optimizer-generated aliases regardless of
/// counter wraparound at `usize::MAX`.
fn is_extracted_alias(alias: &Alias) -> bool {
alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
&& alias.expr.placement().should_push_to_leaves()
}

/// Returns `true` if any sub-expression in `exprs` has
/// [`ExpressionPlacement::MoveTowardsLeafNodes`] placement.
///
Expand Down Expand Up @@ -235,11 +266,7 @@ fn advance_generator_past_existing(
plan.apply_expressions(|expr| {
expr.apply(|e| {
if let Expr::Alias(alias) = e
&& let Some(id) = alias
.name
.strip_prefix(EXTRACTED_EXPR_PREFIX)
.and_then(|s| s.strip_prefix('_'))
.and_then(|s| s.parse().ok())
&& let Some(id) = extracted_expr_id(&alias.name)
{
alias_generator.update_min_id(id);
}
Expand Down Expand Up @@ -393,9 +420,9 @@ fn routing_extract(
input_column_sets: &[std::collections::HashSet<ColumnReference>],
) -> Result<Transformed<Expr>> {
expr.transform_down(|e| {
// Skip expressions already aliased with extracted expression pattern
// Skip expressions already aliased as extraction expressions.
if let Expr::Alias(alias) = &e
&& alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
&& is_extracted_alias(alias)
{
return Ok(Transformed {
data: e,
Expand Down Expand Up @@ -712,7 +739,7 @@ fn build_extraction_projection_impl(
.iter()
.filter_map(|e| {
if let Expr::Alias(alias) = e
&& alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
&& is_extracted_alias(alias)
{
return Some((*alias.expr.clone(), alias.name.clone()));
}
Expand Down Expand Up @@ -1005,9 +1032,10 @@ fn split_and_push_projection(
) -> Result<Option<LogicalPlan>> {
// Fast pre-check: skip if there are no pre-existing extracted aliases
// and no new extractable expressions.
let has_existing_extracted = proj.expr.iter().any(|e| {
matches!(e, Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX))
});
let has_existing_extracted = proj
.expr
.iter()
.any(|e| matches!(e, Expr::Alias(alias) if is_extracted_alias(alias)));
if !has_existing_extracted && !has_extractable_expr(&proj.expr) {
return Ok(None);
}
Expand Down Expand Up @@ -1049,7 +1077,7 @@ fn split_and_push_projection(
recovery_exprs.push(expr.clone());
proj_exprs_captured += 1;
} else if let Expr::Alias(alias) = expr
&& alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
&& is_extracted_alias(alias)
Comment thread
mattsu2020 marked this conversation as resolved.
Resolved
{
// Insert the full Alias expression as the key so that
// distinct alias names don't collide in the IndexMap.
Expand Down Expand Up @@ -1238,8 +1266,15 @@ fn split_and_push_projection(
}

/// Returns true if `exprs` are the expressions of a *pure extraction
/// projection*: every expression is either `Alias(EXTRACTED_EXPR_PREFIX, ...)`
/// or a bare `Column`, and there is at least one extraction alias.
/// projection*: every expression is either an extraction alias (matching
/// [`EXTRACTED_EXPR_PREFIX`] with a pushdown-eligible inner expression via
/// [`ExpressionPlacement::should_push_to_leaves`]) or a bare `Column`, and
/// there is at least one extraction alias.
///
/// Numeric suffix validation is reserved for generator seeding in
/// [`advance_generator_past_existing`]; classification relies on prefix and
/// expression placement so generated `usize::MAX` (and wrapped `0`) aliases
/// are accepted while non-pushable user aliases are rejected.
///
/// Such projections can safely be pushed further without re-extraction.
///
Expand All @@ -1250,7 +1285,7 @@ pub(crate) fn is_pure_extraction_projection(exprs: &[Expr]) -> bool {
let mut has_extraction = false;
for expr in exprs {
match expr {
Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX) => {
Expr::Alias(alias) if is_extracted_alias(alias) => {
has_extraction = true;
}
Expr::Column(_) => {}
Expand Down Expand Up @@ -3778,6 +3813,135 @@ mod tests {
Ok(())
}

#[test]
fn test_extracted_expr_id_boundaries() {
for id in [0, 1, 42, usize::MAX - 1] {
let name = format!("{EXTRACTED_EXPR_PREFIX}_{id}");
assert_eq!(extracted_expr_id(&name), Some(id), "{name}");
}
for (suffix, expected) in [("01", 1), ("0001", 1), ("+1", 1)] {
let name = format!("{EXTRACTED_EXPR_PREFIX}_{suffix}");
assert_eq!(extracted_expr_id(&name), Some(expected), "{name}");
}

assert_eq!(extracted_expr_id(EXTRACTED_EXPR_PREFIX), None);
let invalid_suffixes = ["", "-1", "1x", " 1", "1 ", "1"].map(str::to_owned);
for suffix in invalid_suffixes
.into_iter()
.chain([usize::MAX.to_string(), format!("{}0", usize::MAX)])
{
let name = format!("{EXTRACTED_EXPR_PREFIX}_{suffix}");
assert_eq!(extracted_expr_id(&name), None, "{name}");
}
}

#[test]
fn test_advance_generator_ignores_invalid_extraction_ids() -> Result<()> {
let exprs = [
"0".to_owned(),
"-1".to_owned(),
"1x".to_owned(),
usize::MAX.to_string(),
format!("{}0", usize::MAX),
]
.into_iter()
.map(|suffix| lit(1).alias(format!("{EXTRACTED_EXPR_PREFIX}_{suffix}")))
.collect::<Vec<_>>();
let plan = LogicalPlanBuilder::from(test_table_scan_with_struct()?)
.project(exprs)?
.build()?;
let alias_generator = AliasGenerator::new();
advance_generator_past_existing(&plan, &alias_generator)?;
assert_eq!(
alias_generator.next(EXTRACTED_EXPR_PREFIX),
"__datafusion_extracted_1"
);
Ok(())
}

#[test]
fn test_advance_generator_seeds_leading_zero_and_plus_ids() -> Result<()> {
for suffix in ["01", "+1"] {
let plan = LogicalPlanBuilder::from(test_table_scan_with_struct()?)
.project(vec![
lit(99).alias(format!("{EXTRACTED_EXPR_PREFIX}_{suffix}")),
])?
.build()?;
let alias_generator = AliasGenerator::new();
advance_generator_past_existing(&plan, &alias_generator)?;
assert_eq!(
alias_generator.next(EXTRACTED_EXPR_PREFIX),
"__datafusion_extracted_2",
"suffix={suffix}"
);
}
Ok(())
}

fn inexact_table_scan_with_struct() -> Result<LogicalPlan> {
#[derive(Debug)]
struct InexactStructTable(arrow::datatypes::SchemaRef);

impl datafusion_expr::TableSource for InexactStructTable {
fn schema(&self) -> arrow::datatypes::SchemaRef {
Arc::clone(&self.0)
}
fn table_type(&self) -> datafusion_expr::TableType {
datafusion_expr::TableType::Base
}
fn supports_filters_pushdown(
&self,
filters: &[&Expr],
) -> Result<Vec<datafusion_expr::TableProviderFilterPushDown>> {
Ok(vec![
datafusion_expr::TableProviderFilterPushDown::Inexact;
filters.len()
])
}
}

let schema = Arc::new(arrow::datatypes::Schema::new(
test_table_scan_with_struct_fields(),
));
LogicalPlanBuilder::scan("test", Arc::new(InexactStructTable(schema)), None)?
.build()
}

#[test]
fn test_canonical_user_alias_not_pushed_below_filter() -> Result<()> {
let table_scan = inexact_table_scan_with_struct()?;
let guarded_div = datafusion_expr::binary_expr(
lit(10u32),
datafusion_expr::Operator::Divide,
col("id"),
)
.alias(format!("{EXTRACTED_EXPR_PREFIX}_1"));
let plan = LogicalPlanBuilder::from(table_scan)
.filter(
col("id")
.gt(lit(0u32))
.and(leaf_udf(col("user"), "status").eq(lit("active"))),
)?
.project(vec![guarded_div])?
.build()?;

let ctx = OptimizerContext::new();
let optimizer = Optimizer::with_rules(vec![
Arc::new(crate::push_down_filter::PushDownFilter::new()),
Arc::new(ExtractLeafExpressions::new()),
Arc::new(PushDownLeafProjections::new()),
Arc::new(OptimizeProjections::new()),
]);
let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;
insta::assert_snapshot!(format!("{optimized}"), @r#"
Projection: UInt32(10) / test.id AS __datafusion_extracted_1
Filter: test.id > UInt32(0) AND __datafusion_extracted_2 = Utf8("active")
Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id
TableScan: test projection=[id, user], partial_filters=[test.id > UInt32(0), leaf_udf(test.user, Utf8("status")) = Utf8("active")]
"#);
Ok(())
}

/// Pre-existing `__datafusion_extracted_N` aliases must advance the alias
/// generator even when they live inside a subquery plan, since extraction
/// descends into subqueries and would otherwise reuse the same alias.
Expand Down Expand Up @@ -3969,11 +4133,59 @@ mod tests {
assert!(!is_pure_extraction_projection(&common_expr.expressions()));

// A bare expression is never allowed.
let bare_expr = LogicalPlanBuilder::from(scan)
let bare_expr = LogicalPlanBuilder::from(scan.clone())
.project(vec![leaf_udf(col("user"), "status"), col("id")])?
.build()?;
assert!(!is_pure_extraction_projection(&bare_expr.expressions()));

// Generated boundary IDs (usize::MAX and wrapped 0) remain valid when
// wrapping a pushdown-eligible expression.
let max_id_expr = LogicalPlanBuilder::from(scan.clone())
.project(vec![
leaf_udf(col("user"), "status")
.alias(format!("{EXTRACTED_EXPR_PREFIX}_{}", usize::MAX)),
col("id"),
])?
.build()?;
assert!(is_pure_extraction_projection(&max_id_expr.expressions()));

let zero_id_expr = LogicalPlanBuilder::from(scan.clone())
.project(vec![
leaf_udf(col("user"), "status")
.alias(format!("{EXTRACTED_EXPR_PREFIX}_0")),
col("id"),
])?
.build()?;
assert!(is_pure_extraction_projection(&zero_id_expr.expressions()));

// Column-backed extraction aliases (e.g. after CSE or SubqueryAlias)
// are pushdown-eligible too.
let column_alias = LogicalPlanBuilder::from(scan.clone())
.project(vec![
col("user").alias(format!("{EXTRACTED_EXPR_PREFIX}_1")),
col("id"),
])?
.build()?;
assert!(is_pure_extraction_projection(&column_alias.expressions()));

// Canonical user aliases wrapping KeepInPlace or Literal expressions
// must not be classified as extraction aliases.
let non_pushable = LogicalPlanBuilder::from(scan.clone())
.project(vec![
(col("id") + lit(1u32)).alias(format!("{EXTRACTED_EXPR_PREFIX}_1")),
col("id"),
])?
.build()?;
assert!(!is_pure_extraction_projection(&non_pushable.expressions()));

let literal_alias = LogicalPlanBuilder::from(scan)
.project(vec![
lit(1u32).alias(format!("{EXTRACTED_EXPR_PREFIX}_1")),
col("id"),
])?
.build()?;
assert!(!is_pure_extraction_projection(&literal_alias.expressions()));

Ok(())
}

Expand Down
Loading