mbutrovich commented on code in PR #7696: URL: https://github.com/apache/datafusion-comet/pull/7696#discussion_r4789763188
########## 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: This comment states a crossover that the numbers in the description don't show. Combining 512-row batches in a spilling single-key sort went from 51.4 to 54.0 ms (5%), and the description puts laptop noise at 10% to 20%. The 1024-row spilling single-key case, where both sides pass the batches through unchanged, differs by more (40.1 to 42.7 ms). The "never slower" half doesn't hold either: the in-order two-key spilling case at 256 rows went from 49.1 to 51.0 ms. The limit matters because blocks of 512 to 4095 rows still produce one merge stream each, and #5686 measured 1.49x from coalescing 1024-row batches. Could the 512 and 1024 cases, run with combining on a server CPU (x86_64 with AVX2, which Comet builds for), go in the re-evaluation issue? For this PR, the comment can say what the data supports: ```suggestion /// The gain shrinks as batches grow. In `sort_small_batches` the differences at 512 rows were /// within the run's noise, so this limit is a conservative choice rather than a measured /// crossover. const MAX_SMALL_BATCH_ROWS: usize = 512; ``` ########## 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: The 16% belongs here, but I don't think the copy is the cause. As I read DataFusion 55.2, without the coalescer `ExternalSorter` concatenates the raw batches of a single-key sort into runs of up to `sort_in_place_threshold_bytes` of reserved memory, which is 2x the data ([`in_mem_sort_stream`](https://github.com/apache/datafusion/blob/500744d5c25499055e3b2ca46b022bc425989203/datafusion/physical-plan/src/sorts/sort.rs#L634-L644), [`coalesce_in_mem_batches_into_runs`](https://github.com/apache/datafusion/blob/500744d5c25499055e3b2ca46b022bc425989203/datafusion/physical-plan/src/sorts/sort.rs#L676-L708)). That is about 512 KiB of data per run at the default 1 MiB threshold. With the coalescer, each combined batch holds up to 512 KiB and reserves up to 1 MiB, so it fills a run by itself and the sort skips its own concat. Both paths copy each row once into runs of about the same size. Could we drop the cause from the doc string for now, and put a profile of that stage with the flag off and on in the re-evaluation issue? If the time goes somewhere else, the cost may be avoidable. ```suggestion "slower, about 16% in one measurement. It helps most when a sort spills over many " + ``` -- 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]
