Skip to content

Optimize logical optimizer: skip map_subqueries + in-place rewriting#22298

Open
adriangb wants to merge 3 commits into
apache:mainfrom
pydantic:optimize-logical-optimizer
Open

Optimize logical optimizer: skip map_subqueries + in-place rewriting#22298
adriangb wants to merge 3 commits into
apache:mainfrom
pydantic:optimize-logical-optimizer

Conversation

@adriangb
Copy link
Copy Markdown
Contributor

@adriangb adriangb commented May 17, 2026

Which issue does this PR close?

Supersedes #20837. That PR's branch was rebased onto current main; GitHub does
not allow reopening a closed PR once its branch has been force-pushed, so this is
a fresh PR carrying the same work, rebased and re-benchmarked.

Rationale for this change

Optimizer::optimize runs every logical optimizer rule over the whole plan,
repeatedly, until a fixed point. Benchmarking the optimizer in isolation (SQL
parsing and analysis excluded) surfaced two avoidable costs:

  1. rewrite_with_subqueries calls map_subqueries at every plan node, walking
    every expression tree via ownership-based transform_down — even for plans
    with no subquery expressions at all, which is the common case.
  2. The ownership-based TreeNode::rewrite traversal performs an
    Arc::unwrap_or_clone + Arc::new cycle at every child node, re-allocating
    the Arc spine on every pass even when nothing changes.

What changes are included in this PR?

Three optimizations:

  1. map_subqueries short-circuit — skip the expression-tree walk when a node
    has no subquery expressions.
  2. plan_has_subqueries per-pass check — when the whole plan has no
    subqueries, bypass rewrite_with_subqueries entirely and use the cheaper
    in-place traversal.
  3. rewrite_plan_in_place with Arc::make_mut — a private
    map_children_mut helper in the optimizer crate mutates Arc<LogicalPlan>
    children in place (copy-on-write; free when the refcount is 1, the common
    case in the optimizer), avoiding the Arc::unwrap_or_clone + Arc::new
    cycle. The owned-plan rule API is bridged with std::mem::take, which is
    allocation-free because LogicalPlan::default() is an EmptyRelation that
    shares the process-wide static empty schema.

Also adds optimizer-only benchmarks to sql_planner.rs that isolate optimizer
cost from SQL parsing/analysis.

Benchmark results (optimizer-only, criterion, this PR vs main)

Benchmark main this PR Change
optimizer_select_one_from_700 200 µs 202 µs +1% (noise)
optimizer_select_all_from_1000 4.71 ms 4.13 ms −12%
optimizer_join_chain_4 136 µs 103 µs −24%
optimizer_join_chain_8 445 µs 363 µs −18%
optimizer_wide_filter_200 4.91 ms 3.47 ms −29%
optimizer_wide_aggregate_100 2.10 ms 1.50 ms −29%
optimizer_correlated_exists 187 µs 185 µs −1% (noise)
optimizer_join_4_with_agg_filter 384 µs 276 µs −28%
optimizer_tpch_all 12.25 ms 9.14 ms −25%
optimizer_tpcds_all 220 ms 170 ms −23%

Measured A/B on a single machine: for the baseline run the two optimizer rule
files were reverted to main (keeping the new benchmark code), then restored, so
only the optimization itself is being measured. The optimizer_tpcds_all number
was confirmed across multiple back-to-back runs after an initial reading was
distorted by machine interference.

Possible future work (not in this PR)

The mem::take bridge in rewrite_plan_in_place is allocation-free, but it still
extracts an owned plan for every (node, rule) pair up front — before the rule
decides whether it will transform — and the overwhelming majority of those pairs
are no-ops. A dynamic "lazy handle" rule API (the rule receives a handle that
derefs to &LogicalPlan for free and only pays the copy-on-write / move when it
calls make_mut / replace) would let the framework skip the extraction for
no-op rule invocations entirely. That is a breaking change to the public
OptimizerRule trait and is out of scope here; it is being prototyped separately.

Are these changes tested?

