LinSimon-901101 commented on code in PR #7825:
URL: https://github.com/apache/datafusion-comet/pull/7825#discussion_r4783836507


##########
native/spark-expr/benches/nested_compaction_query.rs:
##########
@@ -0,0 +1,574 @@
+// 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.
+
+//! Full sort of Comet's nested extraction results. See the contributor 
benchmarking guide.
+//! Usage: cargo bench --bench nested_compaction_query -- [CASE [MiB [SAMPLES 
[BATCHES]]]] [--check]
+
+#[cfg(unix)]
+#[path = "common/nested_compaction_query_metrics.rs"]
+mod metrics;
+
+#[cfg(not(unix))]
+fn main() {
+    eprintln!("The nested compaction benchmark requires Unix process CPU 
accounting");
+}
+
+#[cfg(unix)]
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+    query::run()
+}
+
+#[cfg(unix)]
+mod query {
+    use super::metrics::{cpu_time, AllocationWindow, TRACK_ALLOCATIONS};
+    use arrow::array::{
+        Array, ArrayData, ArrayRef, BooleanArray, Int32Array, ListArray, 
MapArray, StringArray,
+        UInt32Array, UInt64Array,
+    };
+    use arrow::buffer::{NullBuffer, OffsetBuffer};
+    use arrow::compute::{take, SortOptions};
+    use arrow::datatypes::{DataType, Field, Schema};
+    use arrow::record_batch::RecordBatch;
+    use datafusion::common::config::{ConfigOptions, SpillCompression};
+    use datafusion::common::utils::memory::RecordBatchMemoryCounter;
+    use datafusion::common::ScalarValue;
+    use datafusion::datasource::memory::MemorySourceConfig;
+    use datafusion::execution::context::{SessionConfig, SessionContext};
+    use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, 
PeakRecordingPool};
+    use datafusion::execution::runtime_env::RuntimeEnvBuilder;
+    use datafusion::logical_expr::ScalarUDF;
+    use datafusion::physical_expr::expressions::{Column, Literal};
+    use datafusion::physical_expr::{
+        LexOrdering, PhysicalExpr, PhysicalSortExpr, ScalarFunctionExpr,
+    };
+    use datafusion::physical_plan::{
+        projection::ProjectionExec, sorts::sort::SortExec, ExecutionPlan,
+    };
+    use datafusion_comet_spark_expr::{create_query_context_map, ListExtract, 
SparkMapExtract};
+    use futures::TryStreamExt;
+    use rand::rngs::StdRng;
+    use rand::{RngExt, SeedableRng};
+    use std::hint::black_box;
+    use std::path::PathBuf;
+    use std::sync::Arc;
+    use std::time::Instant;
+
+    type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
+    const ROWS: usize = 8192;
+    const ID_MASK: usize = 0x1555;
+    const MERGE_RESERVATION: usize = 16 * 1024 * 1024;
+    const FIXTURE_SEED: u64 = 7145;
+
+    #[derive(Clone, Copy)]
+    enum Shape {
+        Map { miss_percent: usize },
+        RandomMap,
+        BoundaryMap,
+        MapParentNull,
+        Short,
+        Empty,
+        Deep,
+        RandomLength,
+        ParentNull,
+        ChildNull,
+        StructList,
+        Strings,
+        Booleans,
+        Uniform,
+        Flat,
+    }
+
+    impl Shape {
+        fn parse(name: &str) -> Result<Self> {
+            if let Some(percent) = name.strip_prefix("map-").filter(|_| {
+                !matches!(
+                    name,
+                    "map-random-75" | "map-random-boundary" | "map-parent-null"
+                )
+            }) {
+                let miss_percent = percent.parse()?;
+                if miss_percent > 100 {
+                    return Err("Map miss percentage must be in 
0..=100".into());
+                }
+                return Ok(Self::Map { miss_percent });
+            }
+            Ok(match name {
+                "list-short" => Self::Short,
+                "list-empty" => Self::Empty,
+                "list-deep" => Self::Deep,
+                "map-random-75" => Self::RandomMap,
+                "map-random-boundary" => Self::BoundaryMap,
+                "map-parent-null" => Self::MapParentNull,
+                "list-random-length" => Self::RandomLength,
+                "list-parent-null" => Self::ParentNull,
+                "list-child-null" => Self::ChildNull,
+                "list-struct" => Self::StructList,
+                "list-string" => Self::Strings,
+                "list-boolean" => Self::Booleans,
+                "list-uniform" => Self::Uniform,
+                "list-flat" => Self::Flat,
+                _ => return Err(format!("Unknown case {name}").into()),
+            })
+        }
+
+        fn input(self) -> Fixture {
+            let mut rng = StdRng::seed_from_u64(FIXTURE_SEED);
+            let is_map = matches!(
+                self,
+                Self::Map { .. } | Self::RandomMap | Self::BoundaryMap | 
Self::MapParentNull
+            );
+            let valid: Vec<bool> = (0..ROWS)
+                .map(|_| match self {
+                    Self::MapParentNull | Self::ParentNull => 
rng.random_range(0..100) >= 25,
+                    _ => true,
+                })
+                .collect();
+            let picks: Vec<Option<usize>> = (0..ROWS)
+                .map(|row| {
+                    let missing = match self {
+                        Self::Map { miss_percent } => row % 100 < miss_percent,
+                        Self::RandomMap | Self::BoundaryMap => 
rng.random_range(0..100) < 75,
+                        _ => false,
+                    };
+                    (valid[row] && !missing).then_some(2 * row)
+                })
+                .collect();
+            let selected_len = match self {
+                Self::Map { .. } | Self::RandomMap | Self::MapParentNull | 
Self::Uniform => 128,
+                Self::Empty => 0,
+                _ => 1,
+            };
+            let selected_lengths: Vec<usize> = (0..ROWS)
+                .map(|_| match self {
+                    Self::BoundaryMap => rng.random_range(108..=124),
+                    Self::RandomLength => rng.random_range(0..=8),
+                    _ => selected_len,
+                })
+                .collect();
+            let values: ArrayRef = if matches!(self, Self::Flat) {
+                Arc::new(Int32Array::from_iter_values(0..2 * ROWS as i32))
+            } else {
+                let offsets = OffsetBuffer::from_lengths(
+                    selected_lengths
+                        .iter()
+                        .flat_map(|&selected| [selected, 128]),
+                );
+                let count = *offsets.last().unwrap() as usize;
+                let leaf_null = |i: usize| i.is_multiple_of(11);
+                let values: ArrayRef = match self {
+                    Self::Strings => Arc::new(StringArray::from_iter(
+                        (0..count).map(|i| (!leaf_null(i)).then_some("é")),
+                    )),
+                    Self::Booleans => Arc::new(BooleanArray::from_iter(
+                        (0..count).map(|i| (!leaf_null(i)).then_some(i % 2 == 
0)),
+                    )),
+                    Self::Deep => {
+                        let offsets = OffsetBuffer::from_lengths(
+                            (0..count).map(|i| 1 + (i.wrapping_mul(0x9e3779b1) 
>> 19) % 4),
+                        );
+                        let values = Int32Array::from_iter(
+                            (0..*offsets.last().unwrap())
+                                .map(|i| (!leaf_null(i as 
usize)).then_some(i)),
+                        );
+                        list(offsets, Arc::new(values), None)
+                    }
+                    Self::StructList => {
+                        let nested_offsets =
+                            OffsetBuffer::from_lengths((0..count).map(|i| 1 + 
i % 3));
+                        let nested_count = *nested_offsets.last().unwrap();
+                        let nested = list(
+                            nested_offsets,
+                            
Arc::new(Int32Array::from_iter_values(0..nested_count)),
+                            None,
+                        );
+                        Arc::new(arrow::array::StructArray::from(vec![
+                            (
+                                Arc::new(Field::new("nested", 
nested.data_type().clone(), true)),
+                                nested,
+                            ),
+                            (
+                                Arc::new(Field::new("tag", DataType::Int32, 
false)),
+                                Arc::new(Int32Array::from_iter_values(0..count 
as i32)) as ArrayRef,
+                            ),
+                        ]))
+                    }
+                    Self::ChildNull => Arc::new(Int32Array::from_iter(
+                        (0..count).map(|i| (rng.random_range(0..100) >= 
15).then_some(i as i32)),
+                    )),
+                    _ => Arc::new(Int32Array::from_iter_values(0..count as 
i32)),
+                };
+                let validity = matches!(self, Self::Deep)
+                    .then(|| (0..2 * ROWS).map(|i| i % 13 != 0).collect());
+                list(offsets, values, validity)
+            };
+
+            let offsets = OffsetBuffer::from_lengths(std::iter::repeat_n(2, 
ROWS));
+            let parent_validity = (!valid.iter().all(|&v| v)).then(|| 
valid.into_iter().collect());
+            let input = if is_map {
+                let keys = 
Int32Array::from_iter_values((0..ROWS).flat_map(|row| {
+                    if matches!(self, Self::MapParentNull) || 
picks[row].is_some() {
+                        [1, 2]
+                    } else {
+                        [2, 3]
+                    }
+                }));
+                let entries = arrow::array::StructArray::from(vec![
+                    (
+                        Arc::new(Field::new("key", DataType::Int32, false)),
+                        Arc::new(keys) as ArrayRef,
+                    ),
+                    (
+                        Arc::new(Field::new("value", 
values.data_type().clone(), true)),
+                        Arc::clone(&values),
+                    ),
+                ]);
+                Arc::new(MapArray::new(
+                    Arc::new(Field::new("entries", 
entries.data_type().clone(), false)),
+                    offsets,
+                    entries,
+                    parent_validity,
+                    false,
+                )) as ArrayRef
+            } else {
+                list(offsets, Arc::clone(&values), parent_validity)
+            };
+            Fixture {
+                input,
+                values,
+                picks,
+            }
+        }
+
+        fn expr(self, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
+            let nested = Arc::new(Column::new("nested", 1));
+            let literal = |n| 
Arc::new(Literal::new(ScalarValue::Int32(Some(n))));
+            Ok(
+                if matches!(
+                    self,
+                    Self::Map { .. } | Self::RandomMap | Self::BoundaryMap | 
Self::MapParentNull
+                ) {
+                    Arc::new(ScalarFunctionExpr::try_new(
+                        Arc::new(ScalarUDF::from(SparkMapExtract::new())),
+                        vec![nested, literal(1)],
+                        schema,
+                        Arc::new(ConfigOptions::default()),
+                    )?)
+                } else {
+                    Arc::new(ListExtract::new(
+                        nested,
+                        literal(0),
+                        None,
+                        false,
+                        false,
+                        None,
+                        create_query_context_map(),
+                    ))
+                },
+            )
+        }
+    }
+
+    struct Fixture {
+        input: ArrayRef,
+        values: ArrayRef,
+        picks: Vec<Option<usize>>,
+    }
+
+    fn list(
+        offsets: OffsetBuffer<i32>,
+        values: ArrayRef,
+        validity: Option<NullBuffer>,
+    ) -> ArrayRef {
+        Arc::new(ListArray::new(
+            Arc::new(Field::new_list_field(values.data_type().clone(), true)),
+            offsets,
+            values,
+            validity,
+        ))
+    }
+
+    fn show_buffers(label: &str, data: &ArrayData) {
+        for (index, buffer) in data.buffers().iter().enumerate() {
+            eprintln!(
+                "{label}.buffer[{index}] used={} capacity={}",
+                buffer.len(),
+                buffer.capacity(),
+            );
+        }
+        if let Some(nulls) = data.nulls() {
+            eprintln!(
+                "{label}.validity used={} capacity={}",
+                nulls.len().div_ceil(8),
+                nulls.buffer().capacity(),
+            );
+        }
+        for (index, child) in data.child_data().iter().enumerate() {
+            show_buffers(&format!("{label}.child[{index}]"), child);
+        }
+    }
+
+    struct Query {
+        batches: Vec<RecordBatch>,
+        expression: Arc<dyn PhysicalExpr>,
+        spill_dir: PathBuf,
+    }
+
+    impl Query {
+        fn new(shape: Shape, fixture: &Fixture, batches: usize) -> 
Result<Self> {
+            let schema = Arc::new(Schema::new(vec![
+                Field::new("id", DataType::Int32, false),
+                Field::new(
+                    "nested",
+                    fixture.input.data_type().clone(),
+                    fixture.input.null_count() > 0,
+                ),
+            ]));
+            let input_batches = (0..batches)
+                .map(|batch| {
+                    let ids = Int32Array::from_iter_values(
+                        (0..ROWS).map(|row| (batch * ROWS + (row ^ ID_MASK)) 
as i32),
+                    );
+                    RecordBatch::try_new(
+                        Arc::clone(&schema),
+                        vec![Arc::new(ids), Arc::clone(&fixture.input)],
+                    )
+                })
+                .collect::<std::result::Result<_, _>>()?;
+            Ok(Self {
+                batches: input_batches,
+                expression: shape.expr(&schema)?,
+                spill_dir: std::env::var_os("COMET_BENCH_SPILL_DIR")
+                    .map_or_else(std::env::temp_dir, PathBuf::from),
+            })
+        }
+
+        fn execute(&self, budget: usize, expected: Option<&ArrayRef>) -> 
Result<Sample> {
+            let pool = 
Arc::new(PeakRecordingPool::new(Arc::new(GreedyMemoryPool::new(
+                budget,
+            ))));
+            let env = RuntimeEnvBuilder::new()
+                .with_memory_pool(pool.clone())
+                .with_temp_file_path(&self.spill_dir)
+                .build_arc()?;
+            let config = SessionConfig::new()
+                .with_batch_size(ROWS)
+                .with_target_partitions(1)
+                .with_sort_spill_reservation_bytes(MERGE_RESERVATION)
+                .with_spill_compression(SpillCompression::Uncompressed);
+            let ctx = SessionContext::new_with_config_rt(config, 
env).task_ctx();
+            let scan = MemorySourceConfig::try_new_exec(
+                std::slice::from_ref(&self.batches),
+                self.batches[0].schema(),
+                None,
+            )?;
+            let id = Arc::new(Column::new("id", 0));
+            let project = Arc::new(ProjectionExec::try_new(
+                [
+                    (id.clone() as Arc<dyn PhysicalExpr>, "id".to_string()),
+                    (Arc::clone(&self.expression), "payload".to_string()),
+                ],
+                scan,
+            )?);
+            let project_input: Arc<dyn ExecutionPlan> = project.clone();
+            let sort = SortExec::new(
+                LexOrdering::new([PhysicalSortExpr::new(
+                    id,
+                    SortOptions {
+                        descending: true,
+                        nulls_first: false,
+                    },
+                )])
+                .unwrap(),
+                Arc::clone(&project_input),
+            );
+            let runtime = tokio::runtime::Builder::new_current_thread()
+                .enable_all()
+                .build()?;
+            if let Some(expected) = expected {
+                assert!(Arc::ptr_eq(&project_input, sort.input()));
+                assert_eq!(sort.schema().field(1).data_type(), 
expected.data_type());
+                let mut stream = project.execute(0, Arc::clone(&ctx))?;
+                // Hold the diagnostic batches so an address cannot be 
recycled between batches.
+                let projected: Vec<RecordBatch> = runtime.block_on(async {
+                    let mut batches = Vec::new();
+                    while let Some(batch) = stream.try_next().await? {
+                        let payload = batch.column(1).to_data();
+                        payload.validate_full()?;
+                        assert_eq!(payload, expected.to_data());
+                        batches.push(batch);
+                    }
+                    Ok::<_, datafusion::common::DataFusionError>(batches)
+                })?;
+                show_buffers("projected", &projected[0].column(1).to_data());
+                let mut counter = RecordBatchMemoryCounter::new();
+                for batch in &projected {
+                    let payload =
+                        RecordBatch::try_from_iter([("payload", 
Arc::clone(batch.column(1)))])?;
+                    counter.count_batch(&payload);
+                }
+                let bytes = counter.memory_usage();
+                eprintln!(
+                    "projection_payload_capacity_bytes={bytes}; 
projected_batches={}",
+                    projected.len()
+                );
+            }
+
+            let expected_rows = self.batches.len() * ROWS;
+            let alloc = AllocationWindow::start();
+            let cpu_start = cpu_time()?;
+            let wall_start = Instant::now();
+            let count = runtime.block_on(async {
+                let mut stream = sort.execute(0, ctx)?;
+                let mut seen = 0;
+                while let Some(batch) = stream.try_next().await? {
+                    if let Some(expected) = expected {
+                        let ids = batch
+                            .column(0)
+                            .as_any()
+                            .downcast_ref::<Int32Array>()
+                            .unwrap();
+                        for (i, id) in ids.values().iter().enumerate() {
+                            let wanted = expected_rows - 1 - seen - i;
+                            assert_eq!(*id as usize, wanted);
+                            let row = (wanted % ROWS) ^ ID_MASK;
+                            assert_eq!(
+                                batch.column(1).slice(i, 1).to_data(),
+                                expected.slice(row, 1).to_data(),
+                            );
+                        }
+                    }
+                    seen += batch.num_rows();
+                    black_box(batch);
+                }
+                Ok::<_, datafusion::common::DataFusionError>(seen)
+            })?;
+            let metrics = sort.metrics().expect("sort metrics");
+            drop(sort);
+            drop(project);
+            drop(project_input);
+            // The runtime owns spill read-ahead tasks; drop it before another 
sample can start.
+            drop(runtime);
+            let wall = wall_start.elapsed();
+            let cpu = cpu_time()? - cpu_start;
+            let (alloc_base, alloc_peak) = alloc.finish();
+            assert_eq!(count, expected_rows);
+            assert_eq!(pool.reserved(), 0, "query left a reservation behind");
+
+            Ok(Sample {
+                wall_ns: wall.as_nanos(),
+                cpu_ns: cpu.as_nanos(),
+                reserved_peak: pool.peak_reserved(),
+                alloc_base,
+                alloc_peak,
+                spills: metrics.spill_count().expect("sort spill count"),
+                spill_bytes: metrics.spilled_bytes().expect("sort spilled 
bytes"),
+                spill_rows: metrics.spilled_rows().expect("sort spilled rows"),
+            })
+        }
+    }
+
+    struct Sample {
+        wall_ns: u128,
+        cpu_ns: u128,
+        reserved_peak: usize,
+        alloc_base: usize,
+        alloc_peak: usize,
+        spills: usize,
+        spill_bytes: usize,
+        spill_rows: usize,
+    }
+
+    pub fn run() -> Result<()> {
+        let args: Vec<_> = std::env::args().skip(1).collect();
+        let check = args.iter().any(|arg| arg == "--check" || arg == "--test");
+        let positional: Vec<_> = args
+            .iter()
+            .filter(|arg| !matches!(arg.as_str(), "--bench" | "--check" | 
"--test"))
+            .map(String::as_str)
+            .collect();
+        let (name, mib, samples, batches) = match positional.as_slice() {
+            [] => ("map-75", "128", "10", "12"),
+            [case] => (*case, "128", "10", "12"),
+            [case, mib] => (*case, *mib, "10", "12"),
+            [case, mib, samples] => (*case, *mib, *samples, "12"),
+            [case, mib, samples, batches] => (*case, *mib, *samples, *batches),
+            _ => return Err("expected CASE [MiB [SAMPLES [BATCHES]]] 
[--check]".into()),
+        };
+        let shape = Shape::parse(name)?;

Review Comment:
   Thanks for catching this. 
   I excluded the runner from default bench selection and made it skip 
unrelated wildcard filters.
   and explicit CI check/Clippy coverage also been added. 
   BTW, Workspace/Make filtering and all 9 wildcard cases pass locally.



##########
spark/src/test/scala/org/apache/spark/sql/benchmark/CometNestedCompactionBenchmark.scala:
##########
@@ -0,0 +1,206 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.benchmark
+
+import java.lang.management.ManagementFactory
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.{CometListenerBusUtils, SparkConf}
+import org.apache.spark.sql.{Row, SparkSession}
+import org.apache.spark.sql.comet.{CometNativeScanExec, CometSortExec}
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.exchange.ShuffleExchangeLike
+
+import com.sun.management.OperatingSystemMXBean
+
+import org.apache.comet.{CometConf, CometSparkSessionExtensions}
+import org.apache.comet.serde.OperatorOuterClass.Operator
+
+/**
+ * Run each memory budget in a separate Spark process so the off-heap budget 
is fixed before
+ * SparkContext starts. The native benchmark isolates the extraction and sort. 
This runner also
+ * measures the scan, Spark execution, and the noop sink.
+ */
+object CometNestedCompactionBenchmark extends CometBenchmarkBase {
+  private def batchSize = 8192
+  private def mergeReservation = 16 * 1024 * 1024
+
+  override def getSparkSession: SparkSession = {
+    val memory = sys.env.getOrElse("COMET_BENCHMARK_OFFHEAP", "128m")
+    val conf = new SparkConf()
+      .setAppName("CometNestedCompactionBenchmark")
+      .setMaster("local[1]")
+      .set(
+        "spark.shuffle.manager",
+        "org.apache.spark.sql.comet.execution.shuffle.CometShuffleManager")
+      .set("spark.ui.enabled", "false")
+      .set("spark.memory.offHeap.enabled", "true")
+      .set("spark.memory.offHeap.size", memory)
+      .set(CometConf.COMET_ONHEAP_ENABLED.key, "false")
+      .set(CometConf.COMET_OFFHEAP_MEMORY_POOL_TYPE.key, "greedy_unified")
+      .set("spark.sql.adaptive.enabled", "false")
+      .set("spark.sql.ansi.enabled", "false")
+      .set("spark.sql.files.minPartitionNum", "1")
+      .set("spark.sql.files.maxPartitionBytes", (512L * 1024 * 1024).toString)
+      .set(CometConf.COMET_BATCH_SIZE.key, batchSize.toString)
+      .set(CometConf.COMET_RESPECT_DATAFUSION_CONFIGS.key, "true")
+      .set(
+        "spark.comet.datafusion.execution.sort_spill_reservation_bytes",
+        mergeReservation.toString)
+      .set("spark.comet.datafusion.execution.spill_compression", 
"uncompressed")
+    SparkSession
+      .builder()
+      .config(conf)
+      .withExtensions(new CometSparkSessionExtensions)
+      .getOrCreate()
+  }
+
+  private case class Workload(input: String, lookups: Seq[String], isMap: 
Boolean)
+
+  private val wide = "sequence(0, 127)"
+  private val repeated = "array_repeat(CAST(id % 251 AS INT), 128)"
+  private def map(misses: Int): Workload = {
+    val missing = s"id % ${batchSize} % 100 < $misses"
+    Workload(
+      s"map(IF($missing, 2, 1), $repeated, IF($missing, 3, 2), $wide)",
+      Seq("nested[1]", "element_at(nested, 1)"),
+      isMap = true)
+  }
+
+  private def list(selected: String): Workload =
+    Workload(s"array($selected, $wide)", Seq("nested[0]", "element_at(nested, 
1)"), isMap = false)
+
+  private def verifySort(
+      plan: SparkPlan,
+      isMap: Boolean,
+      printPlan: Boolean = false): CometSortExec = {
+    val sorts = plan.collect { case sort: CometSortExec => sort }
+    require(sorts.size == 1, s"Expected exactly one native sort:\n$plan")
+    require(
+      plan.collect { case s: ShuffleExchangeLike => s }.isEmpty,
+      s"Unexpected shuffle:\n$plan")
+    require(
+      plan.collect { case s: CometNativeScanExec => s }.size == 1,
+      s"Expected native scan:\n$plan")
+    val sort = sorts.head
+    require(sort.executeColumnar().getNumPartitions == 1, s"Unexpected 
partitioning:\n$plan")
+    val block = Operator.parseFrom(sort.serializedPlanOpt.plan.get)
+    require(
+      block.hasSort && !block.getSort.hasFetch && block.getChildrenCount == 1,
+      block.toString)
+    val projection = block.getChildren(0)
+    require(
+      projection.hasProjection && 
projection.getProjection.getProjectListList.asScala.exists {
+        e =>
+          if (isMap) e.hasScalarFunc && e.getScalarFunc.getFunc == 
"map_extract"
+          else e.hasListExtract
+      },
+      s"Expected native extraction immediately below the sort:\n$block")
+    if (printPlan) {
+      System.err.println(s"Executed noop plan:\n$plan\nSerialized native sort 
plan:\n$block")
+    }
+    sort
+  }
+
+  override def runCometBenchmark(args: Array[String]): Unit = {
+    require(args.length <= 3, "Usage: [case] [batches] [samples]")
+    val name = args.headOption.getOrElse("map-75")
+    val workload = name match {
+      case "map-75" => map(75)
+      case "map-0" => map(0)
+      case "list-short" => list("array(CAST(id % 251 AS INT))")
+      case "list-empty" => list("CAST(array() AS ARRAY<INT>)")
+      case _ => throw new IllegalArgumentException(s"Unknown case $name")
+    }
+    val batches = args.lift(1).map(_.toInt).getOrElse(12)
+    val samples = args.lift(2).map(_.toInt).getOrElse(10)
+    require(batches > 1 && samples > 0)
+    val diagnostics = sys.env.get("COMET_BENCHMARK_DIAGNOSTICS").contains("1")
+    val rows = batchSize.toLong * batches
+    val cpu = 
ManagementFactory.getPlatformMXBean(classOf[OperatingSystemMXBean])
+    require(cpu != null && cpu.getProcessCpuTime >= 0, "Process CPU time 
unavailable")
+    val memory = spark.sparkContext.getConf.get("spark.memory.offHeap.size")
+    val sparkOnly = CometConf.COMET_ENABLED.key -> "false"
+    val comet = Seq(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_NATIVE_SCAN_ENABLED.key -> "true")
+
+    val out = output.fold(System.out)(new java.io.PrintStream(_))
+    withTempPath { dir =>
+      withTempTable("parquetV1Table") {
+        withSQLConf(sparkOnly) {
+          prepareTable(
+            dir,
+            spark.range(0, rows, 1, 1).selectExpr("id", s"${workload.input} AS 
nested"))
+        }
+        
out.println("case,lookup,offheap,sample,wall_ns,process_cpu_ns,spill_count,spilled_bytes")
+        for (lookup <- workload.lookups) {
+          def reportPhase(phase: String): Unit =
+            if (diagnostics) System.err.println(s"$name / $lookup / $memory: 
$phase")
+
+          // Sorting on the extracted array forces the optimizer to evaluate 
extraction first.
+          def query =
+            spark.sql(
+              s"SELECT id, $lookup AS payload FROM parquetV1Table " +
+                "SORT BY payload NULLS FIRST, id")

Review Comment:
   Thanks for pointing this out. 
   `benchmarkung.md`has been updated, mainly for distinguish the sort keys (`id 
DESC` vs. `payload NULLS FIRST, id`), and clarify that CPU and spill results 
are not directly comparable.



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