Skip to content

Commit ff677c4

Browse files
authored
fix: Fix peak memory display in EXPLAIN ANALYZE for multiple operators (#23140)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> See reproducer in `datafusion-cli`: ```sh yongting@Yongtings-MacBook-Pro-2 ~/C/d/datafusion (hj-mem-fix *)> datafusion-cli DataFusion CLI v54.0.0 > set datafusion.explain.analyze_categories = 'bytes'; 0 row(s) fetched. Elapsed 0.001 seconds. > explain analyze select * from generate_series(100000000) as t1(v1) join generate_series(100000000) as t2(v1) on t1.v1=t2.v1; +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+ | plan_type | plan | +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+ | Plan with Metrics | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(v1@0, v1@0)], metrics=[output_bytes=1526.7 MB, build_mem_used=2.80 B] | | | RepartitionExec: partitioning=Hash([v1@0], 14), input_partitions=1, maintains_sort_order=true, metrics=[output_bytes=763.4 MB, spilled_bytes=0.0 B] | | | ProjectionExec: expr=[value@0 as v1], metrics=[output_bytes=763.0 MB] | | | LazyMemoryExec: partitions=1, batch_generators=[generate_series: start=0, end=100000000, batch_size=8192], metrics=[output_bytes=763.0 MB] | | | RepartitionExec: partitioning=Hash([v1@0], 14), input_partitions=1, maintains_sort_order=true, metrics=[output_bytes=763.4 MB, spilled_bytes=0.0 B] | | | ProjectionExec: expr=[value@0 as v1], metrics=[output_bytes=763.0 MB] | | | LazyMemoryExec: partitions=1, batch_generators=[generate_series: start=0, end=100000000, batch_size=8192], metrics=[output_bytes=763.0 MB] | | | | +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row(s) fetched. Elapsed 1.040 seconds. ``` See `HashJoinExec: ... build_mem_used=2.80 B`, it actually means 2.8 billion bytes, but it looks quite misleading. This PR fixes it: ```sh +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+ | plan_type | plan | +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+ | Plan with Metrics | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(v1@0, v1@0)], metrics=[output_bytes=1526.7 MB, build_mem_used=2.6 GB] ``` The reason is those metrics are tracking peak memory usage for a operator in the query lifecycle, so it's using `Gauge` metrics type, but how to choose display format become tricky (bytes or count?) This PR adds a new `Metric` type, that wraps the existing `Gauge`, and use it to represent 'gauge for memory bytes', this fixes the bytes display issue. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> 1. Introduce `MetricValue::PeakMemoryUsage` to address the above issue 2. Use this metric type for applicable metrics 3. Add slts for testing. ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 4. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. -->
1 parent 32e27ac commit ff677c4

12 files changed

Lines changed: 330 additions & 14 deletions

File tree

‎datafusion/ffi/src/physical_expr/metrics.rs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ pub struct FFI_RatioMetrics {
128128
}
129129

130130
/// FFI-stable mirror of [`MetricValue`].
131+
///
132+
/// This is part of the stable ABI and must not be reordered. New variants must be
133+
/// appended at the end.
131134
#[repr(C, u8)]
132135
#[derive(Debug, Clone)]
133136
pub enum FFI_MetricValue {
@@ -170,6 +173,10 @@ pub enum FFI_MetricValue {
170173
display: SString,
171174
as_usize_value: u64,
172175
},
176+
PeakMemoryUsage {
177+
name: SString,
178+
gauge: u64,
179+
},
173180
}
174181

175182
// -----------------------------------------------------------------------------
@@ -425,6 +432,10 @@ impl From<&MetricValue> for FFI_MetricValue {
425432
name: SString::from(name.as_ref()),
426433
gauge: gauge.value() as u64,
427434
},
435+
MetricValue::PeakMemoryUsage { name, gauge } => Self::PeakMemoryUsage {
436+
name: SString::from(name.as_ref()),
437+
gauge: gauge.value() as u64,
438+
},
428439
MetricValue::Time { name, time } => Self::Time {
429440
name: SString::from(name.as_ref()),
430441
time_ns: time.value() as u64,
@@ -481,6 +492,10 @@ impl From<FFI_MetricValue> for MetricValue {
481492
name: Cow::Owned(name.into()),
482493
gauge: gauge_from_value(gauge),
483494
},
495+
FFI_MetricValue::PeakMemoryUsage { name, gauge } => Self::PeakMemoryUsage {
496+
name: Cow::Owned(name.into()),
497+
gauge: gauge_from_value(gauge),
498+
},
484499
FFI_MetricValue::Time { name, time_ns } => Self::Time {
485500
name: Cow::Owned(name.into()),
486501
time: time_from_nanos(time_ns),
@@ -624,6 +639,13 @@ mod tests {
624639
gauge,
625640
});
626641

642+
let peak_memory = Gauge::new();
643+
peak_memory.add(44);
644+
assert_value_roundtrip(MetricValue::PeakMemoryUsage {
645+
name: Cow::Borrowed("peak_mem_used"),
646+
gauge: peak_memory,
647+
});
648+
627649
let time = Time::new();
628650
time.add_duration(std::time::Duration::from_nanos(33));
629651
assert_value_roundtrip(MetricValue::Time {

‎datafusion/physical-expr-common/src/metrics/builder.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,23 @@ impl<'a> MetricBuilder<'a> {
249249
gauge
250250
}
251251

252+
/// Consumes self and creates a new [`Gauge`] for recording peak memory
253+
/// usage in bytes.
254+
pub fn peak_memory_usage(
255+
self,
256+
gauge_name: impl Into<Cow<'static, str>>,
257+
partition: usize,
258+
) -> Gauge {
259+
let gauge = Gauge::new();
260+
self.with_category(MetricCategory::Bytes)
261+
.with_partition(partition)
262+
.build(MetricValue::PeakMemoryUsage {
263+
name: gauge_name.into(),
264+
gauge: gauge.clone(),
265+
});
266+
gauge
267+
}
268+
252269
/// Consume self and create a new Timer for recording the elapsed
253270
/// CPU time spent by an operator
254271
pub fn elapsed_compute(self, partition: usize) -> Time {

‎datafusion/physical-expr-common/src/metrics/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ impl MetricsSet {
309309
MetricValue::SpilledRows(_) => false,
310310
MetricValue::CurrentMemoryUsage(_) => false,
311311
MetricValue::Gauge { name, .. } => name == metric_name,
312+
MetricValue::PeakMemoryUsage { name, .. } => name == metric_name,
312313
MetricValue::StartTimestamp(_) => false,
313314
MetricValue::EndTimestamp(_) => false,
314315
MetricValue::PruningMetrics { name, .. } => name == metric_name,

‎datafusion/physical-expr-common/src/metrics/value.rs‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,13 @@ pub enum MetricValue {
672672
/// The value of the metric
673673
gauge: Gauge,
674674
},
675+
/// Operator defined peak memory usage in bytes.
676+
PeakMemoryUsage {
677+
/// The provided name of this metric
678+
name: Cow<'static, str>,
679+
/// The value of the metric
680+
gauge: Gauge,
681+
},
675682
/// Operator defined time
676683
Time {
677684
/// The provided name of this metric
@@ -744,6 +751,13 @@ impl PartialEq for MetricValue {
744751
name: other_name,
745752
gauge: other_gauge,
746753
},
754+
)
755+
| (
756+
MetricValue::PeakMemoryUsage { name, gauge },
757+
MetricValue::PeakMemoryUsage {
758+
name: other_name,
759+
gauge: other_gauge,
760+
},
747761
) => name == other_name && gauge == other_gauge,
748762
(
749763
MetricValue::Time { name, time },
@@ -810,7 +824,9 @@ impl MetricValue {
810824
Self::CurrentMemoryUsage(_) => "mem_used",
811825
Self::ElapsedCompute(_) => "elapsed_compute",
812826
Self::Count { name, .. } => name.borrow(),
813-
Self::Gauge { name, .. } => name.borrow(),
827+
Self::Gauge { name, .. } | Self::PeakMemoryUsage { name, .. } => {
828+
name.borrow()
829+
}
814830
Self::Time { name, .. } => name.borrow(),
815831
Self::StartTimestamp(_) => "start_timestamp",
816832
Self::EndTimestamp(_) => "end_timestamp",
@@ -833,7 +849,9 @@ impl MetricValue {
833849
Self::CurrentMemoryUsage(used) => used.value(),
834850
Self::ElapsedCompute(time) => time.value(),
835851
Self::Count { count, .. } => count.value(),
836-
Self::Gauge { gauge, .. } => gauge.value(),
852+
Self::Gauge { gauge, .. } | Self::PeakMemoryUsage { gauge, .. } => {
853+
gauge.value()
854+
}
837855
Self::Time { time, .. } => time.value(),
838856
Self::StartTimestamp(timestamp) => timestamp
839857
.value()
@@ -875,6 +893,10 @@ impl MetricValue {
875893
name: name.clone(),
876894
gauge: Gauge::new(),
877895
},
896+
Self::PeakMemoryUsage { name, .. } => Self::PeakMemoryUsage {
897+
name: name.clone(),
898+
gauge: Gauge::new(),
899+
},
878900
Self::Time { name, .. } => Self::Time {
879901
name: name.clone(),
880902
time: Time::new(),
@@ -933,6 +955,12 @@ impl MetricValue {
933955
Self::Gauge {
934956
gauge: other_gauge, ..
935957
},
958+
)
959+
| (
960+
Self::PeakMemoryUsage { gauge, .. },
961+
Self::PeakMemoryUsage {
962+
gauge: other_gauge, ..
963+
},
936964
) => gauge.add(other_gauge.value()),
937965
(Self::ElapsedCompute(time), Self::ElapsedCompute(other_time))
938966
| (
@@ -1029,6 +1057,7 @@ impl MetricValue {
10291057
"page_index_pages_skipped_by_fully_matched" => 8,
10301058
_ => 14,
10311059
},
1060+
Self::PeakMemoryUsage { .. } => 13,
10321061
Self::Gauge { .. } => 15,
10331062
Self::Time { .. } => 16,
10341063
Self::Ratio { .. } => 17,
@@ -1064,6 +1093,10 @@ impl Display for MetricValue {
10641093
let readable_size = human_readable_size(gauge.value());
10651094
write!(f, "{readable_size}")
10661095
}
1096+
Self::PeakMemoryUsage { gauge, .. } => {
1097+
let readable_size = human_readable_size(gauge.value());
1098+
write!(f, "{readable_size}")
1099+
}
10671100
Self::Gauge { gauge, .. } => {
10681101
// Generic gauge metrics - format with human-readable count
10691102
write!(f, "{}", human_readable_count(gauge.value()))
@@ -1525,6 +1558,18 @@ mod tests {
15251558
"100.0 MB"
15261559
);
15271560

1561+
// Test PeakMemoryUsage formatting (should use size, not count)
1562+
let peak_mem_gauge = Gauge::new();
1563+
peak_mem_gauge.add(100 * MB as usize);
1564+
assert_eq!(
1565+
MetricValue::PeakMemoryUsage {
1566+
name: "peak_mem_used".into(),
1567+
gauge: peak_mem_gauge.clone()
1568+
}
1569+
.to_string(),
1570+
"100.0 MB"
1571+
);
1572+
15281573
// Test custom Gauge formatting (should use count)
15291574
let custom_gauge = Gauge::new();
15301575
custom_gauge.add(50_000);

‎datafusion/physical-plan/src/aggregates/row_hash.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,7 @@ impl GroupedHashAggregateStream {
527527
merging_aggregate_arguments,
528528
merging_group_by: PhysicalGroupBy::new_single(merging_group_by_expr),
529529
peak_mem_used: MetricBuilder::new(&agg.metrics)
530-
.with_category(MetricCategory::Bytes)
531-
.gauge("peak_mem_used", partition),
530+
.peak_memory_usage("peak_mem_used", partition),
532531
spill_manager,
533532
};
534533

‎datafusion/physical-plan/src/buffer.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,7 @@ impl ExecutionPlan for BufferExec {
194194
let curr_mem_out = Arc::clone(&curr_mem_in);
195195
let mut max_mem_in = 0;
196196
let max_mem = MetricBuilder::new(&self.metrics)
197-
.with_category(MetricCategory::Bytes)
198-
.gauge("max_mem_used", partition);
197+
.peak_memory_usage("max_mem_used", partition);
199198

200199
let curr_queued_in = Arc::new(AtomicUsize::new(0));
201200
let curr_queued_out = Arc::clone(&curr_queued_in);

‎datafusion/physical-plan/src/display.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -775,6 +775,9 @@ impl PgJsonExecutionPlanVisitor<'_> {
775775
}
776776
MetricValue::Count { count, .. } => serde_json::Value::from(count.value()),
777777
MetricValue::Gauge { gauge, .. } => serde_json::Value::from(gauge.value()),
778+
MetricValue::PeakMemoryUsage { gauge, .. } => {
779+
serde_json::Value::from(gauge.value())
780+
}
778781
MetricValue::Time { time, .. } => {
779782
let ms = (time.value() as f64) / 1_000_000.0;
780783
serde_json::Value::from(ms)

‎datafusion/physical-plan/src/joins/sort_merge_join/bitwise_stream.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,8 @@ impl BitwiseSortMergeJoinStream {
360360
MetricBuilder::new(metrics).counter("input_batches", partition);
361361
let input_rows = MetricBuilder::new(metrics).counter("input_rows", partition);
362362
let baseline_metrics = BaselineMetrics::new(metrics, partition);
363-
let peak_mem_used = MetricBuilder::new(metrics).gauge("peak_mem_used", partition);
363+
let peak_mem_used =
364+
MetricBuilder::new(metrics).peak_memory_usage("peak_mem_used", partition);
364365

365366
Ok(Self {
366367
join_type,

‎datafusion/physical-plan/src/joins/sort_merge_join/metrics.rs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,8 @@ impl SortMergeJoinMetrics {
4646
let input_rows = MetricBuilder::new(metrics)
4747
.with_category(MetricCategory::Rows)
4848
.counter("input_rows", partition);
49-
let peak_mem_used = MetricBuilder::new(metrics)
50-
.with_category(MetricCategory::Bytes)
51-
.gauge("peak_mem_used", partition);
49+
let peak_mem_used =
50+
MetricBuilder::new(metrics).peak_memory_usage("peak_mem_used", partition);
5251

5352
let baseline_metrics = BaselineMetrics::new(metrics, partition);
5453

‎datafusion/physical-plan/src/joins/utils.rs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1798,9 +1798,8 @@ impl BuildProbeJoinMetrics {
17981798
.with_category(MetricCategory::Rows)
17991799
.counter("build_input_rows", partition);
18001800

1801-
let build_mem_used = MetricBuilder::new(metrics)
1802-
.with_category(MetricCategory::Bytes)
1803-
.gauge("build_mem_used", partition);
1801+
let build_mem_used =
1802+
MetricBuilder::new(metrics).peak_memory_usage("build_mem_used", partition);
18041803

18051804
let input_batches = MetricBuilder::new(metrics)
18061805
.with_category(MetricCategory::Rows)

0 commit comments

Comments
 (0)