Skip to content

fix: keep a sub-expression as the canonical expression of its equivalence class - #26967

Open
abp002 wants to merge 1 commit into
apache:mainfrom
abp002:smj-self-referencing-equality
Open

abp002 wants to merge 1 commit into
apache:mainfrom
abp002:smj-self-referencing-equality

Conversation

@abp002

@abp002 abp002 commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

A sort-merge join on (a, b) fails with SanityCheckPlan when a filter below it equates an expression with one of its own sub-expressions, such as x.a + x.b = x.a.

The filter puts a + b and a in one equivalence class, with a + b as the canonical expression because it comes first. normalize_expr rewrites bottom-up, so it replaces the a inside a + b with a + b and turns a + b into (a + b) + b. The join requires [a, b], which normalizes to [a + b, b], while the sort below it is on [a + b, b], which normalizes to [(a + b) + b, b], so the sort no longer satisfies the join. Written as x.a = x.a + x.b, the query works, because a is the canonical expression.

What changes are included in this PR?

When EquivalenceGroup::add_equal_conditions adds to a class, a member that is a sub-expression of the canonical expression now becomes the canonical expression. normalize_expr is unchanged, so classes without such a pair normalize as before.

What is the testing strategy for this PR?

The query from the issue is added to sort_merge_join.slt. It fails without the fix.

equivalence_properties.slt gets a plan that main already gets right and that a fix in normalize_expr itself would break: with a = b AND c = a + 1 above ORDER BY a + 1 LIMIT 100, the outer ORDER BY a + 1 needs no sort.

It also gets a query with two IN lists that hold the same values in a different order. They compare equal but hash differently, so both stay in the class, and the promotion must still stop.

Are there any user-facing changes?

No API changes. Queries like the one in the issue now plan instead of failing in SanityCheckPlan.

@github-actions github-actions Bot added physical-expr Changes to the physical-expr crates sqllogictest SQL Logic Tests (.slt) labels Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

physical-expr Changes to the physical-expr crates sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SanityCheckPlan error with sort-merge join when a filter says a + b = a

1 participant