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


##########
datafusion/physical-expr-common/src/metrics/snapshot.rs:
##########
@@ -0,0 +1,376 @@
+// 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.
+
+//! Metric [`Registry`] and [`Snapshot`] implementations.
+
+use super::Metric;
+use parking_lot::Mutex;
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, OnceLock};
+
+#[derive(Debug, Default)]
+pub(super) struct Registry {
+    metrics: Vec<Arc<Metric>>,
+    // Readers index each registration once, avoiding repeated full scans when
+    // reporting successive partitions. Registration itself only appends to 
metrics.
+    index: PartitionIndex,
+}
+
+#[derive(Debug, Default)]
+struct PartitionIndex {
+    // Number of registry entries already examined, including global metrics.
+    indexed: usize,
+    // Partition ID -> positions in Registry::metrics, in registration order.
+    // Positions also let older snapshots exclude later registrations. Storing
+    // handles here would duplicate Arc ownership and still require these 
positions.
+    positions: HashMap<usize, Vec<usize>>,
+}
+
+impl Registry {
+    pub(super) fn new(metrics: Vec<Arc<Metric>>) -> Self {
+        Self {
+            metrics,
+            index: PartitionIndex::default(),
+        }
+    }
+
+    pub(super) fn register(&mut self, metric: Arc<Metric>) {
+        self.metrics.push(metric);
+    }
+
+    /// Select metrics whose partition ID equals `partition`. `end` is an 
exclusive
+    /// position in the full registration vector, including other partitions 
and
+    /// global metrics. It fixes the membership of the requesting snapshot.
+    fn select(&mut self, partition: usize, end: usize) -> Vec<Arc<Metric>> {
+        let index = &mut self.index;
+        for position in index.indexed..end {
+            if let Some(partition) = self.metrics[position].partition() {
+                index.positions.entry(partition).or_default().push(position);
+            }
+        }
+        index.indexed = index.indexed.max(end);
+        let Some(positions) = index.positions.get(&partition) else {
+            return Vec::new();
+        };
+        // Another snapshot may already have indexed registrations after our 
end.
+        let len = positions.partition_point(|&position| position < end);
+        positions[..len]
+            .iter()
+            .map(|&i| Arc::clone(&self.metrics[i]))
+            .collect()
+    }
+}
+
+#[derive(Clone)]
+pub(super) enum Snapshot {

Review Comment:
   👍 



##########
datafusion/physical-expr-common/src/metrics/snapshot.rs:
##########
@@ -0,0 +1,376 @@
+// 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.
+
+//! Metric [`Registry`] and [`Snapshot`] implementations.
+
+use super::Metric;
+use parking_lot::Mutex;
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, OnceLock};
+
+#[derive(Debug, Default)]
+pub(super) struct Registry {
+    metrics: Vec<Arc<Metric>>,
+    // Readers index each registration once, avoiding repeated full scans when
+    // reporting successive partitions. Registration itself only appends to 
metrics.
+    index: PartitionIndex,
+}
+
+#[derive(Debug, Default)]
+struct PartitionIndex {
+    // Number of registry entries already examined, including global metrics.
+    indexed: usize,
+    // Partition ID -> positions in Registry::metrics, in registration order.
+    // Positions also let older snapshots exclude later registrations. Storing
+    // handles here would duplicate Arc ownership and still require these 
positions.
+    positions: HashMap<usize, Vec<usize>>,
+}
+
+impl Registry {
+    pub(super) fn new(metrics: Vec<Arc<Metric>>) -> Self {
+        Self {
+            metrics,
+            index: PartitionIndex::default(),
+        }
+    }
+
+    pub(super) fn register(&mut self, metric: Arc<Metric>) {
+        self.metrics.push(metric);
+    }
+
+    /// Select metrics whose partition ID equals `partition`. `end` is an 
exclusive
+    /// position in the full registration vector, including other partitions 
and
+    /// global metrics. It fixes the membership of the requesting snapshot.
+    fn select(&mut self, partition: usize, end: usize) -> Vec<Arc<Metric>> {
+        let index = &mut self.index;
+        for position in index.indexed..end {
+            if let Some(partition) = self.metrics[position].partition() {
+                index.positions.entry(partition).or_default().push(position);
+            }
+        }
+        index.indexed = index.indexed.max(end);
+        let Some(positions) = index.positions.get(&partition) else {
+            return Vec::new();
+        };
+        // Another snapshot may already have indexed registrations after our 
end.
+        let len = positions.partition_point(|&position| position < end);
+        positions[..len]
+            .iter()
+            .map(|&i| Arc::clone(&self.metrics[i]))
+            .collect()
+    }
+}
+
+#[derive(Clone)]
+pub(super) enum Snapshot {
+    /// All metrics registered before a fixed boundary; partition reads use 
the index.
+    All(Arc<AllMetrics>),
+    /// A selected partition, independent of the source registry.
+    Partition {
+        partition: usize,
+        metrics: Vec<Arc<Metric>>,
+    },
+    /// An arbitrary collection created directly or detached by mutation. It 
has
+    /// no registry/index and may contain multiple partitions and global 
metrics.
+    Standalone(Vec<Arc<Metric>>),
+}
+
+pub(super) struct AllMetrics {
+    registry: Arc<Mutex<Registry>>,
+    // Exclusive position in Registry::metrics, not a per-partition count.
+    end: usize,
+    flat: OnceLock<Vec<Arc<Metric>>>,

Review Comment:
   what is the `flat` field for and how does it relate to `registry.metrics`? 
Perhaps we can document it -- it seems like maybe it is a cache to avoid 
copying registry.metrics ? 
   
   ```
       metrics: Vec<Arc<Metric>>,
   ```



##########
datafusion/physical-expr-common/src/metrics/snapshot.rs:
##########
@@ -0,0 +1,376 @@
+// 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.
+
+//! Metric [`Registry`] and [`Snapshot`] implementations.
+
+use super::Metric;
+use parking_lot::Mutex;
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, OnceLock};
+
+#[derive(Debug, Default)]
+pub(super) struct Registry {
+    metrics: Vec<Arc<Metric>>,
+    // Readers index each registration once, avoiding repeated full scans when
+    // reporting successive partitions. Registration itself only appends to 
metrics.
+    index: PartitionIndex,
+}
+
+#[derive(Debug, Default)]
+struct PartitionIndex {
+    // Number of registry entries already examined, including global metrics.
+    indexed: usize,
+    // Partition ID -> positions in Registry::metrics, in registration order.
+    // Positions also let older snapshots exclude later registrations. Storing
+    // handles here would duplicate Arc ownership and still require these 
positions.
+    positions: HashMap<usize, Vec<usize>>,
+}
+
+impl Registry {
+    pub(super) fn new(metrics: Vec<Arc<Metric>>) -> Self {
+        Self {
+            metrics,
+            index: PartitionIndex::default(),
+        }
+    }
+
+    pub(super) fn register(&mut self, metric: Arc<Metric>) {
+        self.metrics.push(metric);
+    }
+
+    /// Select metrics whose partition ID equals `partition`. `end` is an 
exclusive
+    /// position in the full registration vector, including other partitions 
and
+    /// global metrics. It fixes the membership of the requesting snapshot.
+    fn select(&mut self, partition: usize, end: usize) -> Vec<Arc<Metric>> {
+        let index = &mut self.index;
+        for position in index.indexed..end {
+            if let Some(partition) = self.metrics[position].partition() {
+                index.positions.entry(partition).or_default().push(position);
+            }
+        }
+        index.indexed = index.indexed.max(end);
+        let Some(positions) = index.positions.get(&partition) else {
+            return Vec::new();
+        };
+        // Another snapshot may already have indexed registrations after our 
end.
+        let len = positions.partition_point(|&position| position < end);
+        positions[..len]
+            .iter()
+            .map(|&i| Arc::clone(&self.metrics[i]))
+            .collect()
+    }
+}
+
+#[derive(Clone)]
+pub(super) enum Snapshot {
+    /// All metrics registered before a fixed boundary; partition reads use 
the index.
+    All(Arc<AllMetrics>),
+    /// A selected partition, independent of the source registry.
+    Partition {
+        partition: usize,
+        metrics: Vec<Arc<Metric>>,
+    },
+    /// An arbitrary collection created directly or detached by mutation. It 
has
+    /// no registry/index and may contain multiple partitions and global 
metrics.
+    Standalone(Vec<Arc<Metric>>),
+}
+
+pub(super) struct AllMetrics {
+    registry: Arc<Mutex<Registry>>,
+    // Exclusive position in Registry::metrics, not a per-partition count.
+    end: usize,
+    flat: OnceLock<Vec<Arc<Metric>>>,

Review Comment:
   If the idea is to model a delayed mateiralization, Another way to model it 
that might be simpler could be to convert `Snapshot::All` --> 
`Snapshot::Standalone` on a call to `iter` 🤔  or maybe introduce a new variant 
like `Snapshot::AllMaterialized` 
   
   
   
   



##########
datafusion/physical-plan/tests/partition_metrics.rs:
##########
@@ -0,0 +1,101 @@
+// 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.
+
+#[path = "metrics/plan.rs"]
+mod plan;
+
+use std::sync::Arc;
+
+use arrow::array::Int32Array;
+use datafusion_common::Result;
+use datafusion_execution::TaskContext;
+use futures::{FutureExt, StreamExt, TryStreamExt};
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]

