Skip to content

fix: JoinSelection keeps the requirements a join's inputs already satisfy - #27771

Open
jayzhan211 wants to merge 5 commits into
apache:mainfrom
jayzhan211:fix/join-selection-keeps-requirements
Open

jayzhan211 wants to merge 5 commits into
apache:mainfrom
jayzhan211:fix/join-selection-keeps-requirements

Conversation

@jayzhan211

@jayzhan211 jayzhan211 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

A rule list that runs JoinSelection after EnsureRequirements fails to plan many join queries: on the sqllogictest suite, 293 records fail with SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'join_selection' (local harness that moves the rule, not part of this PR). In 292 of them, JoinSelection swapped a join's inputs so that the build side, which needs one partition, has several. SELECT a, b FROM big, small over two tables with two partitions each is enough.

After this PR, the JoinSelection physical optimizer rule produces valid plans for these joins (292 of the 293 records) and does not require a follow-on pass of EnsureRequirements to align requirements. It is part of the longer-term goal in #26481 to simplify the required physical optimizer rule ordering.

What changes are included in this PR?

  • keep_satisfied_requirements in join_selection.rs (start reading here) runs after each swap or mode change. If the old join's inputs satisfied its order and distribution requirements, the new join's inputs must too:
    • A new build side with several partitions gets a CoalescePartitionsExec.
    • The old build side's merge, now on the probe side, is dropped when the old join's output had several partitions and no hash or range key, because nothing above the join can rely on such an output.
    • If another requirement that held breaks, the join is kept as it is.
  • A hash join in PartitionMode::Auto is exempt: it declares no requirement until EnsureRequirements picks its mode.

The decision I'd most like reviewed: adding the merge instead of skipping the swap. Before EnsureRequirements runs, a larger input can have one partition only because it is one batch; skipping would keep it as the build side and change default plans. With the merge, the swap happens as on main, and EnsureRequirements later replaces the merge with the ones the plan needs.

What is the testing strategy for this PR?

  • In core/tests/physical_optimizer/join_selection.rs:
    • join_selection_after_enforcement_keeps_merged_build_side: with JoinSelection after EnsureRequirements, a cross join of two two-partition tables returns all 8 rows. On main it fails with the error above.
    • join_selection_after_enforcement_drops_merge_from_probe_side and ..._keeps_merge_for_hash_partitioned_output: the probe side's merge is dropped when the old output had no key, and kept when it was hash partitioned.
    • join_selection_swaps_larger_single_partition_input: the default order keeps main's plan for a larger input in one partition.
  • The sqllogictest suite (with TPC-H) under the local harness, main 73af333 vs this PR:
Rule list SanityCheckPlan errors
default 0 → 0, no plan changes
JoinSelection after EnsureRequirements 293 → 1
The record left

group_by.slt:3330 still fails planning, with the same error naming join_selection. EnsureRequirements sorted the probe side so the join's output satisfies the order an array_agg(... ORDER BY ...) above the join needs; the swap makes that side the build side. The check only looks at the join's own requirements. Also keeping the join's output order fixes this record, but changes three records in the default order (joins.slt:4020, :4034, :4148), so it isn't in this PR.

Are there any user-facing changes?

No public API change, and no plan change in the default rule order.

For rule lists that run JoinSelection after EnsureRequirements, these swaps no longer fail planning. The swapped join's probe side keeps its partitions, unless the old join's output was hash or range partitioned; then it runs in one partition.

@github-actions github-actions Bot added optimizer Optimizer rules core Core DataFusion crate labels Nov 26, 2026
@jayzhan211
jayzhan211 marked this pull request as ready for review November 26, 2026 13:41
@jayzhan211
jayzhan211 marked this pull request as draft November 26, 2026 14:16
@jayzhan211 jayzhan211 changed the title fix: JoinSelection keeps a join whose inputs already satisfy its requirements fix: JoinSelection keeps the requirements a join's inputs already satisfy Nov 26, 2026
@jayzhan211
jayzhan211 marked this pull request as ready for review November 26, 2026 14:45
&& child.output_partitioning().partition_count() > 1
{
merged_any = true;
Arc::new(CoalescePartitionsExec::new(Arc::clone(child))) as _

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.

After a swap the old build side becomes the probe side but keeps its CoalescePartitionsExec, so with JoinSelection after EnsureRequirements the probe side runs in one partition. SELECT big.column1, small.column1 FROM big, small (two 2-file parquet tables, target_partitions = 2):

CrossJoinExec
  CoalescePartitionsExec
    DataSourceExec  (small)
  CoalescePartitionsExec
    DataSourceExec  (big)

Could the swap drop that merge when nothing else needs it?

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.

The swap now drops it when the old join's output had several partitions and no hash or range key, since nothing above the join can rely on such an output. When the output was hash or range partitioned, the merge stays: a node above may rely on that partitioning, and the swapped join's one-partition output still satisfies it.

})
})?
.data;
let mut broken = false;

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.