Yes. The existing optimizer test suite (713 tests across datafusion-optimizer)
passes unchanged. The optimizations are behavior-preserving: the in-place
traversal produces the same plans as the ownership-based traversal, and the
subquery short-circuit only skips work that is provably a no-op.

Are there any user-facing changes?

No. No new public API — the in-place traversal helper is private to the
optimizer crate. Optimization is faster; output plans are unchanged.

@github-actions github-actions Bot added logical-expr Logical plan and expressions optimizer Optimizer rules core Core DataFusion crate labels May 17, 2026
@adriangb
Copy link
Copy Markdown
Contributor Author

run benchmark sql_planner

Three optimizations that together yield ~23-25% faster optimization on
TPC-H/TPC-DS and up to 33% on expression-heavy queries:

1. map_subqueries short-circuit: skip expression tree walks when no
   subquery expressions exist. Previously rewrite_with_subqueries
   called map_subqueries at every plan node, walking all expression
   trees via ownership-based transform_down even with no subqueries.

2. plan_has_subqueries per-pass check: when no subqueries exist in
   the plan, bypass rewrite_with_subqueries entirely and use the
   cheaper rewrite_plan_in_place path.

3. rewrite_plan_in_place with Arc::make_mut: new map_children_mut
   method that mutates children in-place, avoiding the
   Arc::unwrap_or_clone + Arc::new allocation cycle at every node.
   The owned-plan rule API is bridged with std::mem::take, which is
   allocation-free: LogicalPlan::default() is an EmptyRelation that
   shares the process-wide static empty schema.

Also adds optimizer-only benchmarks that isolate optimizer performance
from SQL parsing and analysis overhead.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@adriangb adriangb force-pushed the optimize-logical-optimizer branch from d405cdf to 7d5359f Compare May 17, 2026 15:42
@adriangbot
Copy link
Copy Markdown

🤖 Criterion benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c4471249479-169-5xgcm 6.12.68+ #1 SMP Wed Apr 1 02:23:28 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing optimize-logical-optimizer (d405cdf) to 102da39 (merge-base) diff
BENCH_NAME=sql_planner
BENCH_COMMAND=cargo bench --features=parquet --bench sql_planner
BENCH_FILTER=
Results will be posted here when complete


File an issue against this benchmark runner

@adriangbot
Copy link
Copy Markdown

🤖 Criterion benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

