-
Notifications
You must be signed in to change notification settings - Fork 151
Add Python bindings for accessing ExecutionMetrics #1381
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ShreyeshArangath
wants to merge
7
commits into
apache:main
Choose a base branch
from
ShreyeshArangath:feat/support-metrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
697de36
feat: add Python bindings for accessing ExecutionMetrics
ShreyeshArangath 0a57da6
test: imporve tests
ShreyeshArangath e1d0c81
first round of reviews
7200857
plan caching
d2b6c9f
address some concerns
30ec047
Merge branch 'main' into feat/support-metrics
a8623c2
merge and address comments
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| // 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. | ||
|
|
||
| use std::collections::HashMap; | ||
| use std::sync::Arc; | ||
|
|
||
| use datafusion::physical_plan::metrics::{MetricValue, MetricsSet, Metric, Timestamp}; | ||
| use pyo3::prelude::*; | ||
|
|
||
| #[pyclass(frozen, name = "MetricsSet", module = "datafusion")] | ||
| #[derive(Debug, Clone)] | ||
| pub struct PyMetricsSet { | ||
| metrics: MetricsSet, | ||
| } | ||
|
|
||
| impl PyMetricsSet { | ||
| pub fn new(metrics: MetricsSet) -> Self { | ||
| Self { metrics } | ||
| } | ||
| } | ||
|
|
||
| #[pymethods] | ||
| impl PyMetricsSet { | ||
| fn metrics(&self) -> Vec<PyMetric> { | ||
| self.metrics | ||
| .iter() | ||
| .map(|m| PyMetric::new(Arc::clone(m))) | ||
| .collect() | ||
| } | ||
|
|
||
| fn output_rows(&self) -> Option<usize> { | ||
| self.metrics.output_rows() | ||
| } | ||
|
|
||
| fn elapsed_compute(&self) -> Option<usize> { | ||
| self.metrics.elapsed_compute() | ||
| } | ||
|
|
||
| fn spill_count(&self) -> Option<usize> { | ||
| self.metrics.spill_count() | ||
| } | ||
|
|
||
| fn spilled_bytes(&self) -> Option<usize> { | ||
| self.metrics.spilled_bytes() | ||
| } | ||
|
|
||
| fn spilled_rows(&self) -> Option<usize> { | ||
| self.metrics.spilled_rows() | ||
| } | ||
|
|
||
| fn sum_by_name(&self, name: &str) -> Option<usize> { | ||
| self.metrics.sum_by_name(name).map(|v| v.as_usize()) | ||
| } | ||
|
|
||
| fn __repr__(&self) -> String { | ||
| format!("{}", self.metrics) | ||
| } | ||
| } | ||
|
|
||
| #[pyclass(frozen, name = "Metric", module = "datafusion")] | ||
| #[derive(Debug, Clone)] | ||
| pub struct PyMetric { | ||
| metric: Arc<Metric>, | ||
| } | ||
|
|
||
| impl PyMetric { | ||
| pub fn new(metric: Arc<Metric>) -> Self { | ||
| Self { metric } | ||
| } | ||
|
|
||
| fn timestamp_to_pyobject<'py>( | ||
| py: Python<'py>, | ||
| ts: &Timestamp, | ||
| ) -> PyResult<Option<Bound<'py, PyAny>>> { | ||
| match ts.value() { | ||
| Some(dt) => { | ||
| let nanos = dt.timestamp_nanos_opt().ok_or_else(|| { | ||
| PyErr::new::<pyo3::exceptions::PyOverflowError, _>( | ||
| "timestamp out of range", | ||
| ) | ||
| })?; | ||
| let datetime_mod = py.import("datetime")?; | ||
| let datetime_cls = datetime_mod.getattr("datetime")?; | ||
| let tz_utc = datetime_mod.getattr("timezone")?.getattr("utc")?; | ||
| let secs = nanos / 1_000_000_000; | ||
| let micros = (nanos % 1_000_000_000) / 1_000; | ||
| let result = datetime_cls.call_method1( | ||
| "fromtimestamp", | ||
| (secs as f64 + micros as f64 / 1_000_000.0, tz_utc), | ||
| )?; | ||
| Ok(Some(result)) | ||
| } | ||
| None => Ok(None), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[pymethods] | ||
| impl PyMetric { | ||
| #[getter] | ||
| fn name(&self) -> String { | ||
| self.metric.value().name().to_string() | ||
| } | ||
|
|
||
| #[getter] | ||
| fn value<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> { | ||
| match self.metric.value() { | ||
| MetricValue::OutputRows(c) => Ok(Some(c.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::OutputBytes(c) => Ok(Some(c.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::ElapsedCompute(t) => Ok(Some(t.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::SpillCount(c) => Ok(Some(c.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::SpilledBytes(c) => Ok(Some(c.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::SpilledRows(c) => Ok(Some(c.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::CurrentMemoryUsage(g) => Ok(Some(g.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::Count { count, .. } => Ok(Some(count.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::Gauge { gauge, .. } => Ok(Some(gauge.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::Time { time, .. } => Ok(Some(time.value().into_pyobject(py)?.into_any())), | ||
| MetricValue::StartTimestamp(ts) | MetricValue::EndTimestamp(ts) => { | ||
| Self::timestamp_to_pyobject(py, ts) | ||
| } | ||
| _ => Ok(None), | ||
| } | ||
| } | ||
|
|
||
| fn value_as_datetime<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> { | ||
| match self.metric.value() { | ||
| MetricValue::StartTimestamp(ts) | MetricValue::EndTimestamp(ts) => { | ||
| Self::timestamp_to_pyobject(py, ts) | ||
| } | ||
| _ => Ok(None), | ||
| } | ||
| } | ||
|
|
||
| #[getter] | ||
| fn partition(&self) -> Option<usize> { | ||
| self.metric.partition() | ||
| } | ||
|
|
||
| fn labels(&self) -> HashMap<String, String> { | ||
| self.metric | ||
| .labels() | ||
| .iter() | ||
| .map(|l| (l.name().to_string(), l.value().to_string())) | ||
| .collect() | ||
| } | ||
|
|
||
| fn __repr__(&self) -> String { | ||
| format!("{}", self.metric.value()) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you go the route of using the existing
last_planforcollect()like in my other comment then I think you could set it here just like you do in collect().