Skip to content

fix: classify leaf extraction aliases by placement - #26969

Open
mattsu2020 wants to merge 3 commits into
apache:mainfrom
mattsu2020:fix/leaf-extraction-alias-format
Open

mattsu2020 wants to merge 3 commits into
apache:mainfrom
mattsu2020:fix/leaf-extraction-alias-format

Conversation

@mattsu2020

@mattsu2020 mattsu2020 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Partially addresses #25449; this does not close it. This is a narrower follow-up to closed #26769; the typed-marker design remains open, and name-collision handling for the reserved __datafusion_extracted prefix is deferred to a separate discussion/follow-up.

Rationale for this change

Any alias starting with __datafusion_extracted is currently treated as an optimizer-generated extraction alias regardless of expression placement:

  1. A user alias such as __datafusion_extracted_manual or __datafusion_extracted_1 on a non-pushable expression can cause the optimizer to move it below a filter. For example, this query fails with division by zero even though the filter excludes zero:

    CREATE TABLE t AS SELECT * FROM (VALUES (0), (1)) AS v(id);
    SELECT 10 / id AS __datafusion_extracted_manual FROM t WHERE id > 0;

    With this change it returns 10, as do queries using bare __datafusion_extracted, _0, _01, _1, _1x, and _+1 suffixes.

  2. Invalid or boundary suffixes (_0, _01, _+1, usize::MAX) should not advance or overflow AliasGenerator in advance_generator_past_existing.

What changes are included in this PR?

  • Classify extraction aliases by placement (is_extracted_alias): Treat an alias starting with __datafusion_extracted (EXTRACTED_EXPR_PREFIX) as an extraction alias only when its inner expression is eligible for leaf pushdown (ExpressionPlacement::should_push_to_leaves). Update all classification sites (routing_extract, build_extraction_projection_impl, split_and_push_projection, and is_pure_extraction_projection) and helper documentation accordingly.
  • Validate canonical IDs for generator seeding (extracted_expr_id): Restrict extracted_expr_id to canonical positive decimal IDs in 1..usize::MAX without leading zeros or signs so invalid suffixes or usize::MAX do not advance or overflow AliasGenerator in advance_generator_past_existing.

What is the testing strategy for this PR?

  • datafusion/sqllogictest/test_files/projection_pushdown.slt:
    • Covers 10 / id guarded by id > 0 with bare __datafusion_extracted and suffixes _manual, _1x, _+1, _0, _01, and _1.
    • Combines id > 0 with s['a'] = 1 in extracted_alias_names_struct (verifying both EXPLAIN plan structure and query results) so leaf extraction pushes get_field(s, 'a') while keeping division above the filter.
  • Rust unit tests in datafusion/optimizer/src/extract_leaf_expressions.rs:
    • test_extracted_expr_id_boundaries and test_advance_generator_ignores_invalid_extraction_ids cover leading zeros, signs, non-ASCII digits, usize::MAX, and out-of-range suffixes.
    • test_canonical_user_alias_not_pushed_below_filter and new cases in test_is_pure_extraction_projection (usize::MAX, 0, Column, KeepInPlace, Literal) verify placement-based classification.
  • Local verification: cargo fmt --all -- --check, cargo clippy -p datafusion-optimizer --all-targets --all-features --no-deps -- -D warnings, cargo test -p datafusion-optimizer extract_leaf_expressions, and cargo test --test sqllogictests -- projection_pushdown passed.

Are there any user-facing changes?

User aliases sharing the __datafusion_extracted prefix (including canonical names like __datafusion_extracted_1) no longer cause non-pushable expressions to be treated as internal extractions. Public Rust APIs and protobuf formats are unchanged.

User-defined aliases with the __datafusion_extracted prefix that wrap pushable expressions can still be classified as extraction aliases (and may collide with existing names); full disambiguation and collision handling are left to #25449 or a separate follow-up.

This PR was prepared with AI assistance.

@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Oct 31, 2026
@mattsu2020 mattsu2020 changed the title fix: require numeric suffixes for leaf extraction aliases fix: validate leaf extraction alias suffixes Oct 31, 2026
@mattsu2020
mattsu2020 marked this pull request as ready for review October 31, 2026 11:07
@mattsu2020

Copy link
Copy Markdown
Contributor Author

