Skip to content

Commit b69fe99

Browse files
committed
perf: share one statistics context across EnsureRequirements
Backport of apache#25098 onto the DataDog 55 branch. EnsureRequirements built a fresh StatisticsContext for each child it checked, so statistics for every subtree were computed again at every ancestor. A plan with hundreds of union inputs paid this at each level. The pass now shares one context. The cache is keyed by node pointer, so it is cleared after any node whose plan pointer changed, since a rewrite can free a cached node and a later allocation could reuse its address. The fork's StatisticsContext has no registry support, so the shared context is built with StatisticsContext::new(), the same as the per-child contexts it replaces. The upstream registry test is left out for that reason.
1 parent 0c03aae commit b69fe99

3 files changed

Lines changed: 262 additions & 9 deletions

File tree

‎datafusion/core/tests/physical_optimizer/enforce_distribution.rs‎

Lines changed: 198 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use std::fmt::Debug;
1919
use std::ops::Deref;
2020
use std::sync::Arc;
21+
use std::sync::atomic::{AtomicUsize, Ordering};
2122

2223
use crate::physical_optimizer::test_utils::{
2324
RequirementsTestExec, bounded_window_exec_with_can_repartition, check_integrity,
@@ -37,7 +38,7 @@ use datafusion::datasource::object_store::ObjectStoreUrl;
3738
use datafusion::datasource::physical_plan::{CsvSource, ParquetSource};
3839
use datafusion::datasource::source::DataSourceExec;
3940
use datafusion::prelude::{SessionConfig, SessionContext};
40-
use datafusion_common::ScalarValue;
41+
use datafusion_common::{ScalarValue, Statistics};
4142
use datafusion_common::config::CsvOptions;
4243
use datafusion_common::error::Result;
4344
use datafusion_common::tree_node::{
@@ -636,7 +637,12 @@ fn ensure_distribution_helper(
636637
config.optimizer.repartition_file_scans = false;
637638
config.optimizer.repartition_file_min_size = 1024;
638639
config.optimizer.prefer_existing_sort = prefer_existing_sort;
639-
ensure_distribution(distribution_context, &config).map(|item| item.data.plan)
640+
ensure_distribution_with_stats(
641+
distribution_context,
642+
&config,
643+
&datafusion_physical_plan::statistics::StatisticsContext::new(),
644+
)
645+
.map(|item| item.data.plan)
640646
}
641647

642648
fn test_suite_default_config_options() -> ConfigOptions {
@@ -753,7 +759,11 @@ impl TestConfig {
753759
// Then run ensure_distribution rule
754760
DistributionContext::new_default(adjusted)
755761
.transform_up(|distribution_context| {
756-
ensure_distribution(distribution_context, &self.config)
762+
ensure_distribution_with_stats(
763+
distribution_context,
764+
&self.config,
765+
&datafusion_physical_plan::statistics::StatisticsContext::new(),
766+
)
757767
})
758768
.data()
759769
.and_then(check_integrity)?;
@@ -4597,3 +4607,188 @@ fn ensure_distribution_reuses_plan_arc_when_no_redistribution_needed() -> Result
45974607
);
45984608
Ok(())
45994609
}
4610+
4611+
/// Single-child pass-through whose `statistics_from_inputs` increments a counter
4612+
/// every time it is actually computed (i.e. on a statistics-cache miss). Used to
4613+
/// observe how often `ensure_distribution` recomputes a node's statistics.
4614+
#[derive(Debug)]
4615+
struct CountingStatsExec {
4616+
input: Arc<dyn ExecutionPlan>,
4617+
cache: Arc<PlanProperties>,
4618+
calls: Arc<AtomicUsize>,
4619+
}
4620+
4621+
impl CountingStatsExec {
4622+
fn new(input: Arc<dyn ExecutionPlan>, calls: Arc<AtomicUsize>) -> Self {
4623+
let cache = PlanProperties::new(
4624+
input.equivalence_properties().clone(),
4625+
input.output_partitioning().clone(),
4626+
input.pipeline_behavior(),
4627+
input.boundedness(),
4628+
);
4629+
Self {
4630+
input,
4631+
cache: Arc::new(cache),
4632+
calls,
4633+
}
4634+
}
4635+
}
4636+
4637+
impl DisplayAs for CountingStatsExec {
4638+
fn fmt_as(
4639+
&self,
4640+
_t: DisplayFormatType,
4641+
f: &mut std::fmt::Formatter,
4642+
) -> std::fmt::Result {
4643+
write!(f, "CountingStatsExec")
4644+
}
4645+
}
4646+
4647+
impl ExecutionPlan for CountingStatsExec {
4648+
fn name(&self) -> &'static str {
4649+
"CountingStatsExec"
4650+
}
4651+
4652+
fn properties(&self) -> &Arc<PlanProperties> {
4653+
&self.cache
4654+
}
4655+
4656+
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
4657+
vec![&self.input]
4658+
}
4659+
4660+
fn replace_children(
4661+
self: Arc<Self>,
4662+
mut children: Vec<Arc<dyn ExecutionPlan>>,
4663+
_: ReplaceChildrenOptions,
4664+
) -> Result<Arc<dyn ExecutionPlan>> {
4665+
assert_eq!(children.len(), 1);
4666+
Ok(Arc::new(Self::new(
4667+
children.pop().unwrap(),
4668+
Arc::clone(&self.calls),
4669+
)))
4670+
}
4671+
4672+
fn with_new_children(
4673+
self: Arc<Self>,
4674+
children: Vec<Arc<dyn ExecutionPlan>>,
4675+
) -> Result<Arc<dyn ExecutionPlan>> {
4676+
self.replace_children(
4677+
children,
4678+
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
4679+
)
4680+
}
4681+
4682+
fn apply_expressions(
4683+
&self,
4684+
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
4685+
) -> Result<TreeNodeRecursion> {
4686+
Ok(TreeNodeRecursion::Continue)
4687+
}
4688+
4689+
fn execute(
4690+
&self,
4691+
_partition: usize,
4692+
_context: Arc<datafusion::execution::context::TaskContext>,
4693+
) -> Result<datafusion_physical_plan::SendableRecordBatchStream> {
4694+
unreachable!();
4695+
}
4696+
4697+
fn statistics_from_inputs(
4698+
&self,
4699+
_input_stats: &[Arc<Statistics>],
4700+
_args: &datafusion_physical_plan::statistics::StatisticsArgs,
4701+
) -> Result<Arc<Statistics>> {
4702+
self.calls.fetch_add(1, Ordering::Relaxed);
4703+
Ok(Arc::new(Statistics::new_unknown(
4704+
self.input.schema().as_ref(),
4705+
)))
4706+
}
4707+
}
4708+
4709+
/// Regression test for the shared statistics cache in `ensure_distribution`.
4710+
///
4711+
/// A deep stack of pass-through operators sits over a counting leaf. Each
4712+
/// ancestor's distribution enforcement inspects its child's statistics, which
4713+
/// recurse to the leaf. With one `StatisticsContext` shared across the pass the
4714+
/// leaf is computed once; with a fresh context per node it is recomputed once
4715+
/// per ancestor. This directly detects a regression where the cache is not
4716+
/// actually shared (e.g. reset on every node), which no plan-output assertion
4717+
/// can catch because the optimized plan is identical either way.
4718+
#[test]
4719+
fn ensure_distribution_shares_statistics_cache() -> Result<()> {
4720+
// Count how many times a leaf's statistics are computed over a stack of
4721+
// `depth` pass-through operators sitting on top of it. Each ancestor's
4722+
// distribution enforcement inspects its child's statistics, which recurse to
4723+
// the leaf.
4724+
//
4725+
// The measured arm drives the real `EnsureRequirements` rule, so the sharing
4726+
// and the cache-reset condition under test are the ones the rule actually
4727+
// uses — reimplementing them here would keep passing even if the rule
4728+
// stopped sharing. The baseline arm allocates a fresh `StatisticsContext`
4729+
// per node, reproducing the behavior before this change.
4730+
fn deep_plan(depth: usize, calls: &Arc<AtomicUsize>) -> Arc<dyn ExecutionPlan> {
4731+
let mut plan: Arc<dyn ExecutionPlan> =
4732+
Arc::new(CountingStatsExec::new(parquet_exec(), Arc::clone(calls)));
4733+
for _ in 0..depth {
4734+
plan = filter_exec(plan);
4735+
}
4736+
plan
4737+
}
4738+
4739+
fn config() -> ConfigOptions {
4740+
let mut config = ConfigOptions::new();
4741+
config.execution.target_partitions = 10;
4742+
// Keep the plan a fixpoint so no node is rebuilt and the shared cache is
4743+
// never reset; statistics are still computed for the round-robin decision.
4744+
config.optimizer.enable_round_robin_repartition = false;
4745+
config
4746+
}
4747+
4748+
/// Leaf statistics computations performed by the real rule.
4749+
fn via_rule(depth: usize) -> Result<usize> {
4750+
let calls = Arc::new(AtomicUsize::new(0));
4751+
EnsureRequirements::new().optimize(deep_plan(depth, &calls), &config())?;
4752+
Ok(calls.load(Ordering::Relaxed))
4753+
}
4754+
4755+
/// Leaf statistics computations with a fresh context per node.
4756+
fn per_node_context(depth: usize) -> Result<usize> {
4757+
let calls = Arc::new(AtomicUsize::new(0));
4758+
let config = config();
4759+
DistributionContext::new_default(deep_plan(depth, &calls)).transform_up(
4760+
|ctx| {
4761+
ensure_distribution_with_stats(
4762+
ctx,
4763+
&config,
4764+
&datafusion_physical_plan::statistics::StatisticsContext::new(),
4765+
)
4766+
},
4767+
)?;
4768+
Ok(calls.load(Ordering::Relaxed))
4769+
}
4770+
4771+
let (shared_shallow, fresh_shallow) = (via_rule(4)?, per_node_context(4)?);
4772+
let (shared_deep, fresh_deep) = (via_rule(12)?, per_node_context(12)?);
4773+
4774+
// Sharing strictly reduces statistics recomputation at any depth. A rule that
4775+
// stopped sharing (or reset the cache on every node) would make these equal.
4776+
assert!(
4777+
shared_shallow < fresh_shallow && shared_deep < fresh_deep,
4778+
"shared cache must recompute less: shallow {shared_shallow} vs {fresh_shallow}, \
4779+
deep {shared_deep} vs {fresh_deep}"
4780+
);
4781+
4782+
// Without sharing, each extra ancestor recomputes the leaf's subtree, so the
4783+
// gap widens as the plan gets deeper. That is the depth-scaling recomputation
4784+
// the shared cache removes.
4785+
let saved_shallow = fresh_shallow - shared_shallow;
4786+
let saved_deep = fresh_deep - shared_deep;
4787+
assert!(
4788+
saved_deep > saved_shallow,
4789+
"the shared cache should save more on deeper plans: \
4790+
saved {saved_shallow} at depth 4, {saved_deep} at depth 12"
4791+
);
4792+
4793+
Ok(())
4794+
}