group                                                 main                                   optimize-logical-optimizer
-----                                                 ----                                   --------------------------
logical_aggregate_with_join                           1.00    414.4±1.67µs        ? ?/sec    1.01    418.4±1.84µs        ? ?/sec
logical_correlated_subquery_exists                                                           1.00    249.0±0.74µs        ? ?/sec
logical_correlated_subquery_in                                                               1.00    249.9±1.28µs        ? ?/sec
logical_distinct_many_columns                                                                1.00    316.6±2.25µs        ? ?/sec
logical_join_4_with_agg_and_filter                                                           1.00    234.9±0.76µs        ? ?/sec
logical_join_8_with_agg_sort_limit                                                           1.00    401.9±2.30µs        ? ?/sec
logical_join_chain_16                                                                        1.00    649.7±4.54µs        ? ?/sec
logical_join_chain_4                                                                         1.00    113.6±0.31µs        ? ?/sec
logical_join_chain_8                                                                         1.00    239.5±0.84µs        ? ?/sec
logical_multiple_subqueries                                                                  1.00    448.3±1.30µs        ? ?/sec
logical_nested_cte_4_levels                                                                  1.00    240.1±2.23µs        ? ?/sec
logical_plan_struct_join_agg_sort                     1.00    170.8±0.75µs        ? ?/sec    1.00    171.2±1.92µs        ? ?/sec
logical_plan_tpcds_all                                                                       1.00     74.0±0.13ms        ? ?/sec
logical_plan_tpch_all                                                                        1.00      5.7±0.01ms        ? ?/sec
logical_scalar_subquery                                                                      1.00    272.3±0.81µs        ? ?/sec
logical_select_all_from_1000                          1.00      8.0±0.03ms        ? ?/sec    1.00      8.0±0.03ms        ? ?/sec
logical_select_one_from_700                           1.00    270.9±1.84µs        ? ?/sec    1.02    276.4±2.41µs        ? ?/sec
logical_trivial_join_high_numbered_columns            1.00    251.2±1.19µs        ? ?/sec    1.02    255.4±1.60µs        ? ?/sec
logical_trivial_join_low_numbered_columns             1.00    239.5±1.04µs        ? ?/sec    1.01    242.7±0.91µs        ? ?/sec
logical_union_4_branches                                                                     1.00    355.8±6.76µs        ? ?/sec
logical_union_8_branches                                                                     1.00    679.2±4.14µs        ? ?/sec
logical_wide_aggregate_100_exprs                                                             1.00      3.7±0.01ms        ? ?/sec
logical_wide_case_50_exprs                                                                   1.00   1649.9±6.05µs        ? ?/sec
logical_wide_filter_200_predicates                                                           1.00   1281.2±7.30µs        ? ?/sec
logical_wide_filter_50_predicates                                                            1.00    367.3±1.58µs        ? ?/sec
optimizer_correlated_exists                                                                  1.00    249.8±0.43µs        ? ?/sec
optimizer_join_4_with_agg_filter                                                             1.00    431.9±2.26µs        ? ?/sec
optimizer_join_chain_4                                                                       1.00    173.3±0.54µs        ? ?/sec
optimizer_join_chain_8                                                                       1.00    547.5±0.81µs        ? ?/sec
optimizer_select_all_from_1000                                                               1.00      4.6±0.01ms        ? ?/sec
optimizer_select_one_from_700                                                                1.00    260.5±0.60µs        ? ?/sec
optimizer_tpcds_all                                                                          1.00    258.8±0.41ms        ? ?/sec
optimizer_tpch_all                                                                           1.00     14.9±0.08ms        ? ?/sec
optimizer_wide_aggregate_100                                                                 1.00      2.1±0.01ms        ? ?/sec
optimizer_wide_filter_200                                                                    1.00      3.9±0.01ms        ? ?/sec
physical_intersection                                 1.04    562.9±2.15µs        ? ?/sec    1.00    539.7±1.88µs        ? ?/sec
physical_join_consider_sort                           1.03   1002.5±6.47µs        ? ?/sec    1.00    976.8±2.23µs        ? ?/sec
physical_join_distinct                                1.00    231.1±0.91µs        ? ?/sec    1.02    236.3±1.19µs        ? ?/sec
physical_many_self_joins                              1.00      7.5±0.04ms        ? ?/sec    1.00      7.6±0.02ms        ? ?/sec
physical_plan_clickbench_all                          1.10    129.6±0.63ms        ? ?/sec    1.00    117.8±0.38ms        ? ?/sec
physical_plan_clickbench_q1                           1.10   1358.0±6.58µs        ? ?/sec    1.00   1233.9±6.99µs        ? ?/sec
physical_plan_clickbench_q10                          1.13      2.0±0.01ms        ? ?/sec    1.00   1820.7±8.94µs        ? ?/sec
physical_plan_clickbench_q11                          1.12      2.2±0.02ms        ? ?/sec    1.00      2.0±0.01ms        ? ?/sec
physical_plan_clickbench_q12                          1.13      2.3±0.02ms        ? ?/sec    1.00      2.1±0.01ms        ? ?/sec
physical_plan_clickbench_q13                          1.12      2.1±0.01ms        ? ?/sec    1.00   1847.3±7.31µs        ? ?/sec
physical_plan_clickbench_q14                          1.12      2.2±0.01ms        ? ?/sec    1.00      2.0±0.01ms        ? ?/sec
physical_plan_clickbench_q15                          1.11      2.1±0.02ms        ? ?/sec    1.00   1923.0±8.54µs        ? ?/sec
physical_plan_clickbench_q16                          1.13  1779.3±16.21µs        ? ?/sec    1.00   1576.6±5.50µs        ? ?/sec
physical_plan_clickbench_q17                          1.10   1817.4±9.95µs        ? ?/sec    1.00   1656.9±7.77µs        ? ?/sec
physical_plan_clickbench_q18                          1.10   1646.7±7.52µs        ? ?/sec    1.00   1490.9±5.41µs        ? ?/sec
physical_plan_clickbench_q19                          1.11      2.0±0.01ms        ? ?/sec    1.00   1842.1±6.17µs        ? ?/sec
physical_plan_clickbench_q2                           1.12   1792.6±8.31µs        ? ?/sec    1.00   1605.2±7.32µs        ? ?/sec
physical_plan_clickbench_q20                          1.07   1525.5±5.78µs        ? ?/sec    1.00   1424.6±6.82µs        ? ?/sec
physical_plan_clickbench_q21                          1.07  1768.5±10.96µs        ? ?/sec    1.00   1648.8±5.87µs        ? ?/sec
physical_plan_clickbench_q22                          1.11      2.2±0.01ms        ? ?/sec    1.00      2.0±0.01ms        ? ?/sec
physical_plan_clickbench_q23                          1.11      2.4±0.02ms        ? ?/sec    1.00      2.2±0.01ms        ? ?/sec
physical_plan_clickbench_q24                          1.07      5.8±0.03ms        ? ?/sec    1.00      5.4±0.04ms        ? ?/sec
physical_plan_clickbench_q25                          1.07   1910.4±7.90µs        ? ?/sec    1.00  1778.6±23.02µs        ? ?/sec
physical_plan_clickbench_q26                          1.09   1725.7±9.05µs        ? ?/sec    1.00   1587.3±5.75µs        ? ?/sec
physical_plan_clickbench_q27                          1.10   1920.3±6.00µs        ? ?/sec    1.00   1753.7±8.55µs        ? ?/sec
physical_plan_clickbench_q28                          1.12      2.4±0.01ms        ? ?/sec    1.00      2.2±0.01ms        ? ?/sec
physical_plan_clickbench_q29                          1.12      2.6±0.01ms        ? ?/sec    1.00      2.3±0.01ms        ? ?/sec
physical_plan_clickbench_q3                           1.10   1614.7±8.30µs        ? ?/sec    1.00   1467.1±7.38µs        ? ?/sec
physical_plan_clickbench_q30                          1.15     16.5±0.09ms        ? ?/sec    1.00     14.4±0.08ms        ? ?/sec
physical_plan_clickbench_q31                          1.11      2.5±0.01ms        ? ?/sec    1.00      2.2±0.01ms        ? ?/sec
physical_plan_clickbench_q32                          1.11      2.5±0.01ms        ? ?/sec    1.00      2.2±0.01ms        ? ?/sec
physical_plan_clickbench_q33                          1.11      2.0±0.01ms        ? ?/sec    1.00   1808.6±8.92µs        ? ?/sec
physical_plan_clickbench_q34                          1.11   1765.6±6.06µs        ? ?/sec    1.00   1596.5±4.91µs        ? ?/sec
physical_plan_clickbench_q35                          1.11   1830.8±7.00µs        ? ?/sec    1.00   1651.4±7.10µs        ? ?/sec
physical_plan_clickbench_q36                          1.12      2.2±0.01ms        ? ?/sec    1.00   1927.1±7.08µs        ? ?/sec
physical_plan_clickbench_q37                          1.13      2.6±0.02ms        ? ?/sec    1.00      2.3±0.01ms        ? ?/sec
physical_plan_clickbench_q38                          1.13      2.6±0.01ms        ? ?/sec    1.00      2.3±0.01ms        ? ?/sec
physical_plan_clickbench_q39                          1.14      2.7±0.01ms        ? ?/sec    1.00      2.4±0.01ms        ? ?/sec
physical_plan_clickbench_q4                           1.13   1456.1±6.60µs        ? ?/sec    1.00   1294.0±9.66µs        ? ?/sec
physical_plan_clickbench_q40                          1.11      3.5±0.02ms        ? ?/sec    1.00      3.1±0.02ms        ? ?/sec
physical_plan_clickbench_q41                          1.13      3.0±0.02ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
physical_plan_clickbench_q42                          1.08      3.1±0.01ms        ? ?/sec    1.00      2.9±0.02ms        ? ?/sec
physical_plan_clickbench_q43                          1.09      3.3±0.01ms        ? ?/sec    1.00      3.0±0.02ms        ? ?/sec
physical_plan_clickbench_q44                          1.10   1526.0±9.37µs        ? ?/sec    1.00   1385.8±5.75µs        ? ?/sec
physical_plan_clickbench_q45                          1.10  1541.0±14.71µs        ? ?/sec    1.00  1407.1±12.41µs        ? ?/sec
physical_plan_clickbench_q46                          1.10   1862.1±7.22µs        ? ?/sec    1.00   1689.6±8.06µs        ? ?/sec
physical_plan_clickbench_q47                          1.11      2.6±0.02ms        ? ?/sec    1.00      2.4±0.01ms        ? ?/sec
physical_plan_clickbench_q48                          1.11      2.9±0.02ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
physical_plan_clickbench_q49                          1.10      2.9±0.02ms        ? ?/sec    1.00      2.7±0.01ms        ? ?/sec
physical_plan_clickbench_q5                           1.10   1565.9±5.42µs        ? ?/sec    1.00   1423.0±9.11µs        ? ?/sec
physical_plan_clickbench_q50                          1.14      2.9±0.02ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
physical_plan_clickbench_q51                          1.11   1977.4±6.97µs        ? ?/sec    1.00   1782.7±6.84µs        ? ?/sec
physical_plan_clickbench_q6                           1.08   1564.0±8.40µs        ? ?/sec    1.00   1446.1±6.36µs        ? ?/sec
physical_plan_clickbench_q7                           1.09   1592.7±4.83µs        ? ?/sec    1.00   1455.7±6.64µs        ? ?/sec
physical_plan_clickbench_q8                           1.09   1911.2±7.12µs        ? ?/sec    1.00   1754.4±6.69µs        ? ?/sec
physical_plan_clickbench_q9                           1.10   1879.3±9.38µs        ? ?/sec    1.00   1714.8±5.70µs        ? ?/sec
physical_plan_struct_join_agg_sort                    1.12   1357.2±2.61µs        ? ?/sec    1.00   1216.5±3.99µs        ? ?/sec
physical_plan_tpcds_all                               1.12    732.6±5.68ms        ? ?/sec    1.00    653.4±4.78ms        ? ?/sec
physical_plan_tpch_all                                1.11     48.3±0.12ms        ? ?/sec    1.00     43.6±0.10ms        ? ?/sec
physical_plan_tpch_q1                                 1.13   1589.2±2.98µs        ? ?/sec    1.00   1408.2±3.07µs        ? ?/sec
physical_plan_tpch_q10                                1.11      3.0±0.01ms        ? ?/sec    1.00      2.7±0.00ms        ? ?/sec
physical_plan_tpch_q11                                1.05      2.2±0.00ms        ? ?/sec    1.00      2.1±0.00ms        ? ?/sec
physical_plan_tpch_q12                                1.16   1336.1±4.50µs        ? ?/sec    1.00   1147.8±3.18µs        ? ?/sec
physical_plan_tpch_q13                                1.14   1015.6±3.09µs        ? ?/sec    1.00    892.9±1.91µs        ? ?/sec
physical_plan_tpch_q14                                1.09   1433.6±3.09µs        ? ?/sec    1.00   1310.8±2.86µs        ? ?/sec
physical_plan_tpch_q16                                1.13   1664.2±2.77µs        ? ?/sec    1.00   1476.0±2.22µs        ? ?/sec
physical_plan_tpch_q17                                1.11   1799.0±2.72µs        ? ?/sec    1.00   1613.6±3.53µs        ? ?/sec
physical_plan_tpch_q18                                1.10   1898.0±5.39µs        ? ?/sec    1.00   1731.1±3.64µs        ? ?/sec
physical_plan_tpch_q19                                1.29      2.5±0.02ms        ? ?/sec    1.00  1952.3±13.36µs        ? ?/sec
physical_plan_tpch_q2                                 1.11      4.4±0.02ms        ? ?/sec    1.00      3.9±0.01ms        ? ?/sec
physical_plan_tpch_q20                                1.11      2.4±0.00ms        ? ?/sec    1.00      2.1±0.02ms        ? ?/sec
physical_plan_tpch_q21                                1.11      3.2±0.01ms        ? ?/sec    1.00      2.8±0.01ms        ? ?/sec
physical_plan_tpch_q22                                1.07   1603.0±3.69µs        ? ?/sec    1.00   1495.1±3.45µs        ? ?/sec
physical_plan_tpch_q3                                 1.13      2.0±0.01ms        ? ?/sec    1.00   1794.4±2.23µs        ? ?/sec
physical_plan_tpch_q4                                 1.08   1179.5±5.16µs        ? ?/sec    1.00   1093.7±3.01µs        ? ?/sec
physical_plan_tpch_q5                                 1.09      2.6±0.01ms        ? ?/sec    1.00      2.4±0.01ms        ? ?/sec
physical_plan_tpch_q6                                 1.17    686.5±2.46µs        ? ?/sec    1.00    586.7±2.80µs        ? ?/sec
physical_plan_tpch_q7                                 1.10      3.2±0.01ms        ? ?/sec    1.00      2.9±0.01ms        ? ?/sec
physical_plan_tpch_q8                                 1.08      4.2±0.01ms        ? ?/sec    1.00      3.9±0.01ms        ? ?/sec
physical_plan_tpch_q9                                 1.09      2.9±0.01ms        ? ?/sec    1.00      2.7±0.00ms        ? ?/sec
physical_select_aggregates_from_200                   1.10     14.7±0.06ms        ? ?/sec    1.00     13.4±0.05ms        ? ?/sec
physical_select_all_from_1000                         1.04     17.5±0.08ms        ? ?/sec    1.00     16.8±0.06ms        ? ?/sec
physical_select_one_from_700                          1.00    707.3±3.18µs        ? ?/sec    1.01    717.3±5.13µs        ? ?/sec
physical_sorted_union_order_by_10_int64               1.13      4.7±0.01ms        ? ?/sec    1.00      4.2±0.01ms        ? ?/sec
physical_sorted_union_order_by_10_uint64              1.25     11.6±0.03ms        ? ?/sec    1.00      9.3±0.04ms        ? ?/sec
physical_sorted_union_order_by_50_int64               1.09    113.5±0.34ms        ? ?/sec    1.00    103.9±0.42ms        ? ?/sec
physical_sorted_union_order_by_50_uint64              1.22    620.0±3.34ms        ? ?/sec    1.00    509.1±2.79ms        ? ?/sec
physical_theta_join_consider_sort                     1.03   1036.7±7.14µs        ? ?/sec    1.00   1004.7±3.46µs        ? ?/sec
physical_unnest_to_join                               1.00    610.3±1.84µs        ? ?/sec    1.02    621.7±1.31µs        ? ?/sec
physical_window_function_partition_by_12_on_values    1.08    738.1±2.47µs        ? ?/sec    1.00    682.8±1.46µs        ? ?/sec
physical_window_function_partition_by_30_on_values    1.07   1473.1±2.78µs        ? ?/sec    1.00   1373.2±3.54µs        ? ?/sec
physical_window_function_partition_by_4_on_values     1.07    440.3±2.00µs        ? ?/sec    1.00    410.1±2.38µs        ? ?/sec
physical_window_function_partition_by_7_on_values     1.08    553.1±1.45µs        ? ?/sec    1.00    511.2±1.47µs        ? ?/sec
physical_window_function_partition_by_8_on_values     1.08    592.8±2.40µs        ? ?/sec    1.00    549.3±2.17µs        ? ?/sec
with_param_values_many_columns                        1.06    459.0±2.16µs        ? ?/sec    1.00    432.9±1.73µs        ? ?/sec

