parthchandra commented on code in PR #7696: URL: https://github.com/apache/datafusion-comet/pull/7696#discussion_r4795848327
########## native/operators/src/sort_input_coalesce.rs: ########## @@ -0,0 +1,1168 @@ +// 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. + +//! Combines small input batches before a native sort. +//! +//! On its spill path DataFusion's sort merges one stream per buffered batch, so thousands of +//! tiny shuffle blocks make it very slow. Below the in-place threshold the sort concatenates its +//! input itself, so batches pass through until a partition's input reaches that threshold. The +//! gate never closes again, so a sort whose share is below the threshold gets a copy it does not +//! need. +//! +//! This sits in front of the sort rather than in the shuffle reader because only the sort's merge +//! cost grows with the number of batches. Arrow's `BatchCoalescer` has no byte limit and copies +//! as batches arrive, and `DecodedBatchCoalescer` takes only flat types, so neither lets the held +//! memory be reserved exactly for any input. + +use std::fmt::Formatter; +use std::sync::Arc; + +use arrow::compute::concat_batches; +use arrow::datatypes::DataType; +use arrow::record_batch::RecordBatch; +use datafusion::common::tree_node::TreeNodeRecursion; +use datafusion::common::utils::memory::get_record_batch_memory_size; +use datafusion::common::{DataFusionError, Result}; +use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation}; +use datafusion::execution::{async_try_stream, TaskContext}; +use datafusion::physical_expr::PhysicalExpr; +use datafusion::physical_plan::execution_plan::CardinalityEffect; +use datafusion::physical_plan::metrics::{ + BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, MetricsSet, RecordOutput, +}; +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; +use datafusion::physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, SendableRecordBatchStream, +}; +use futures::TryStreamExt; + +/// The cap is half the in-place threshold because the sort reserves about twice a batch's size. +/// The bounds also keep string and binary offsets far below the i32 limit. +const MIN_GROUP_BYTES: usize = 64 * 1024; +const MAX_GROUP_BYTES: usize = 4 * 1024 * 1024; + +/// In `sort_small_batches`, combining 512-row batches made a spilling single-key sort slower, +/// while 384 rows or fewer was never slower. +const MAX_SMALL_BATCH_ROWS: usize = 512; Review Comment: Agreed, the numbers don't show a crossover. I applied your wording, and the description now says the 512-row limit is a conservative choice. The 512 and 1024 cases with combining on, on an x86_64 server, are in #7852. ########## spark/src/main/scala/org/apache/comet/CometConf.scala: ########## @@ -414,6 +414,31 @@ object CometConf extends ShimCometConf { createExecEnabledConfig("filter", defaultValue = true) val COMET_EXEC_SORT_ENABLED: ConfigEntry[Boolean] = createExecEnabledConfig("sort", defaultValue = true) + val COMET_EXEC_SORT_COALESCE_INPUT_ENABLED: ConfigEntry[Boolean] = + conf(s"$COMET_EXEC_CONFIG_PREFIX.sort.coalesceInput.enabled") + .category(CATEGORY_EXEC) + .doc( + "Experimental: whether `CometSort` combines small input batches before sorting them. " + + "A shuffle with many map tasks and many partitions gives each reduce task many tiny " + + "Arrow batches. DataFusion's sort then merges one stream per batch, at least when it " + + "spills or sorts on more than one key, which is slow. Batches pass through " + + "unchanged until a task's sort input is large enough that the sort would merge " + + "instead of sorting in place, so small sorts are not affected. After that, batches " + + "with fewer rows than half of `spark.comet.batchSize`, and fewer than 512, are " + + "combined into batches of at most `spark.comet.batchSize` rows and half of " + + "DataFusion's in-place sort threshold in bytes, 512 KiB by default, kept between 64 " + + "KiB and 4 MiB. The threshold is " + + "`spark.comet.datafusion.execution.sort_in_place_threshold_bytes`, which takes " + + "effect with `spark.comet.exec.respectDataFusionConfigs=true`. A sort with a " + + "limit is not affected. Off by default for two reasons. A combined batch is larger " + + "than the batches it replaces, so a sort with a very small memory share can fail " + + "with \"Not enough memory to continue external sort\" where the original batches " + + "fit. And a sort on one key whose input is combined but that does not spill gets " + + "slower, about 16% in one measurement, because DataFusion already combines its runs " + + "in memory, so the copy is extra work. It helps most when a sort spills over many " + Review Comment: Good point. I dropped the cause from the doc string with your wording. The description now says the cause isn't settled, and that both paths copy each row once. A profile of that stage with the flag off and on is item 3 in #7852. ########## spark/src/main/scala/org/apache/spark/sql/comet/operators.scala: ########## @@ -1655,7 +1656,13 @@ case class CometSortExec( CometMetricNode.baselineMetrics(sparkContext) ++ Map( "spill_count" -> SQLMetrics.createMetric(sparkContext, "number of spills"), - "spilled_bytes" -> SQLMetrics.createSizeMetric(sparkContext, "total spilled bytes")) + "spilled_bytes" -> SQLMetrics.createSizeMetric(sparkContext, "total spilled bytes"), + "coalesced_input_batches" -> SQLMetrics.createMetric( + sparkContext, + "number of small input batches combined into larger ones"), + "coalesced_output_batches" -> SQLMetrics.createMetric( + sparkContext, + "number of batches produced by combining small input batches")) Review Comment: Done. `CometSortExec` now declares the two metrics only when `nativeOp.getSort.getCoalesceInput` is set, like the join operators. `metrics.md` says they appear only with the config on. With the config off, the `CometTaskMetricsSuite` test now checks that they are not declared. ########## docs/source/contributor-guide/memory_management.md: ########## @@ -583,8 +600,10 @@ unbounded, so nobody charged for them at allocation time. Whether they are charg on who holds them. DataFusion's `ExternalSorter` reserves `get_reserved_bytes_for_record_batch` for every batch it retains, and the hash join build side reserves `get_record_batch_memory_size` for each incoming batch; both read buffer sizes off the `ArrayData` and apply equally to imported -buffers. So an imported batch that a sort or join has buffered _is_ reserved in Comet's pool, and -through a unified pool is charged to Spark. The same batch held by an operator that does not reserve +buffers. The coalescer that can sit in front of a native sort also reserves the batches it holds, +at twice their size to cover the combined copy. So an imported batch that a sort, a join or that Review Comment: Fixed. It now says the coalescer reserves the batches it holds plus their combined copy. ########## native/core/src/execution/memory_pools/fair_pool.rs: ########## @@ -448,6 +448,169 @@ mod tests { (0..n).map(|_| tasks.start()).collect() } + /// Sorts 3000 batches of 60 wide rows in `pool`, optionally combining them first. Returns + /// how many rows came out, how many times the sort spilled, and how many input batches were + /// combined. + async fn sort_small_batches( Review Comment: Done. `sort_in_pool`, built on `sort_on` and `try_collect_with`, replaces both helpers. It returns the sorted output with the spill and combine counts. The share test now also checks that the combined output equals the plain one. I removed the two spilling-sort tests and their `spilling_sort` and `check_spilling_sort` helpers from `sort_input_coalesce.rs`. -- 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]
