alamb commented on code in PR #21815:
URL: https://github.com/apache/datafusion/pull/21815#discussion_r3290848057
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -90,49 +90,41 @@ use distributor_channels::{
/// # Batch Flow with Spilling
///
/// ```text
-/// Input Stream ◀──────┐
-/// │ │
-/// ▼ │
-/// Partition Logic │
-/// │ `batch_size` not
-/// ▼ reached yet
-/// Coalesce Batch │
-/// ┌───────────────┴────────────────┘
-/// ▼
-/// `batch_size` reached
-/// │
-/// └───────────────┐
-/// ▼
-/// try_grow()
-/// ┌───────────────┴────────────────┐
-/// ▼ ▼
-/// try_grow() succeeds try_grow() fails
-/// (Memory Available) (Memory Pressure)
-/// │ │
-/// ▼ ▼
-/// RepartitionBatch::Memory spill_writer.push_batch()
-/// (batch held in memory) (batch written to disk)
-/// │ │
-/// │ ▼
-/// │ RepartitionBatch::Spilled
-/// │ (marker - no batch data)
-/// └──────────────┬─────────────────┘
-/// │
-/// ▼
-/// Send to channel
-/// │
-/// ▼
-/// Output Stream (poll)
-/// │
-/// ┌──────────────┴────────────────┐
-/// ▼ ▼
-/// RepartitionBatch::Memory RepartitionBatch::Spilled
-/// Return batch immediately Poll spill_stream (blocks)
-/// └─────────────┬─────────────────┘
-/// │
-/// ▼
-/// Return batch
-/// (FIFO order preserved)
+/// Input Stream ──▶ Partition Logic ──▶ try_grow()
Review Comment:
why this change?
##########
datafusion/physical-plan/src/statistics_context.rs:
##########
@@ -0,0 +1,213 @@
+// 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.
+
+//! Context for computing statistics in physical plans.
+//!
+//! [`StatisticsArgs`] provides external context to
+//! [`ExecutionPlan::statistics_with_args`], enabling operators to look up
+//! pre-computed child statistics via a shared cache.
+
+use crate::ExecutionPlan;
+use datafusion_common::Result;
+use datafusion_common::Statistics;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// Per-call memoization cache for [`compute_statistics`].
+///
+/// Keyed by `(plan node pointer address, partition)`. Created once per
+/// top-level [`compute_statistics`] call and shared across all recursive
+/// and operator-internal calls via [`StatisticsArgs`].
+///
+/// The pointer-based key is safe within a single synchronous
+/// `compute_statistics` call: 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 `compute_statistics` walk.
Review Comment:
nice
##########
datafusion/physical-plan/src/statistics_context.rs:
##########
Review Comment:
I wonder if this module should now be renamed (to
datafusion/physical-plan/src/statistics.rs for example)
##########
datafusion/physical-plan/src/statistics_context.rs:
##########
@@ -0,0 +1,213 @@
+// 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.
+
+//! Context for computing statistics in physical plans.
+//!
+//! [`StatisticsArgs`] provides external context to
+//! [`ExecutionPlan::statistics_with_args`], enabling operators to look up
+//! pre-computed child statistics via a shared cache.
+
+use crate::ExecutionPlan;
+use datafusion_common::Result;
+use datafusion_common::Statistics;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// Per-call memoization cache for [`compute_statistics`].
+///
+/// Keyed by `(plan node pointer address, partition)`. Created once per
+/// top-level [`compute_statistics`] call and shared across all recursive
+/// and operator-internal calls via [`StatisticsArgs`].
+///
+/// The pointer-based key is safe within a single synchronous
+/// `compute_statistics` call: 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 `compute_statistics` walk.
+ /// Children's overall (`None`) stats are pre-populated by
+ /// `compute_statistics_inner` before calling the operator.
+ cache: Option<Rc<RefCell<StatsCache>>>,
+}
+
+impl StatisticsArgs {
+ /// Creates new statistics arguments without a shared cache.
+ /// Used by callers outside of `compute_statistics` (e.g. benchmarks).
+ pub fn new(partition: Option<usize>) -> Self {
+ Self {
+ partition,
+ cache: None,
+ }
+ }
+
+ pub fn partition(&self) -> Option<usize> {
+ self.partition
+ }
+
+ /// Returns the pre-computed overall (`None`) statistics for a child.
+ /// For per-partition stats, use [`Self::child_stats_for`].
+ pub fn child_stats_of(&self, child: &dyn ExecutionPlan) ->
Result<Arc<Statistics>> {
+ self.compute_child_statistics(child, None)
+ }
+
+ /// Returns statistics for a child, using pre-computed overall stats
+ /// when `partition` is `None`, or computing per-partition stats on
+ /// demand when `partition` is `Some`.
+ pub fn child_stats_for(&self, child: &dyn ExecutionPlan) ->
Result<Arc<Statistics>> {
Review Comment:
You might be able to make this API a bit more ergonomic and avoid some
`as_refs()` in the code if you made this generic like
```rust
pub fn child_stats_for(&self, child: impl AsRef<dyn ExecutionPlan>) ->
Result<Arc<Statistics>> {
let child = child.as_ref()
...
}
```
##########
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:
Do you mean mean copy the implementation of `partition_statistics` into the
default impl here too? Something like
```rust
if let Some(idx) = 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())))
```
##########
datafusion/physical-plan/src/statistics_context.rs:
##########
@@ -0,0 +1,213 @@
+// 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.
+
+//! Context for computing statistics in physical plans.
+//!
+//! [`StatisticsArgs`] provides external context to
+//! [`ExecutionPlan::statistics_with_args`], enabling operators to look up
+//! pre-computed child statistics via a shared cache.
+
+use crate::ExecutionPlan;
+use datafusion_common::Result;
+use datafusion_common::Statistics;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// Per-call memoization cache for [`compute_statistics`].
+///
+/// Keyed by `(plan node pointer address, partition)`. Created once per
+/// top-level [`compute_statistics`] call and shared across all recursive
+/// and operator-internal calls via [`StatisticsArgs`].
+///
+/// The pointer-based key is safe within a single synchronous
+/// `compute_statistics` call: 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)]
Review Comment:
👍
##########
datafusion/physical-plan/src/statistics_context.rs:
##########
@@ -0,0 +1,213 @@
+// 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.
+
+//! Context for computing statistics in physical plans.
+//!
+//! [`StatisticsArgs`] provides external context to
+//! [`ExecutionPlan::statistics_with_args`], enabling operators to look up
+//! pre-computed child statistics via a shared cache.
+
+use crate::ExecutionPlan;
+use datafusion_common::Result;
+use datafusion_common::Statistics;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// Per-call memoization cache for [`compute_statistics`].
+///
+/// Keyed by `(plan node pointer address, partition)`. Created once per
+/// top-level [`compute_statistics`] call and shared across all recursive
+/// and operator-internal calls via [`StatisticsArgs`].
+///
+/// The pointer-based key is safe within a single synchronous
+/// `compute_statistics` call: 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 `compute_statistics` walk.
+ /// Children's overall (`None`) stats are pre-populated by
+ /// `compute_statistics_inner` before calling the operator.
+ cache: Option<Rc<RefCell<StatsCache>>>,
+}
+
+impl StatisticsArgs {
+ /// Creates new statistics arguments without a shared cache.
+ /// Used by callers outside of `compute_statistics` (e.g. benchmarks).
+ pub fn new(partition: Option<usize>) -> Self {
+ Self {
+ partition,
+ cache: None,
+ }
+ }
+
+ pub fn partition(&self) -> Option<usize> {
+ self.partition
+ }
+
+ /// Returns the pre-computed overall (`None`) statistics for a child.
+ /// For per-partition stats, use [`Self::child_stats_for`].
+ pub fn child_stats_of(&self, child: &dyn ExecutionPlan) ->
Result<Arc<Statistics>> {
+ self.compute_child_statistics(child, None)
+ }
+
+ /// Returns statistics for a child, using pre-computed overall stats
+ /// when `partition` is `None`, or computing per-partition stats on
+ /// demand when `partition` is `Some`.
+ pub fn child_stats_for(&self, child: &dyn ExecutionPlan) ->
Result<Arc<Statistics>> {
+ self.compute_child_statistics(child, self.partition)
+ }
+
+ /// Computes statistics for a child plan, using the shared cache
+ /// from the current [`compute_statistics`] walk.
+ pub fn compute_child_statistics(
+ &self,
+ plan: &dyn ExecutionPlan,
+ partition: Option<usize>,
+ ) -> Result<Arc<Statistics>> {
+ match &self.cache {
+ Some(cache) => compute_statistics_inner(plan, partition, cache),
+ None => compute_statistics(plan, partition),
+ }
+ }
+}
+
+/// Computes statistics for a plan node by first recursively computing
Review Comment:
I don't fully understand this extra level of API -- why also have
`compute_statistics`? For example, why not just always use
SOmething like
```rust
let stats = plan.statistics_with_args(&StatisticsContext::new())?
```
That way the caller is responsible for managing the lifetime of the
statistics cache, etc
##########
datafusion/physical-plan/src/statistics_context.rs:
##########
@@ -0,0 +1,213 @@
+// 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.
+
+//! Context for computing statistics in physical plans.
+//!
+//! [`StatisticsArgs`] provides external context to
+//! [`ExecutionPlan::statistics_with_args`], enabling operators to look up
+//! pre-computed child statistics via a shared cache.
+
+use crate::ExecutionPlan;
+use datafusion_common::Result;
+use datafusion_common::Statistics;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// Per-call memoization cache for [`compute_statistics`].
+///
+/// Keyed by `(plan node pointer address, partition)`. Created once per
+/// top-level [`compute_statistics`] call and shared across all recursive
+/// and operator-internal calls via [`StatisticsArgs`].
+///
+/// The pointer-based key is safe within a single synchronous
+/// `compute_statistics` call: 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 `compute_statistics` walk.
+ /// Children's overall (`None`) stats are pre-populated by
+ /// `compute_statistics_inner` before calling the operator.
+ cache: Option<Rc<RefCell<StatsCache>>>,
+}
+
+impl StatisticsArgs {
+ /// Creates new statistics arguments without a shared cache.
+ /// Used by callers outside of `compute_statistics` (e.g. benchmarks).
+ pub fn new(partition: Option<usize>) -> Self {
+ Self {
+ partition,
+ cache: None,
+ }
+ }
+
+ pub fn partition(&self) -> Option<usize> {
+ self.partition
+ }
+
+ /// Returns the pre-computed overall (`None`) statistics for a child.
+ /// For per-partition stats, use [`Self::child_stats_for`].
+ pub fn child_stats_of(&self, child: &dyn ExecutionPlan) ->
Result<Arc<Statistics>> {
+ self.compute_child_statistics(child, None)
+ }
+
+ /// Returns statistics for a child, using pre-computed overall stats
+ /// when `partition` is `None`, or computing per-partition stats on
+ /// demand when `partition` is `Some`.
+ pub fn child_stats_for(&self, child: &dyn ExecutionPlan) ->
Result<Arc<Statistics>> {
+ self.compute_child_statistics(child, self.partition)
+ }
+
+ /// Computes statistics for a child plan, using the shared cache
+ /// from the current [`compute_statistics`] walk.
+ pub fn compute_child_statistics(
+ &self,
+ plan: &dyn ExecutionPlan,
+ partition: Option<usize>,
+ ) -> Result<Arc<Statistics>> {
+ match &self.cache {
+ Some(cache) => compute_statistics_inner(plan, partition, cache),
+ None => compute_statistics(plan, partition),
+ }
+ }
+}
+
+/// Computes statistics for a plan node by first recursively computing
+/// overall (`None`) statistics for all children, then calling
+/// [`ExecutionPlan::statistics_with_args`].
+///
+/// Results are memoized within a single call: operators that call
+/// [`StatisticsArgs::child_stats_of`] or [`StatisticsArgs::child_stats_for`]
+/// will hit the cache instead of re-walking subtrees.
+///
+/// Children are always pre-computed with `partition = None` (overall stats).
+/// Operators that need per-partition child stats (e.g., partition-preserving
+/// operators when called with `Some(partition)`) should use
+/// [`StatisticsArgs::child_stats_for`].
+pub fn compute_statistics(
+ plan: &dyn ExecutionPlan,
+ partition: Option<usize>,
+) -> Result<Arc<Statistics>> {
+ let cache = Rc::new(RefCell::new(StatsCache::default()));
+ compute_statistics_inner(plan, partition, &cache)
+}
+
+fn compute_statistics_inner(
+ plan: &dyn ExecutionPlan,
+ partition: Option<usize>,
+ cache: &Rc<RefCell<StatsCache>>,
+) -> Result<Arc<Statistics>> {
+ if let Some(cached) = cache.borrow().get(plan, partition) {
+ return Ok(Arc::clone(cached));
+ }
+
+ for child in plan.children() {
+ compute_statistics_inner(child.as_ref(), None, cache)?;
Review Comment:
I think that is the intention (as described above) -- the idea being we
compute the stats once and then compute per-partition statistics
However i am not sure why it is always computing the all partitions case
(the rationale is not explained int he comments) 🤔
--
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]