Resource Usage

base (merge-base)

Metric Value
Wall time 1240.3s
Peak memory 19.8 GiB
Avg memory 19.7 GiB
CPU user 1483.2s
CPU sys 1.7s
Peak spill 0 B

branch

Metric Value
Wall time 1565.3s
Peak memory 19.8 GiB
Avg memory 19.8 GiB
CPU user 1882.2s
CPU sys 1.5s
Peak spill 0 B

File an issue against this benchmark runner

@adriangb
Copy link
Copy Markdown
Contributor Author

@alamb I know you worry about planning performance, wdyt of this change?

@adriangb adriangb requested a review from alamb May 17, 2026 17:11
@alamb
Copy link
Copy Markdown
Contributor

alamb commented May 18, 2026

ysical_plan_clickbench_q40                          1.11      3.5±0.02ms        ? ?/sec    1.00      3.1±0.02ms        ? ?/sec
physical_plan_clickbench_q41                          1.13      3.0±0.02ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
physical_plan_clickbench_q42                          1.08      3.1±0.01ms        ? ?/sec    1.00      2.9±0.02ms        ? ?/sec
physical_plan_clickbench_q43                          1.09      3.3±0.01ms        ? ?/sec    1.00      3.0±0.02ms        ? ?/sec
physical_plan_clickbench_q44                          1.10   1526.0±9.37µs        ? ?/sec    1.00   1385.8±5.75µs        ? ?/sec
physical_plan_clickbench_q45                          1.10  1541.0±14.71µs        ? ?/sec    1.00  1407.1±12.41µs        ? ?/sec
physical_plan_clickbench_q46                          1.10   1862.1±7.22µs        ? ?/sec    1.00   1689.6±8.06µs        ? ?/sec
physical_plan_clickbench_q47                          1.11      2.6±0.02ms        ? ?/sec    1.00      2.4±0.01ms        ? ?/sec
physical_plan_clickbench_q48                          1.11      2.9±0.02ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
physical_plan_clickbench_q49                          1.10      2.9±0.02ms        ? ?/sec    1.00      2.7±0.01ms        ? ?/sec
physical_plan_clickbench_q5                           1.10   1565.9±5.42µs        ? ?/sec    1.00   1423.0±9.11µs        ? ?/sec
physical_plan_clickbench_q50                          1.14      2.9±0.02ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
physical_plan_clickbench_q51                          1.11   1977.4±6.97µs        ? ?/sec    1.00   1782.7±6.84µs        ? ?/sec
physical_plan_clickbench_q6                           1.08   1564.0±8.40µs        ? ?/sec    1.00   1446.1±6.36µs        ? ?/sec
physical_plan_clickbench_q7                           1.09   1592.7±4.83µs        ? ?/sec    1.00   1455.7±6.64µs        ? ?/sec
physical_plan_clickbench_q8                           1.09   1911.2±7.12µs        ? ?/sec    1.00   1754.4±6.69µs        ? ?/sec
physical_plan_clickbench_q9  