‎datafusion/physical-optimizer/src/ensure_requirements/enforce_distribution.rs‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,7 @@ fn get_repartition_requirement_status(
983983
plan: &Arc<dyn ExecutionPlan>,
984984
batch_size: usize,
985985
should_use_estimates: bool,
986+
stats_ctx: &StatisticsContext,
986987
) -> Result<Vec<RepartitionRequirementStatus>> {
987988
let mut needs_alignment = false;
988989
let children = plan.children();
@@ -994,7 +995,7 @@ fn get_repartition_requirement_status(
994995
{
995996
// Decide whether adding a round robin is beneficial depending on
996997
// the statistical information we have on the number of rows:
997-
let roundrobin_beneficial_stats = match StatisticsContext::new()
998+
let roundrobin_beneficial_stats = match stats_ctx
998999
.compute(child.as_ref(), &StatisticsArgs::new())?
9991000
.num_rows
10001001
{
@@ -1123,6 +1124,23 @@ fn enforce_distribution_relationships(
11231124
}
11241125
}
11251126

1127+
/// Deprecated in favour of [`ensure_distribution_with_stats`].
1128+
///
1129+
/// This entry point allocates a fresh [`StatisticsContext`] per call, so a
1130+
/// bottom-up traversal recomputes each shared subtree's statistics once per
1131+
/// ancestor. Pass one context through the whole walk instead — see
1132+
/// [`ensure_distribution_with_stats`].
1133+
#[deprecated(
1134+
since = "56.0.0",
1135+
note = "use `ensure_distribution_with_stats` and share one `StatisticsContext` across the traversal"
1136+
)]
1137+
pub fn ensure_distribution(
1138+
dist_context: DistributionContext,
1139+
config: &ConfigOptions,
1140+
) -> Result<Transformed<DistributionContext>> {
1141+
ensure_distribution_with_stats(dist_context, config, &StatisticsContext::new())
1142+
}
1143+
11261144
/// This function checks whether we need to add additional data exchange
11271145
/// operators to satisfy distribution requirements. Since this function
11281146
/// takes care of such requirements, we should avoid manually adding data
@@ -1131,13 +1149,21 @@ fn enforce_distribution_relationships(
11311149
/// This function is intended to be used in a bottom up traversal, as it
11321150
/// can first repartition (or newly partition) at the datasources -- these
11331151
/// source partitions may be later repartitioned with additional data exchange operators.
1152+
///
1153+
/// `stats_ctx` carries the memoization cache used to answer the child
1154+
/// statistics queries behind the repartition decisions. Share one context
1155+
/// across the whole traversal so each subtree is computed once rather than
1156+
/// once per ancestor. The cache is keyed by raw plan-node pointers, so reset
1157+
/// it (via [`StatisticsContext::reset_cache`]) after any node whose plan
1158+
/// pointer actually changed.
11341159
#[expect(
11351160
deprecated,
11361161
reason = "HashPartitioned is accepted during the KeyPartitioned migration"
11371162
)]
1138-
pub fn ensure_distribution(
1163+
pub fn ensure_distribution_with_stats(
11391164
dist_context: DistributionContext,
11401165
config: &ConfigOptions,
1166+
stats_ctx: &StatisticsContext,
11411167
) -> Result<Transformed<DistributionContext>> {
11421168
let dist_context = update_children(dist_context)?;
11431169

@@ -1233,8 +1259,12 @@ pub fn ensure_distribution(
12331259
|| plan.is::<SortMergeJoinExec>();
12341260

12351261
let input_distributions = plan.input_distribution_requirements();
1236-
let repartition_status_flags =
1237-
get_repartition_requirement_status(&plan, batch_size, should_use_estimates)?;
1262+
let repartition_status_flags = get_repartition_requirement_status(
1263+
&plan,
1264+
batch_size,
1265+
should_use_estimates,
1266+
stats_ctx,
1267+
)?;
12381268
// This loop iterates over all the children to:
12391269
// - Increase parallelism for every child if it is beneficial.
12401270
// - Satisfy the distribution requirements of every child, if it is not

‎datafusion/physical-optimizer/src/ensure_requirements/mod.rs‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,13 @@ pub mod enforce_sorting;
148148
use std::sync::Arc;
149149

150150
use crate::PhysicalOptimizerRule;
151+
use crate::optimizer::{ConfigOnlyContext, PhysicalOptimizerContext};
151152

152153
use datafusion_common::Result;
153154
use datafusion_common::config::ConfigOptions;
154155
use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
155156
use datafusion_physical_plan::ExecutionPlan;
157+
use datafusion_physical_plan::statistics::StatisticsContext;
156158

157159
/// Optimizer rule that enforces both distribution and sorting requirements.
158160
///
@@ -178,6 +180,15 @@ impl PhysicalOptimizerRule for EnsureRequirements {
178180
plan: Arc<dyn ExecutionPlan>,
179181
config: &ConfigOptions,
180182
) -> Result<Arc<dyn ExecutionPlan>> {
183+
self.optimize_with_context(plan, &ConfigOnlyContext::new(config))
184+
}
185+
186+
fn optimize_with_context(
187+
&self,
188+
plan: Arc<dyn ExecutionPlan>,
189+
context: &dyn PhysicalOptimizerContext,
190+
) -> Result<Arc<dyn ExecutionPlan>> {
191+
let config = context.config_options();
181192
// Phase 1: Join key reordering (top-down, from EnforceDistribution)
182193
use super::enforce_distribution::{
183194
PlanWithKeyRequirements, adjust_input_keys_ordering,
@@ -194,13 +205,30 @@ impl PhysicalOptimizerRule for EnsureRequirements {
194205

195206
// Phase 2: Combined distribution + sorting enforcement (single bottom-up pass)
196207
// For each node: distribution first, then sorting.
197-
use super::enforce_distribution::{DistributionContext, ensure_distribution};
208+
use super::enforce_distribution::{
209+
DistributionContext, ensure_distribution_with_stats,
210+
};
198211
use super::enforce_sorting::{PlanWithCorrespondingSort, ensure_sorting};
199212

200213
// Step 2a: Distribution enforcement (bottom-up)
201214
let dist_ctx = DistributionContext::new_default(plan);
215+
// Share one statistics context across the whole distribution pass so each
216+
// subtree's statistics are computed once instead of once per ancestor.
217+
// `StatsCache` is keyed by raw node pointer, so reset it after any node
218+
// whose plan pointer actually changed: a rewrite can free a cached node
219+
// and a later allocation could reuse its address. A node that makes no
220+
// change cannot free anything, so the cache safely persists across the
221+
// no-op nodes that dominate a deep plan.
222+
let stats_ctx = StatisticsContext::new();
202223
let dist_ctx = dist_ctx
203-
.transform_up(|ctx| ensure_distribution(ctx, config))
224+
.transform_up(|ctx| {
225+
let before = Arc::clone(&ctx.plan);
226+
let result = ensure_distribution_with_stats(ctx, config, &stats_ctx)?;
227+
if !Arc::ptr_eq(&before, &result.data.plan) {
228+
stats_ctx.reset_cache();
229+
}
230+
Ok(result)
231+
})
204232
.data()?;
205233

206234
// Step 2b: Sorting enforcement (bottom-up) — runs on distribution-fixed plan

0 commit comments

Comments
 (0)