For group_by.slt:3330, the node relying on the order is the partial AggregateExec two levels above the join (a ProjectionExec in between), so a parent check wouldn't catch it. A whole-plan check like #27772 fixes it, but changes two default-order plans (cte_materialized.slt, preserve_file_partitioning.slt: CollectLeft becomes Partitioned), since before EnsureRequirements a simple plan can already satisfy its requirements.

@alamb alamb 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.

Thanks for this PR @jayzhan211

I think it would help if we also cleaned up the PR summary. I found this really hard to understand (and I already know what this PR does):

With this PR, JoinSelection keeps the requirements a join's inputs already satisfy, as every rule after EnsureRequirements must, instead of leaving a plan that only a later pass could repair.

Maybe something like

After this PR, the JoinSelection physical optimizer rule produces valid plans and does not require a follow on pass of EnsureRequirements to align requirements. It is part of our longer term goal to simplify required optimizer rule ordering

@alamb alamb 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.

Thanks @jayzhan211 -- this seems like an improvement to me. I think it would help if we clarified some of the comments but otherwise this looks great

}

/// A session whose physical optimizer runs [`JoinSelection`] right after
/// [`EnsureRequirements`] instead of before it.

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.

maybe we can add rationale here (we want to ensure that JoinSelection does not make invalid plans that require EnsureRequirements to repair)

/// [`EnsureRequirements`] instead of before it.
fn session_with_join_selection_after_enforcement() -> SessionContext {
let mut rules = PhysicalOptimizer::new().rules;
let position = |rules: &[Arc<dyn PhysicalOptimizerRule + Send + Sync>],

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.

would this be better as a method on PhysicalOptimizer? this is fine, it just feels weird to be mucking round with the internal stte

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.

rules is already the public way to change the list (PhysicalOptimizer::with_rules points to the contract for non-default lists), and the test in output_requirements.rs reads it the same way, so a method would be new public API with only this test as a caller. If a test harness for other rule orders lands later, it would have more callers and I'd add the method there. OK to keep it as is here?

/// order and distribution requirements that `old`'s inputs satisfy, because
/// nothing restores them once `EnsureRequirements` has run.
///
/// A swap can make an input with several partitions the build side, which

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.

I don't quite follow this paragraph -- is it trying to say that this returns None if it is not possible to build a valid join ?

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.

Yes: None means the rewritten join would break a requirement the old join's inputs met, so JoinSelection keeps the old join. The doc comment now says that in its first sentence.

@jayzhan211

Copy link
Copy Markdown
Contributor Author

Address all the comments!

})
};
// Several partitions without a key satisfy only an unspecified distribution.
let output_has_no_key = matches!(

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.

Keeping the merge can break a co-partitioned parent. With JoinSelection after EnsureRequirements, target_partitions = 2 and the single-partition thresholds at 0:

SELECT x.a, x.k FROM (SELECT a, s.k FROM big, (SELECT k FROM small GROUP BY k) s) x JOIN t ON x.k = t.k
HashJoinExec: mode=Partitioned, on=[(k@1, k@0)]
  ProjectionExec: expr=[a@1 as a, k@0 as k]
    CrossJoinExec
      CoalescePartitionsExec
        AggregateExec: mode=FinalPartitioned, gby=[k@0 as k]
      CoalescePartitionsExec
        DataSourceExec: partitions=2
  RepartitionExec: partitioning=Hash([k@0], 2)

Planning fails with HashJoinExec requires children [0, 1] to be co-partitioned. Maybe keep the join as is when the old output had a key?

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

Labels

core Core DataFusion crate optimizer Optimizer rules

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants