Skip to content

Conversation

@askalt
Copy link
Contributor

@askalt askalt commented Jan 13, 2026

This patch aims to implement a fast-path for the ExecutionPlan::with_new_children function for some plans, moving closer to a physical plan re-use implementation and improving planning performance. If the passed children properties are the same as in self, we do not actually recompute self's properties (which could be costly if projection mapping is required). Instead, we just replace the children and re-use self's properties as-is.

To be able to compare two different properties -- ExecutionPlan::properties(...) signature is modified and now returns &Arc<PlanProperties>. If children properties are the same in with_new_children -- we clone our properties arc and then a parent plan will consider our properties as unchanged, doing the same.

Also, there are other improvenets, all changes:

  • Return &Arc<PlanProperties> from ExecutionPlan::properties(...) instead of a reference.
  • Implement with_new_children fast-path if there is no children properties changes for all
    major plans.
  • Store Arc<[usize]> instead of vector within FilterExec.
  • Store Arc<[usize]> instead of vector within projection of HashJoinExec.
  • Store Arc<[Arc<AggregateFunctionExpr>]> instead of vec for aggr expr and filters.
  • Store Arc<[ProjectionExpr]> instead of vec in ProjectionExprs` struct.
  • Get Option<&[usize]> instead of option vec ref in project_schema -- it makes API
    more flexible.

Note: currently, reset_plan_states does not allow to re-use plan in general: it is not
supported for dynamic filters and recursive queries features, as in this case state reset
should update pointers in the children plans.

@github-actions github-actions bot added documentation Improvements or additions to documentation physical-expr Changes to the physical-expr crates optimizer Optimizer rules core Core DataFusion crate catalog Related to the catalog crate common Related to common crate proto Related to proto crate datasource Changes to the datasource crate ffi Changes to the ffi crate physical-plan Changes to the physical-plan crate labels Jan 13, 2026
@askalt askalt changed the title add fast-path for with_new_children Draft: add fast-path for with_new_children Jan 13, 2026
@askalt askalt marked this pull request as draft January 13, 2026 14:26
@askalt askalt force-pushed the askalt/with_new_children_fast_path branch from 72ff575 to 796f731 Compare January 13, 2026 15:20
@askalt
Copy link
Contributor Author

askalt commented Jan 13, 2026

Also added a typical analytical query plan re-usage benchmark. On the main branch it runs ~4-5 ms when at this MR it spends ~100us.

$ cargo bench  --profile=release-nonlto   --bench plan_reuse

@askalt askalt force-pushed the askalt/with_new_children_fast_path branch from 796f731 to 5601c4f Compare January 13, 2026 15:24
@alamb
Copy link
Contributor

alamb commented Jan 13, 2026

I filed a ticket to track this idea

@alamb
Copy link
Contributor

alamb commented Jan 13, 2026

run benchmark sql_planner

@alamb-ghbot
Copy link

🤖 ./gh_compare_branch_bench.sh compare_branch_bench.sh Running
Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
Comparing askalt/with_new_children_fast_path (5601c4f) to 4c67d02 diff
BENCH_NAME=sql_planner
BENCH_COMMAND=cargo bench --features=parquet --bench sql_planner
BENCH_FILTER=
BENCH_BRANCH_NAME=askalt_with_new_children_fast_path
Results will be posted here when complete

@alamb
Copy link
Contributor

alamb commented Jan 13, 2026

Also added a typical analytical query plan re-usage benchmark. On the main branch it runs ~4-5 ms when at this MR it spends ~100us.

$ cargo bench  --profile=release-nonlto   --bench plan_reuse

Could you move the plan_reuse benchmark into its own PR (as I think it is valuable both for this PR and others, and it makes it easier to automatically compare performance)

@alamb-ghbot
Copy link

Benchmark script failed with exit code 101.

Last 10 lines of output:

Click to expand
                        time:   [5.6457 ms 5.6877 ms 5.7286 ms]

Benchmarking physical_plan_clickbench_q50
Benchmarking physical_plan_clickbench_q50: Warming up for 3.0000 s

thread 'main' (3793320) panicked at datafusion/core/benches/sql_planner.rs:62:14:
called `Result::unwrap()` on an `Err` value: Context("type_coercion", Internal("Expect TypeSignatureClass::Native(LogicalType(Native(String), String)) but received NativeType::Binary, DataType: BinaryView"))
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

error: bench failed, to rerun pass `-p datafusion --bench sql_planner`

@askalt
Copy link
Contributor Author

askalt commented Jan 14, 2026

Also added a typical analytical query plan re-usage benchmark. On the main branch it runs ~4-5 ms when at this MR it spends ~100us.

$ cargo bench  --profile=release-nonlto   --bench plan_reuse

Could you move the plan_reuse benchmark into its own PR (as I think it is valuable both for this PR and others, and it makes it easier to automatically compare performance)

Done in #19806

@askalt askalt force-pushed the askalt/with_new_children_fast_path branch from 5601c4f to 99cf634 Compare January 14, 2026 10:32
@askalt
Copy link
Contributor Author

askalt commented Jan 14, 2026

Benchmark script failed with exit code 101.

Last 10 lines of output:

Click to expand

The same panic on 4c67d02

Created an issue for it: #19809

@askalt askalt force-pushed the askalt/with_new_children_fast_path branch from 99cf634 to b81dd66 Compare January 14, 2026 14:49
Copy link
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.

Thanks @askalt -- this is quite clever and I think it looks very promising

I also think we may be able to potentially make with_new_children even faster by checking the children as well -- and if they are the same there is no reason to recompute everything either.

However, this likely won't help your usecase as the children will likely change (their states need to be reset) 🤔

db: CustomDataSource,
projected_schema: SchemaRef,
cache: PlanProperties,
cache: Arc<PlanProperties>,
Copy link
Contributor

Choose a reason for hiding this comment

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

💯 for this change

mut children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
if has_same_children_properties(&self, &children)? {
// Avoid properties re-computation.
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we coulda avoid even more copying / cloning in the common case using Arc::make_mut https://doc.rust-lang.org/std/sync/struct.Arc.html#method.make_mut

Something like

        if has_same_children_properties(&self, &children)? {
            // Avoid properties re-computation.
            let me = Arc::make_mut(&mut self);
            me.input = children.swap_remove(0);
            me.metrics = ExecutionPlanMetricsSet::new();
            return Ok(self);
        }

Copy link
Contributor

Choose a reason for hiding this comment

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

Now that I write that, I wonder if we could use make_mut to avoid lots of cloning in general 🤔

We could check if the new children are the same as the existing children and if so return self 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It seems we already check it explicitly in DynTreeNode implementation:

with_new_children_if_necessary(arc_self, new_children)

pub fn with_new_children_if_necessary(

@askalt askalt force-pushed the askalt/with_new_children_fast_path branch from b81dd66 to 741b085 Compare January 15, 2026 11:48
@askalt askalt marked this pull request as ready for review January 15, 2026 11:49
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
check_if_same_properties!(self, children);
Copy link
Contributor Author

@askalt askalt Jan 15, 2026

Choose a reason for hiding this comment

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

Fast-path is currently implemented for most plans. It seems quite odd to me that we need to ensure it's implemented for every plan (if at least one plan doesn't implement this check and recalculates its properties, then recalculation will be performed for all parent plans). I've reduced the required code as much as possible: a plan implementer needs to call the added macro and implement the with_new_children_and_same_properties(...) method for the plan.

@askalt askalt changed the title Draft: add fast-path for with_new_children add fast-path for with_new_children Jan 15, 2026
@alamb
Copy link
Contributor

alamb commented Jan 15, 2026

This PR seems to have accumulated some conflicts

@alamb
Copy link
Contributor

alamb commented Jan 15, 2026

I plan to run the newly introduced benchmark in #19806

I suspect we'll see quite a nice improvement

This patch aims to implement a fast-path for the ExecutionPlan::with_new_children function
for some plans, moving closer to a physical plan re-use implementation and improving planning
performance. If the passed children properties are the same as in self, we do not actually
recompute self's properties  (which could be costly if projection mapping is required).
Instead, we just replace the children and re-use self's properties as-is.

To be able to compare two different properties -- ExecutionPlan::properties(...) signature
is modified and now returns `&Arc<PlanProperties>`. If `children` properties are the same
in `with_new_children` -- we clone our properties arc and then a parent plan will consider
our properties as unchanged, doing the same.

Also, there are other improvements. The patch includes the following changes:

- Return `&Arc<PlanProperties>` from `ExecutionPlan::properties(...)` instead of a reference.
- Implement `with_new_children` fast-path if there is no children properties changes for all
  major plans.
- Store `Arc<[usize]>` instead of vector within `FilterExec`.
- Store `Arc<[usize]>` instead of vector within projection of `HashJoinExec`.
- Store `Arc<[Arc<AggregateFunctionExpr>]>` instead of vec for aggr expr and filters.
- Store `Arc<[ProjectionExpr]> instead of vec in `ProjectionExprs` struct.
- Get `Option<&[usize]>` instead of option vec ref in `project_schema` -- it makes API
  more flexible.