I also reviewed the AI-generated code myself.

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattsu2020, thanks for centralizing extraction-alias recognition. The approach fixes the reported misclassification and adds useful regression coverage.

However, the allocator can still generate aliases rejected by the new validator, causing a reproducible optimizer failure. Please address this before merging.

@mattsu2020
mattsu2020 force-pushed the fix/leaf-extraction-alias-format branch from 5cdcb2c to 837c515 Compare November 21, 2026 08:16
@mattsu2020
mattsu2020 requested a review from kosiew November 21, 2026 08:16

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattsu2020, thanks for the follow-up. The suffix parser correctly protects alias counter seeding, but it is insufficient for identifying extracted expressions.

I'm requesting changes because canonical user aliases can still bypass filter guards, while generated aliases near the counter limit can cause schema ambiguity. Classification should depend on expression pushdown eligibility, not numeric suffix validity.


/// Returns true if `exprs` are the expressions of a *pure extraction
/// projection*: every expression is either `Alias(EXTRACTED_EXPR_PREFIX, ...)`
/// projection*: every expression is either an alias named `__datafusion_extracted_<number>`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please update the rustdoc to describe prefix and expression-based classification rather than canonical numeric suffixes. Reserve numeric suffix validation for generator seeding.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed it

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattsu2020,

Thanks for addressing the previous findings. Separating expression placement from counter seeding is the right approach.

One alias collision still causes valid SQL to fail. Please fix this case, add a regression test, and update the PR description to reflect the current implementation.

@mattsu2020
mattsu2020 force-pushed the fix/leaf-extraction-alias-format branch from b98c6bc to 2ab85f3 Compare November 26, 2026 22:27
Require extracted alias suffixes parsed by `advance_generator_past_existing`
to be canonical positive decimal integers in `1..usize::MAX` without leading
zeros or signs. This prevents invalid suffixes (`_0`, `_01`, `_+1`, etc.)
from advancing the counter and prevents `usize::MAX` from overflowing when
`update_min_id` increments it.
@mattsu2020
mattsu2020 force-pushed the fix/leaf-extraction-alias-format branch from 2ab85f3 to 5923630 Compare November 26, 2026 22:47
@mattsu2020 mattsu2020 changed the title fix: validate leaf extraction alias suffixes fix: classify leaf extraction aliases by placement and avoid collisions Nov 26, 2026
@mattsu2020
mattsu2020 requested a review from kosiew November 26, 2026 22:49

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattsu2020,

Thanks for addressing the previous feedback. Separating expression eligibility from numeric ID seeding is the right approach, and the guarded-division and direct collision regressions are addressed.

One blocking correctness issue remains: leaf projection pushdown must preserve column bindings at every destination, not just the immediate input.

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattsu2020,

Thanks for addressing the destination alias collisions. The current approach resolves the reproduced correctness failures.

Before approval, please add a SQL regression test that fails without the destination fix. The semi-join optimization tradeoff and projection merge simplification are non-blocking considerations.