@alamb I know you worry about planning performance, wdyt of this change?

😍 Ok you nerd sniped me -- going to review this one now

@alamb alamb added the performance Make DataFusion faster label May 18, 2026
Copy link
Copy Markdown
Contributor

@alamb alamb left a comment

Choose a reason for hiding this comment

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

TLDR is I think this is great and a really nice idea -- It is also nice it is so localized

As I mentioned in my comments, I was thinking we could expand the scope of this optimization (as a follow on PR) -- maybe we could implement the same/similar thing for Expr, PhysicalExpr and ExecutionPlan (though maybe they already have it)

@neilconway I think was working on something similar in #21749

FYI @joroKr21 as I think this may be related to some work you have been doing

Comment thread datafusion/optimizer/src/optimizer.rs Outdated
///
/// This avoids the `Arc::unwrap_or_clone` + `Arc::new` cycle that the
/// ownership-based `TreeNode::rewrite` performs at every child node.
/// When the `Arc` refcount is 1 (always true in the optimizer),
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.

Why is this always true in the optimizer?

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.

I think it's usually true except for stuff like DynamicFilterPhsyicalExpr. But I'll remove the comment, I don't think it's helpful.

Comment thread datafusion/optimizer/src/optimizer.rs Outdated
/// When the `Arc` refcount is 1 (always true in the optimizer),
/// `Arc::make_mut` is essentially free.
///
/// The `rule.rewrite()` API takes ownership, so we bridge the `&mut` to an
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 is an implementation detail -- I think it belongs next to the code below