Note: currently, `reset_plan_states` does not allow to re-use plan in general: it is not
supported for dynamic filters and recursive queries features, as in this case state reset
should update pointers in the children plans.

Closes apache#19796
@askalt askalt force-pushed the askalt/with_new_children_fast_path branch from 741b085 to 21b8a3f Compare January 15, 2026 18:22
@alamb
Copy link
Contributor

alamb commented Jan 15, 2026

run benchmark reset_plan_states

@alamb-ghbot
Copy link

🤖 ./gh_compare_branch_bench.sh compare_branch_bench.sh Running
Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
Comparing askalt/with_new_children_fast_path (21b8a3f) to 094e7ee diff
BENCH_NAME=reset_plan_states
BENCH_COMMAND=cargo bench --features=parquet --bench reset_plan_states
BENCH_FILTER=
BENCH_BRANCH_NAME=askalt_with_new_children_fast_path
Results will be posted here when complete

@alamb-ghbot
Copy link

🤖: Benchmark completed

Details

group     askalt_with_new_children_fast_path     main
-----     ----------------------------------     ----
query1    1.00      2.6±0.01µs        ? ?/sec    14935.96    39.4±0.71ms        ? ?/sec
query2    1.00      3.3±0.06µs        ? ?/sec    3184.28    10.4±0.14ms        ? ?/sec
query3    1.00    980.0±9.64ns        ? ?/sec    15606.83    15.3±0.41ms        ? ?/sec