Review Comment:
   I would prefer this NOT be its own test binary (as that adds several hundred 
MB of binary to `--workspace` builds). Can we add these tests to some existing 
end to end tests (perhaps in `core_integration`)?



##########
datafusion/physical-expr-common/src/metrics/mod.rs:
##########
@@ -228,9 +230,17 @@ impl Metric {
 }
 
 /// A snapshot of the metrics for a particular execution plan.
+///
+/// The set's members remain fixed as execution registers more metrics, but 
their
+/// values continue to reflect execution progress. Use [`Self::for_partition`] 
to
+/// select the metrics belonging to one partition.
+///
+/// Snapshots from [`ExecutionPlanMetricsSet::clone_inner`] retain the source

Review Comment:
   I think this last paragraph in the comment is about internal implementation 
details and is confusing on `Metrics` -- maybe it would be better on `Snapshot` 
or just dropped entirely



##########
datafusion/physical-expr-common/src/metrics/snapshot.rs:
##########
@@ -0,0 +1,301 @@
+// 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.
+
+//! Fixed-membership snapshots of an append-only registry.
+//!
+//! Registration only appends to a vector. Partition readers share an index 
that
+//! catches up with registration on demand; snapshots remember their original 
end
+//! position even when a later reader has advanced the index past that 
position.
+
+use super::Metric;
+use parking_lot::Mutex;
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, OnceLock};
+
+#[derive(Debug, Default)]
+pub(super) struct Registry {
+    pub(super) metrics: Vec<Arc<Metric>>,
+    // No index allocation or maintenance on the registration path.
+    index: Option<Box<PartitionIndex>>,
+}
+
+#[derive(Debug, Default)]
+struct PartitionIndex {
+    // Number of registry entries already examined, including global metrics.
+    indexed: usize,
+    // Partition ID -> positions in Registry::metrics, in registration order.
+    positions: HashMap<usize, Vec<usize>>,

Review Comment:
   The new comments help a lot. Thank you



-- 
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