let is_join = matches!(node, LogicalPlan::Join(_));
for (idx, input) in inputs.into_iter().enumerate() {
if per_input[idx].pairs.is_empty() {
if is_join

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: this guard prevents Parquet leaf pushdown in the tested LEFT SEMI join despite the conflicting right-hand field being excluded from the output. Is this intentional? If narrowing the guard, please preserve output, join key and filter bindings.

statement ok
DROP TABLE review_alias_collision;

# Nested UNION ALL where a carried or retried extraction alias collides with a

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both UNION ALL queries pass without the destination checks. Please retain the Rust regressions and add a SQL test that fails without the fix, using the previous nested LIMIT reproducer with pointer-width handling or a portable equivalent.

return Ok(false);
}

let existing_extractions: IndexMap<Expr, String> = existing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking suggestion: could the guard and projection builder share the expression substitution and deduplication decision to prevent future divergence in collision detection and safe alias reuse?

@kosiew

kosiew commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@mattsu2020

Thanks for working through all the review rounds. Looking at the whole change, I think it contains two separate fixes that would be easier to review and land apart, and the slow progress is partly my fault.

1. Classifying by placement fixes a real user-facing bug. SELECT 10 / id AS __datafusion_extracted_manual FROM t WHERE id > 0 should never divide by zero. is_extracted_alias fixes this where the decision belongs: whether an expression may be evaluated below a guard now comes from Expr::placement, not from its alias text. The narrower extracted_expr_id keeps invalid suffixes from moving the counter. Together with the guarded-division SQL and Rust tests, this part is small and correct, and I'd be glad to approve it alone.

2. Avoiding name collisions is a different problem. It only shows up when user columns or aliases use the reserved __datafusion_extracted prefix, often with suffixes near usize::MAX. Each review round, including my own requests, found one more place where a moved name could collide. The PR added a check at each one: reserved-name sets, re-extraction on shadowing, has_destination_alias_conflict at three sites, and a join-only check. The latest round showed that the join check now blocks Parquet leaf pushdown for an ordinary LEFT SEMI shape. has_destination_alias_conflict also repeats the merge builder's decisions, so the two have to stay in sync. The underlying cause is still that we can't tell generated aliases from user ones, which is #25449, and the description says full disambiguation still depends on it.

I don't think more checks at more sites will settle this, and my crafted-name witnesses pushed the PR that way. So I suggest:

  • This PR: keep only the placement classification and the canonical-ID seeding, roughly a8d5031b26 and b706ae6fec without the wraparound and collision tests, plus the guarded-division tests. Drop the allocation, shadowing and destination-check changes.
  • Collisions: track them separately, either as a documented limitation of the reserved prefix until Replace the __datafusion_extracted / __common_expr alias prefix protocol with a typed marker #25449 lands, or as a follow-up that handles collisions in one place. One idea I haven't tried: never move a user-supplied prefixed alias down the plan, always re-extract under a fresh name reserved across the whole plan, and skip the extraction instead of wrapping when no name is free. I haven't checked whether that holds for aliases the optimizer generated on an earlier pass, so please treat it as a starting point for discussion, not a requirement.

Sorry for the churn. Splitting it this way lets the real fix merge now and leaves the collision design to its own discussion.

@mattsu2020

Copy link
Copy Markdown
Contributor Author

@kosiew Should I split this PR?

@kosiew

kosiew commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@mattsu2020

Should I split this PR?

Yes.

Classify an alias as an extraction alias only when its name starts with
`__datafusion_extracted` and its inner expression is eligible for leaf
pushdown (`ExpressionPlacement::should_push_to_leaves`).

This prevents user-defined aliases with canonical names such as
`10 / id AS __datafusion_extracted_1` from being hoisted below filters,
while still accepting optimizer-generated `usize::MAX` and wrapped `_0`
aliases. Numeric suffix parsing remains reserved for generator seeding.
@mattsu2020
mattsu2020 force-pushed the fix/leaf-extraction-alias-format branch from cb3cc32 to 76acab8 Compare December 2, 2026 08:49
@mattsu2020 mattsu2020 changed the title fix: classify leaf extraction aliases by placement and avoid collisions fix: classify leaf extraction aliases by placement Dec 2, 2026
@mattsu2020

Copy link
Copy Markdown
Contributor Author

@kosiew I've split this PR as suggested.

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattsu2020,

Thanks for separating the placement fix from the broader alias collision work. The placement-based classification is appropriate, and the regression tests demonstrate that guarded expressions remain above filters.

However, the narrowed seeding policy introduces a reproducible compatibility regression. Please preserve the previous parsing behavior while retaining overflow protection.

.strip_prefix(EXTRACTED_EXPR_PREFIX)?
.strip_prefix('_')?;
// Integer parsing alone also accepts leading zeros and a leading '+'.
if suffix.starts_with('0') || !suffix.bytes().all(|b| b.is_ascii_digit()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting _01 or _+1 during seeding can allocate _1 despite an existing scan field, causing previously working SQL to fail with schema ambiguity. Please restore the previous parsing behavior for IDs below usize::MAX and add the _01 SQL regression.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eg this passes on main but fails in this PR

   SET datafusion.optimizer.enable_leaf_expression_pushdown = true;
   CREATE TABLE seed AS
   SELECT column1 AS __datafusion_extracted_1, column2 AS s
   FROM VALUES (0, {a: 10}), (1, {a: 20});

   SELECT 99 AS __datafusion_extracted_01
   FROM seed WHERE __datafusion_extracted_1 > 0 AND s['a'] = 20;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants