Skip to content

fix: the physical planner runs EnsureRequirements again after a rule breaks a requirement - #27648

Open
jayzhan211 wants to merge 1 commit into
apache:mainfrom
jayzhan211:fix/planner-repairs-broken-requirements
Open

jayzhan211 wants to merge 1 commit into
apache:mainfrom
jayzhan211:fix/planner-repairs-broken-requirements

Conversation

@jayzhan211

@jayzhan211 jayzhan211 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

Every physical optimizer rule after EnsureRequirements, including rules a project appends to the default list, must keep the plan's order and distribution requirements, or planning fails with a SanityCheckPlan error. So a rule only works where the rules before it left a plan it handles. Running the sqllogictest suite with JoinSelection moved after EnsureRequirements (with a local harness, not part of this PR), 293 records fail with that error on main at c5361f0; with this PR, 0.

This PR makes the physical planner repair such a plan: when a rule after EnsureRequirements returns a plan whose requirements no longer hold, the planner runs EnsureRequirements again before the next rule. In the default rule order no rule breaks a requirement, so nothing runs again and no plan changes; the checks add about 1–2% to planning time.

What changes are included in this PR?

  • DefaultPhysicalPlanner::optimize_physical_plan (start reading here): after each rule that follows EnsureRequirements, it checks the nodes the rule changed. If a requirement broke, it runs EnsureRequirements with round-robin repartitioning and file-scan splitting off, so the repair adds only what a requirement needs, not extra parallelism that could split a limit's input.
  • input_requirements_hold_since in sanity_checker.rs (#[doc(hidden)]): skips nodes shared with the previous plan (pointer identity), so the check walks only what the rule changed.
  • Docs: the contract in optimizer.rs. The error naming the rule that broke the requirements now only appears when the repair can't restore them.

The decision I'd most like reviewed: repairing right after the rule that broke a requirement, not once after the last rule, so every later rule still gets a plan whose requirements hold. Repairing at the end would skip the per-rule check; I did not measure it.

What is the testing strategy for this PR?

  • test_appended_rule_that_breaks_requirements_is_repaired in core/tests/physical_optimizer/sanity_checker.rs: a rule appended after the default list removes every sort. The plan gets its sort back and row_number() returns 1, 2, 3. On main it fails with "order and distribution requirements stopped holding after physical optimizer rule 'remove_sorts'".
  • The sqllogictest suite (with TPC-H), the physical optimizer integration tests and the crate's unit tests pass unchanged; a local counter showed 0 repairs over the suite.
  • sql_planner benchmarks, main vs this PR, 3 alternating rounds: planning the TPC-H, TPC-DS and ClickBench queries takes +1.4%, +1.1% and +1.7% longer (median round). For comparison, a logical-planning benchmark this PR does not touch moved +0.5%.
  • Rearranged rule lists (local harness): no list gains a wrong or reordered result; plan errors drop as below.
sqllogictest records per rule list, main c5361f0 vs this PR (local harness)
Rule list SanityCheckPlan errors Result mismatches Repairs
default 0 → 0 0 → 0 0
JoinSelection after EnsureRequirements 293 → 0 1 → 0 318
EnsureRequirements first 294 → 0 3 → 3 (same records) 315
shuffled (seed 1) 296 → 1 16 → 15 (subset) 314
whole list run twice (re-planning) 0 → 0 1 → 1, intermittent in both (2 of 20 runs each) 48

Every mismatch left with this PR also occurs on main. The intermittent one is a MATERIALIZED CTE query whose ORDER BY rows come out of order when the list runs twice.

`sql_planner` per round, main c5361f0 vs this PR (Criterion estimate, ms; main ran first in each pair)
Benchmark Round 1 Round 2 Round 3
physical_plan_tpch_all 19.51 → 19.79 (+1.4%) 19.40 → 19.73 (+1.7%) 19.31 → 19.32 (+0.1%)
physical_plan_tpcds_all 294.6 → 294.2 (−0.1%) 287.3 → 290.5 (+1.1%) 286.4 → 296.4 (+3.5%)
physical_plan_clickbench_all 68.39 → 70.00 (+2.4%) 67.89 → 68.34 (+0.7%) 69.47 → 70.64 (+1.7%)
physical_select_all_from_1000 3.95 → 3.91 (−1.0%) 3.84 → 3.86 (+0.7%) 3.87 → 3.83 (−1.1%)
logical_select_all_from_1000 (not touched) 1.385 → 1.396 (+0.7%) 1.399 → 1.399 (0%) 1.386 → 1.393 (+0.5%)

Are there any user-facing changes?

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

Downstream impact, for rule lists that contain EnsureRequirements and run rules after it:

  • A rule that leaves a requirement broken at the end used to fail planning; now the plan gets the missing sort, repartition or merge.
  • A rule that breaks a requirement that a later rule of the same list fixes used to be accepted as is; now EnsureRequirements runs between them, so the later rule sees the repaired plan and the final plan can differ.
  • Lists without EnsureRequirements are unchanged.
Downstream projects checked (by reading their code, not by running them)
  • Ballista's adaptive planner appends ParallelWindowRule, PrefixWindowRule and DistributedExchangeRule after the default list. PrefixWindowRule inserts a PrefixMergeExec that keeps its input's partitions and adds no merge for the parent (prefix_window.rs:174-179). If that parent needs one partition, planning failed before; now it gets a merge. I don't know whether real plans reach that.
  • datafusion-distributed runs its passes on the plan the planner returns, so they are unaffected.
  • liquid-cache appends a rule whose wrapper node copies its child's partitioning and orderings, so it keeps every requirement.

{
// Repair only: added parallelism could split the input of a fetch.
let mut config = session_state.config_options().clone();
config.optimizer.enable_round_robin_repartition = 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.

This repair also drops parallelism far from the broken node. ensure_distribution strips existing repartitions on every node and, with round-robin off, doesn't add them back. With target_partitions = 4 and RemoveSorts appended:

SELECT b, c, row_number() OVER (ORDER BY b) FROM
  (SELECT value % 7 AS b, count(*) AS c FROM generate_series(1, 1000000)
   WHERE value > 5 GROUP BY value % 7)

the sort comes back, but the RoundRobinBatch(4) under the filter and partial aggregate is gone (Hash(...), input_partitions=1), so that part now runs on one partition.

/// them: either `EnsureRequirements` itself, or the rule after which the
/// requirements stopped holding. To find it, `optimizers` run again from `input_plan`, so
/// planning that succeeds keeps no intermediate plans.
fn sanity_check_error(

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.

The replay doesn't repair, so it can name the wrong rule. With RemoveSorts (repaired in the loop) followed by a rule whose break can't be repaired, the error says stopped holding after physical optimizer rule 'remove_sorts'. My second rule was contrived (a node that ignores new children), but the loop already knows which rule's repair failed, so recording it there would avoid the replay.

Box::new(e),
)
})?;
enforced = input_requirements_hold(&new_plan);

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.