let mut changed = false;
if apply_order == ApplyOrder::TopDown {
let owned = std::mem::take(plan);
let result = rule.rewrite(owned, config)?;
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.

If this returns early, the plan is left with the default LogicalPlan -- I think we should make it clear in the comments what the expected semantics are when the rule fails (aka the tree is left in an inconsistent / errored state)

Comment thread datafusion/optimizer/src/optimizer.rs Outdated
}

// Recurse into children using Arc::make_mut (zero-cost when refcount == 1)
changed |= plan.map_children_mut(|child| {
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 wonder if we could eventually consider making a TreeNode API that uses the same trick to mutate the plans in place, rather than forcing a copy

/// traversal is needed. When the plan has no subqueries, the cheaper
/// `rewrite` traversal is sufficient since all plan nodes are reachable
/// via direct children.
fn plan_has_subqueries(plan: &LogicalPlan) -> bool {
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.

it is unfortunate to have to walk the tree twice, but that does seem better than copying it in non subquery cases

It isn't clear to me why we couldn't do a similar "rewrite in place" trick with Expr / PhysicalExprs as well, to avoid the owned rewrite path entirely 🤔

/// When the refcount is >1, it clones the inner value first.
///
/// Returns `Ok(true)` if any child was modified by `f`.
pub fn map_children_mut<F: FnMut(&mut Self) -> Result<bool>>(
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.

It would be great if we could move this into TreeNode eventually

Address review feedback on the in-place optimizer rewrite:

- Document the error contract of `rewrite_plan_in_place`: on `Err` the
  plan is left in an unspecified state because `rule.rewrite()` consumes
  it by value, and explain why it cannot be recovered without the clone
  the function exists to avoid. Note how `Optimizer::optimize` handles it.
- Move the `mem::take` bridge explanation from the doc comment into an
  inline comment next to the code it describes.
- Drop the inaccurate "Arc refcount is 1 is always true" claim.
- Document that `LogicalPlan::map_children_mut` does not roll back
  partial mutations when `f` fails.

Comment-only changes; no behavior change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@adriangb
Copy link
Copy Markdown
Contributor Author

@alamb I've addressed the docs side of things.

Regarding moving into TreeNode: I'm not sure yet this will work for other cases. In particular the dyn cases. To de-risk this work I've moved the new method out of the public API. This PR is now a completely internal implementation, we can work towards public API in a followup.

`map_children_mut` was added as a public method on `LogicalPlan` in
`datafusion-expr` only because the optimizer, in a different crate,
needed to call it. But the optimizer is its sole consumer, and the
`Arc::make_mut` in-place trick does not generalize to the other tree
types (`Expr` children are `Box`ed; `PhysicalExpr`/`ExecutionPlan`
children are `Arc<dyn _>`, which `Arc::make_mut` cannot handle), so
committing to it as public API is not warranted.

Move it into `optimizer.rs` as a private free function next to
`rewrite_plan_in_place`, its only caller. `datafusion-expr` is now
untouched by this PR except for the `map_subqueries` short-circuit, and
the optimizer adds no public API. If `TreeNode` ever grows an in-place
traversal this logic can move there with no breaking change.

No behavior change; the 713 datafusion-optimizer tests pass unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@adriangb
Copy link
Copy Markdown
Contributor Author

@alamb I think it won't be a problem but just FYI I did move map_children_mut to be private. Let me know if you're still good with this and I can send it to merge.

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

Labels

core Core DataFusion crate logical-expr Logical plan and expressions optimizer Optimizer rules performance Make DataFusion faster

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants