alamb commented on code in PR #21815:
URL: https://github.com/apache/datafusion/pull/21815#discussion_r3375696120


##########
datafusion/physical-plan/src/statistics.rs:
##########
@@ -0,0 +1,168 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Statistics computation for physical plans.
+//!
+//! [`StatisticsArgs`] provides external context to
+//! [`ExecutionPlan::statistics_with_args`].
+
+use crate::ExecutionPlan;
+use datafusion_common::{Result, Statistics, assert_or_internal_err};
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// Per-call memoization cache for statistics computation.
+///
+/// Keyed by `(plan node pointer address, partition)`. Shared across
+/// a single statistics walk via [`StatisticsArgs`].
+///
+/// The pointer-based key is safe within a single synchronous walk:
+/// all `Arc<dyn ExecutionPlan>` nodes are held by the plan tree for
+/// the duration of the walk, so addresses cannot be reused.
+#[derive(Debug, Default)]
+struct StatsCache(HashMap<(usize, Option<usize>), Arc<Statistics>>);
+
+impl StatsCache {
+    fn get(
+        &self,
+        plan: &dyn ExecutionPlan,
+        partition: Option<usize>,
+    ) -> Option<&Arc<Statistics>> {
+        let key = (
+            plan as *const dyn ExecutionPlan as *const () as usize,
+            partition,
+        );
+        self.0.get(&key)
+    }
+
+    fn insert(
+        &mut self,
+        plan: &dyn ExecutionPlan,
+        partition: Option<usize>,
+        stats: Arc<Statistics>,
+    ) {
+        let key = (
+            plan as *const dyn ExecutionPlan as *const () as usize,
+            partition,
+        );
+        self.0.insert(key, stats);
+    }
+}
+
+/// Arguments passed to [`ExecutionPlan::statistics_with_args`] carrying
+/// external information that operators can use when computing their
+/// statistics.
+#[derive(Debug)]
+pub struct StatisticsArgs {
+    partition: Option<usize>,
+    /// Shared memoization cache for the current statistics walk.
+    cache: Rc<RefCell<StatsCache>>,
+}
+
+impl StatisticsArgs {
+    /// Creates new statistics arguments with a fresh cache.
+    pub fn new(partition: Option<usize>) -> Self {

Review Comment:
   I think we can make this API a little easier to use / more ergonomic -- here 
is a proposal for your consideration:
   - https://github.com/asolimando/datafusion/pull/1
   
   By making partition optional I think it makes the callsites that do set it 
clearer and will make it easier to extend this structure going forward. 



##########
datafusion/ffi/src/execution_plan.rs:
##########
@@ -209,6 +209,7 @@ unsafe extern "C" fn partition_statistics_fn_wrapper(
     partition: FFI_Option<usize>,
 ) -> FFI_Result<SVec<u8>> {
     let partition: Option<usize> = partition.into();
+    #[expect(deprecated)]

Review Comment:
   Claude caught that this call would be dangerous for people who had correctly 
updated their plans: it would still call the old `partition_statistics` 
implementation
   - https://github.com/asolimando/datafusion/pull/2



##########
datafusion/physical-plan/src/execution_plan.rs:
##########
@@ -563,6 +566,22 @@ pub trait ExecutionPlan: Any + Debug + DisplayAs + Send + 
Sync {
         Ok(Arc::new(Statistics::new_unknown(&self.schema())))
     }
 
+    /// Returns statistics for a specific partition of this `ExecutionPlan` 
node.
+    /// If statistics are not available, should return 
[`Statistics::new_unknown`]
+    /// (the default), not an error.
+    /// If `partition` is `None`, it returns statistics for the entire plan.
+    ///
+    /// [`StatisticsArgs`] carries the partition index, pre-computed child
+    /// statistics, and a shared cache. See [`compute_statistics`] for the
+    /// top-level entry point that builds the args automatically.
+    ///
+    /// [`StatisticsArgs`]: crate::statistics_context::StatisticsArgs
+    /// [`compute_statistics`]: crate::statistics_context::compute_statistics
+    fn statistics_with_args(&self, args: &StatisticsArgs) -> 
Result<Arc<Statistics>> {
+        #[expect(deprecated)]
+        self.partition_statistics(args.partition())

Review Comment:
   I guess I was thinking we could make it
   ```rust
       fn statistics_with_args(&self, args: &StatisticsArgs) -> 
Result<Arc<Statistics>> {
         if let Some(idx) = args.partition() {
               // Validate partition index
               let partition_count = 
self.properties().partitioning.partition_count();
               assert_or_internal_err!(
                   idx < partition_count,
                   "Invalid partition index: {}, the partition count is {}",
                   idx,
                   partition_count
               );
           }
           Ok(Arc::new(Statistics::new_unknown(&self.schema())))
       }
   ```
   
   (aka literally copy/paste the implementation of partition_statistics inline)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to