@alamb alamb mentioned this pull request Jan 15, 2026
@alamb
Copy link
Contributor

alamb commented Jan 15, 2026

group     askalt_with_new_children_fast_path     main
-----     ----------------------------------     ----
query1    1.00      2.6±0.01µs        ? ?/sec    14935.96    39.4±0.71ms        ? ?/sec
query2    1.00      3.3±0.06µs        ? ?/sec    3184.28    10.4±0.14ms        ? ?/sec
query3    1.00    980.0±9.64ns        ? ?/sec    15606.83    15.3±0.41ms        ? ?/sec

That is pretty amazing (3000x-15000x performance improvement 👍 )

I am also testing sql_planner time using

@alamb alamb changed the title add fast-path for with_new_children Cache PlanProperties, add fast-path for with_new_children Jan 15, 2026
@alamb alamb added the api change Changes the API exposed to users of the crate label Jan 15, 2026
Copy link
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.

Thank you @askalt

I went through this carefully -- I think the basic idea is great and we should proceed.

The only thing I think we should try and do is minimize the impact of the API changes when people upgrade. I have some thoughts on that below

For next steps, I suggest break this PR down into smaller parts (it is quite challenging to review all the changes now). Some ideas on relevant chunks:

  1. Change ExecutionPlan::properties to return an &Arc<Properties> and the necessary plumbing changes
  2. Changes to FilterExec to avoid cloning project
  3. Changes to AggregateExec to avoid cloning the vec / exprs
  4. Changes to the various join operations to avoid cloning the projections

thoughts on reducing upgrade impact

Since this PR does change some core APIs, think we need to be careful.

  1. I think we can avoid the need to change Schema::project, see askalt#2 for my proposal
  2. We should figure out some way to make FilterExec::with_projection easier to use -- the new signature is pretty awkward.

Maybe we can use ProjectionExprs or something like

struct SharedProjection {
  Arc<[usize]> 
}

impl From<Vec<usize>> for SharedProjection {
  ...
}

And then have FilterExec take

pub fn fn with_projection(mut self, projection impl Into<SharedProjection>)

With enough comments I think this could be clear and would also be backwards compatible

/// This information is available via methods on [`ExecutionPlanProperties`]
/// trait, which is implemented for all `ExecutionPlan`s.
fn properties(&self) -> &PlanProperties;
fn properties(&self) -> &Arc<PlanProperties>;
Copy link
Contributor

Choose a reason for hiding this comment

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

This is technically a breaking API change, so it should be documented in the upgrading.md guide:
https://github.com/apache/datafusion/blob/main/docs/source/library-user-guide/upgrading.md

Per the policy in
https://datafusion.apache.org/contributor-guide/api-health.html

I am happy to help write such an entry

pub fn project_schema(
schema: &SchemaRef,
projection: Option<&Vec<usize>>,
projection: Option<&[usize]>,
Copy link
Contributor

Choose a reason for hiding this comment

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

this is also technically a public API change, but I think it just relaxes the constraints (you can still pass in a &Vec so all downstream code should continue to work

name: String,
plan: FFI_ExecutionPlan,
properties: PlanProperties,
properties: Arc<PlanProperties>,
Copy link
Contributor

Choose a reason for hiding this comment

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

since the FFI is supposed to be a stable boundary, I think we shouldn't change this (and instead just copy the properties when needed)

So I suggest reverting this change

self.aggr_expr.clone(),
self.filter_expr.clone(),
Arc::clone(&children[0]),
self.aggr_expr.to_vec(),
Copy link
Contributor

Choose a reason for hiding this comment

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

we might be able to avoid these clones too by changing the signature of AggregateExec 🤔

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

Labels

api change Changes the API exposed to users of the crate catalog Related to the catalog crate common Related to common crate core Core DataFusion crate datasource Changes to the datasource crate documentation Improvements or additions to documentation ffi Changes to the ffi crate optimizer Optimizer rules physical-expr Changes to the physical-expr crates physical-plan Changes to the physical-plan crate proto Related to proto crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Avoid recomputing PlanProperties redundently

3 participants