sunchao commented on code in PR #7316: URL: https://github.com/apache/datafusion-comet/pull/7316#discussion_r4436276887
########## native/core/src/execution/planner/scalar_expansion.rs: ########## @@ -0,0 +1,285 @@ +// 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. + +//! Bounds the rows per batch under an operator that expands a large string scalar. +//! +//! An aggregate, a hash partitioner and most string kernels expand a scalar argument to the +//! batch's length: a 256 KiB string over the default 8192-row batch needs 2 GiB of value bytes, +//! past the 32-bit offsets of Arrow's `Utf8` and `Binary` arrays. Spark evaluates such scalars +//! row by row and never materializes the column. See +//! <https://github.com/apache/datafusion-comet/issues/7247>. +//! +//! The bound is enforced right under the operator that evaluates the expressions, with a +//! [`BatchSplitExec`], because the operators below do not keep the session's batch size: a +//! filter coalesces its output toward DataFusion's default size and a window emits its whole +//! partition. + +use std::sync::Arc; + +use arrow::datatypes::{DataType, Schema}; +use arrow::record_batch::{RecordBatch, RecordBatchOptions}; +use datafusion::common::ScalarValue; +use datafusion::logical_expr::{ColumnarValue, Volatility}; +use datafusion::physical_expr::expressions::{Column, InListExpr}; +use datafusion::physical_expr::{PhysicalExpr, ScalarFunctionExpr}; +use datafusion::physical_plan::ExecutionPlan; +use datafusion::prelude::SessionConfig; +use datafusion_comet_operators::BatchSplitExec; +use datafusion_comet_spark_expr::jvm_udf::JvmScalarUdfExpr; +use datafusion_comet_spark_expr::monotonically_increasing_id::MonotonicallyIncreasingId; +use datafusion_comet_spark_expr::{ + RandExpr, RandStrExpr, RandnExpr, ShuffleExpr, Subquery, UuidExpr, +}; + +use super::{PhysicalPlanner, TEST_EXEC_CONTEXT_ID}; + +/// The most value bytes the string and binary scalars of one operator may take once expanded to +/// a batch's length. Arrow's 32-bit offsets make 2 GiB the hard limit; half of it leaves room for +/// kernels that append to the expanded value, such as `concat`, and matches what an Arrow Java +/// vector can hold before its reallocation fails. +const SCALAR_EXPANSION_BYTES: usize = 1 << 30; + +/// The most rows per batch at which `scalar_bytes`, expanded to the batch's length, stay within +/// `SCALAR_EXPANSION_BYTES`; unbounded when there is nothing to expand. +fn scalar_rows_cap(scalar_bytes: usize) -> usize { + if scalar_bytes == 0 { + return usize::MAX; + } + (SCALAR_EXPANSION_BYTES / scalar_bytes).max(1) +} + +impl PhysicalPlanner { + /// Wraps `input` so that the batches it emits keep the string and binary scalars in `exprs`, + /// expanded to a batch's length, within `SCALAR_EXPANSION_BYTES`. Returns `input` as is when + /// the widest batch it can emit already does. + pub(crate) fn bound_scalar_expansion<'a>( + &self, + input: Arc<dyn ExecutionPlan>, + exprs: impl IntoIterator<Item = &'a Arc<dyn PhysicalExpr>>, + ) -> Arc<dyn ExecutionPlan> { + let schema = input.schema(); + let bytes: usize = exprs + .into_iter() + .map(|expr| self.expanded_scalar_bytes(expr, &schema)) + .sum(); + let cap = scalar_rows_cap(bytes); + let batch_size = self.session_ctx.copied_config().batch_size(); + // A filter below coalesces toward DataFusion's default batch size whatever the session's + // is, so a session batch size under the default does not bound what arrives here. + let widest_input = batch_size.max(SessionConfig::default().batch_size()); + if cap < widest_input { Review Comment: A native window can emit more rows than `widest_input`. I ran this on Spark 4.1.3 with AQE off and `spark.comet.batchSize=8192`. ```sql SELECT sum(length(concat(repeat('x', 65536), CAST(tile AS STRING)))) FROM ( SELECT ntile(2) OVER (ORDER BY id) AS tile FROM range(0, 32768, 1, 1) ) ``` Spark returned `2147516416`. On this commit the plan used `CometWindowExec` and failed with `CometNativeException: byte array offset overflow`. The 64 KiB scalar gives a cap of 16,384 rows, so this comparison skips the splitter. The window emits all 32,768 rows in one batch. Could the expanding operator enforce the cap against incoming batches whenever the producer can exceed it? This query would cover the branch the existing 8,192-row window test misses. ########## spark/src/test/resources/sql-tests/operators/large_scalar_string.sql: ########## @@ -0,0 +1,72 @@ +-- 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. + +-- A string scalar, from a scalar subquery or a literal, is expanded to the batch length by the +-- aggregate, the hash partitioner and string kernels. A 256 KiB string over the default 8192-row +-- batch needs 2 GiB of value bytes, past Arrow's 32-bit offsets. Spark evaluates row by row. +-- The ids are written in one task so they arrive in one batch. Constant folding is on so that +-- `repeat('x', 262144)` reaches Comet as the literal it is in a Spark session. +-- See https://github.com/apache/datafusion-comet/issues/7247. +-- Config: spark.sql.adaptive.enabled=false +-- Config: spark.comet.exec.range.enabled=true +-- ConstantFolding: enabled + +statement +CREATE TABLE test_large_scalar_wide(s string) USING parquet + +statement +INSERT INTO test_large_scalar_wide SELECT repeat('x', 262144) + +statement +CREATE TABLE test_large_scalar_ids(k int) USING parquet + +statement +INSERT INTO test_large_scalar_ids SELECT /*+ COALESCE(1) */ CAST(id % 2 AS INT) FROM range(8192) + +-- count of the scalar in a grouped aggregate, which expands it to the batch length. A literal +-- rather than the subquery: the harness's missingInput check trips on a grouped count of a +-- scalar subquery whatever the string's size, which is a separate plan issue. +query +SELECT k, count(repeat('x', 262144)) FROM test_large_scalar_ids GROUP BY k ORDER BY k Review Comment: With this fixture’s optimizer settings on Spark 4.1.3, the optimized aggregate is `count(1)`. The native-plan assertion can pass without the aggregate ever receiving the 256 KiB literal. Excluding `org.apache.spark.sql.catalyst.optimizer.NullPropagation` for this case kept the wide literal inside `count` in the optimized plan. Could the grouped-count regression preserve that argument so it actually exercises scalar expansion? -- 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]