The observer below then sees the repaired plan under the rule that broke it, so EXPLAIN VERBOSE shows physical_plan after remove_sorts: SAME TEXT AS ABOVE (with the SortExec) and the repair is invisible. Could the repair be reported as its own EnsureRequirements step?

@2010YOUY01

Copy link
Copy Markdown
Member

Thank you for working on this. I got a question:

Every physical optimizer rule after EnsureRequirements, including rules a project appends to the default list, must keep the plan's order and distribution requirements, or planning fails with a SanityCheckPlan error. So a rule only works where the rules before it left a plan it handles. Running the sqllogictest suite with JoinSelection moved after EnsureRequirements (with a local harness, not part of this PR), 293 records fail with that error on main at c5361f0; with this PR, 0.

Why are we moving JoinSelection after EnsureRequirements?

I don't think we need to enforce a rule that all optimizations must run after EnsureRequirements. Instead, the invariant should be:

  • A rule should be placed after EnsureRequriements if it have to, since this placement make the impl harder (need to recognize RepartitionExec)
  • any rule running after EnsureRequirements must preserve the established ordering and distribution requirements.

So the question is: what additional requirements motivate moving JoinSelection after EnsureRequirements? I suspect this change is unlikely to make the implementation simpler.

@alamb

alamb commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

So the question is: what additional requirements motivate moving JoinSelection after EnsureRequirements? I suspect this change is unlikely to make the implementation simpler.

One thing it would allow is for JoinSelection to maintain the invariant of "The input must be an executable plan, and the output is also an executable plan"

Since it runs today before EnsureRequirements, it can't make assumptions of the input plans

let mut new_plan = Arc::clone(&plan);
let optimizer_context = SessionOptimizerContext::new(session_state);
let enforcement = EnsureRequirements::new();
// Whether the requirements held after enforcement ran. Once they have, a rule

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.

Isn't this just going to cause confusion as plans may work even with broken optimizer rules (this code will repair them)? That feels like it will go against the idea of separating out the "make the plans valid" from the "make a valid plan faster" ideas 🤔

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.

Agreed. Fixing the two rules that break requirements after EnsureRequirements looks like a better choice than this PR. On the sqllogictest suite, when I move each rule that runs before EnsureRequirements (other than OutputRequirements) to after it, only JoinSelection and WindowTopN break a requirement. With each of them fixed to keep the requirements it finds satisfied (#27771, #27772):

  • JoinSelection after EnsureRequirements: 293 planning errors → 1
  • WindowTopN after EnsureRequirements: 1 → 0, and a query that put the NULL row first for ORDER BY pk now returns it last
  • no plan change in the default order

Each rule then turns a valid plan into a valid plan, so a broken rule still fails planning with its name, and the physical planner needs no repair step after each rule, so the lost parallelism @zhuqi-lucas found can't happen.

If you agree, I'll close this PR in favor of those two.

@jayzhan211

Copy link
Copy Markdown
Contributor Author

Why are we moving JoinSelection after EnsureRequirements?

The default order doesn't change. The goal is that no rule implicitly assumes it runs before EnsureRequirements, so JoinSelection should not break a requirement when it runs after it. I moved it only in a local harness to check that: on main, 293 records then fail planning.

Thanks @2010YOUY01, @alamb and @zhuqi-lucas for the reviews. #27771 (JoinSelection) and #27772 (WindowTopN) fix the two rules instead, so the physical planner doesn't need to repair the plan as this PR does. Those two PRs are the next step to review.

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.

4 participants