1818use std:: fmt:: Debug ;
1919use std:: ops:: Deref ;
2020use std:: sync:: Arc ;
21+ use std:: sync:: atomic:: { AtomicUsize , Ordering } ;
2122
2223use 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;
3738use datafusion:: datasource:: physical_plan:: { CsvSource , ParquetSource } ;
3839use datafusion:: datasource:: source:: DataSourceExec ;
3940use datafusion:: prelude:: { SessionConfig , SessionContext } ;
40- use datafusion_common:: ScalarValue ;
41+ use datafusion_common:: { ScalarValue , Statistics } ;
4142use datafusion_common:: config:: CsvOptions ;
4243use datafusion_common:: error:: Result ;
4344use 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
642648fn 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+ }
0 commit comments