Apache DataFusion SQL Query Engine
Add `spilled_rows` metric to `ExternalSorter` by `IPCWriter` (#9885)
Eren Avsarogullari544e49bb0aca
diff --git a/datafusion/physical-plan/src/metrics/builder.rs b/datafusion/physical-plan/src/metrics/builder.rsindex 5e8ff72df3..2037ddb70c 100644--- a/datafusion/physical-plan/src/metrics/builder.rs+++ b/datafusion/physical-plan/src/metrics/builder.rs@@ -123,6 +123,15 @@ impl<'a> MetricBuilder<'a> {count}+ /// Consume self and create a new counter for recording the total spilled rows+ /// triggered by an operator+ pub fn spilled_rows(self, partition: usize) -> Count {+ let count = Count::new();+ self.with_partition(partition)+ .build(MetricValue::SpilledRows(count.clone()));+ count+ }+/// Consume self and create a new gauge for reporting current memory usagepub fn mem_used(self, partition: usize) -> Gauge {let gauge = Gauge::new();diff --git a/datafusion/physical-plan/src/metrics/mod.rs b/datafusion/physical-plan/src/metrics/mod.rsindex b2e0086f69..9232865aa0 100644--- a/datafusion/physical-plan/src/metrics/mod.rs+++ b/datafusion/physical-plan/src/metrics/mod.rs@@ -70,7 +70,7 @@ pub struct Metric {/// The value of the metricvalue: MetricValue,- /// arbitrary name=value pairs identifiying this metric+ /// arbitrary name=value pairs identifying this metriclabels: Vec<Label>,/// To which partition of an operators output did this metric@@ -209,6 +209,13 @@ impl MetricsSet {.map(|v| v.as_usize())}+ /// Convenience: return the total rows of spills, aggregated+ /// across partitions or `None` if no metric is present+ pub fn spilled_rows(&self) -> Option<usize> {+ self.sum(|metric| matches!(metric.value(), MetricValue::SpilledRows(_)))+ .map(|v| v.as_usize())+ }+/// Convenience: return the amount of elapsed CPU time spent,/// aggregated across partitions or `None` if no metric is presentpub fn elapsed_compute(&self) -> Option<usize> {@@ -251,6 +258,7 @@ impl MetricsSet {MetricValue::ElapsedCompute(_) => false,MetricValue::SpillCount(_) => false,MetricValue::SpilledBytes(_) => false,+ MetricValue::SpilledRows(_) => false,MetricValue::CurrentMemoryUsage(_) => false,MetricValue::Gauge { name, .. } => name == metric_name,MetricValue::StartTimestamp(_) => false,diff --git a/datafusion/physical-plan/src/metrics/value.rs b/datafusion/physical-plan/src/metrics/value.rsindex ab87cd9e37..22db8f1e4e 100644--- a/datafusion/physical-plan/src/metrics/value.rs+++ b/datafusion/physical-plan/src/metrics/value.rs@@ -364,13 +364,15 @@ pub enum MetricValue {/// Note 2: *Does* includes time when the thread could have made/// progress but the OS did not schedule it (e.g. due to CPU/// contention), thus making this value different than the- /// classical defintion of "cpu_time", which is the time reported+ /// classical definition of "cpu_time", which is the time reported/// from `clock_gettime(CLOCK_THREAD_CPUTIME_ID, ..)`.ElapsedCompute(Time),/// Number of spills produced: "spill_count" metricSpillCount(Count),/// Total size of spilled bytes produced: "spilled_bytes" metricSpilledBytes(Count),+ /// Total size of spilled rows produced: "spilled_rows" metric+ SpilledRows(Count),/// Current memory usedCurrentMemoryUsage(Gauge),/// Operator defined count.@@ -407,6 +409,7 @@ impl MetricValue {Self::OutputRows(_) => "output_rows",Self::SpillCount(_) => "spill_count",Self::SpilledBytes(_) => "spilled_bytes",+ Self::SpilledRows(_) => "spilled_rows",Self::CurrentMemoryUsage(_) => "mem_used",Self::ElapsedCompute(_) => "elapsed_compute",Self::Count { name, .. } => name.borrow(),@@ -423,6 +426,7 @@ impl MetricValue {Self::OutputRows(count) => count.value(),Self::SpillCount(count) => count.value(),Self::SpilledBytes(bytes) => bytes.value(),+ Self::SpilledRows(count) => count.value(),Self::CurrentMemoryUsage(used) => used.value(),Self::ElapsedCompute(time) => time.value(),Self::Count { count, .. } => count.value(),@@ -448,6 +452,7 @@ impl MetricValue {Self::OutputRows(_) => Self::OutputRows(Count::new()),Self::SpillCount(_) => Self::SpillCount(Count::new()),Self::SpilledBytes(_) => Self::SpilledBytes(Count::new()),+ Self::SpilledRows(_) => Self::SpilledRows(Count::new()),Self::CurrentMemoryUsage(_) => Self::CurrentMemoryUsage(Gauge::new()),Self::ElapsedCompute(_) => Self::ElapsedCompute(Time::new()),Self::Count { name, .. } => Self::Count {@@ -481,6 +486,7 @@ impl MetricValue {(Self::OutputRows(count), Self::OutputRows(other_count))| (Self::SpillCount(count), Self::SpillCount(other_count))| (Self::SpilledBytes(count), Self::SpilledBytes(other_count))+ | (Self::SpilledRows(count), Self::SpilledRows(other_count))| (Self::Count { count, .. },Self::Count {@@ -526,12 +532,13 @@ impl MetricValue {Self::ElapsedCompute(_) => 1, // show secondSelf::SpillCount(_) => 2,Self::SpilledBytes(_) => 3,- Self::CurrentMemoryUsage(_) => 4,- Self::Count { .. } => 5,- Self::Gauge { .. } => 6,- Self::Time { .. } => 7,- Self::StartTimestamp(_) => 8, // show timestamps last- Self::EndTimestamp(_) => 9,+ Self::SpilledRows(_) => 4,+ Self::CurrentMemoryUsage(_) => 5,+ Self::Count { .. } => 6,+ Self::Gauge { .. } => 7,+ Self::Time { .. } => 8,+ Self::StartTimestamp(_) => 9, // show timestamps last+ Self::EndTimestamp(_) => 10,}}@@ -541,13 +548,14 @@ impl MetricValue {}}-impl std::fmt::Display for MetricValue {+impl Display for MetricValue {/// Prints the value of this metricfn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {match self {Self::OutputRows(count)| Self::SpillCount(count)| Self::SpilledBytes(count)+ | Self::SpilledRows(count)| Self::Count { count, .. } => {write!(f, "{count}")}diff --git a/datafusion/physical-plan/src/sorts/sort.rs b/datafusion/physical-plan/src/sorts/sort.rsindex a6f47d3d2f..2f4276c5ba 100644--- a/datafusion/physical-plan/src/sorts/sort.rs+++ b/datafusion/physical-plan/src/sorts/sort.rs@@ -71,6 +71,9 @@ struct ExternalSorterMetrics {/// total spilled bytes during the execution of the operatorspilled_bytes: Count,++ /// total spilled rows during the execution of the operator+ spilled_rows: Count,}impl ExternalSorterMetrics {@@ -79,6 +82,7 @@ impl ExternalSorterMetrics {baseline: BaselineMetrics::new(metrics, partition),spill_count: MetricBuilder::new(metrics).spill_count(partition),spilled_bytes: MetricBuilder::new(metrics).spilled_bytes(partition),+ spilled_rows: MetricBuilder::new(metrics).spilled_rows(partition),}}}@@ -231,13 +235,13 @@ struct ExternalSorter {/// prior to spilling.sort_spill_reservation_bytes: usize,/// If the in size of buffered memory batches is below this size,- /// the data will be concated and sorted in place rather than+ /// the data will be concatenated and sorted in place rather than/// sort/merged.sort_in_place_threshold_bytes: usize,}impl ExternalSorter {- // TOOD: make a builder or some other nicer API to avoid the+ // TODO: make a builder or some other nicer API to avoid the// clippy warning#[allow(clippy::too_many_arguments)]pub fn new(@@ -371,13 +375,18 @@ impl ExternalSorter {self.metrics.spilled_bytes.value()}+ /// How many rows have been spilled to disk?+ fn spilled_rows(&self) -> usize {+ self.metrics.spilled_rows.value()+ }+/// How many spill files have been created?fn spill_count(&self) -> usize {self.metrics.spill_count.value()}/// Writes any `in_memory_batches` to a spill file and clears- /// the batches. The contents of the spil file are sorted.+ /// the batches. The contents of the spill file are sorted.////// Returns the amount of memory freed.async fn spill(&mut self) -> Result<usize> {@@ -390,13 +399,15 @@ impl ExternalSorter {self.in_mem_sort().await?;- let spillfile = self.runtime.disk_manager.create_tmp_file("Sorting")?;+ let spill_file = self.runtime.disk_manager.create_tmp_file("Sorting")?;let batches = std::mem::take(&mut self.in_mem_batches);- spill_sorted_batches(batches, spillfile.path(), self.schema.clone()).await?;+ let spilled_rows =+ spill_sorted_batches(batches, spill_file.path(), self.schema.clone()).await?;let used = self.reservation.free();self.metrics.spill_count.add(1);self.metrics.spilled_bytes.add(used);- self.spills.push(spillfile);+ self.metrics.spilled_rows.add(spilled_rows as usize);+ self.spills.push(spill_file);Ok(used)}@@ -576,6 +587,7 @@ impl Debug for ExternalSorter {f.debug_struct("ExternalSorter").field("memory_used", &self.used()).field("spilled_bytes", &self.spilled_bytes())+ .field("spilled_rows", &self.spilled_rows()).field("spill_count", &self.spill_count()).finish()}@@ -650,11 +662,14 @@ pub(crate) fn lexsort_to_indices_multi_columns(Ok(indices)}+/// Spills sorted `in_memory_batches` to disk.+///+/// Returns number of the rows spilled to disk.async fn spill_sorted_batches(batches: Vec<RecordBatch>,path: &Path,schema: SchemaRef,-) -> Result<()> {+) -> Result<u64> {let path: PathBuf = path.into();let task = SpawnedTask::spawn_blocking(move || write_sorted(batches, path, schema));match task.join().await {@@ -685,7 +700,7 @@ fn write_sorted(batches: Vec<RecordBatch>,path: PathBuf,schema: SchemaRef,-) -> Result<()> {+) -> Result<u64> {let mut writer = IPCWriter::new(path.as_ref(), schema.as_ref())?;for batch in batches {writer.write(&batch)?;@@ -697,7 +712,7 @@ fn write_sorted(writer.num_rows,human_readable_size(writer.num_bytes as usize),);- Ok(())+ Ok(writer.num_rows)}fn read_spill(sender: Sender<Result<RecordBatch>>, path: &Path) -> Result<()> {@@ -1062,8 +1077,9 @@ mod tests {assert_eq!(metrics.output_rows().unwrap(), 10000);assert!(metrics.elapsed_compute().unwrap() > 0);- assert!(metrics.spill_count().unwrap() > 0);- assert!(metrics.spilled_bytes().unwrap() > 0);+ assert_eq!(metrics.spill_count().unwrap(), 4);+ assert_eq!(metrics.spilled_bytes().unwrap(), 38784);+ assert_eq!(metrics.spilled_rows().unwrap(), 9600);let columns = result[0].columns();