sunchao commented on code in PR #7316: URL: https://github.com/apache/datafusion-comet/pull/7316#discussion_r4417648841
########## native/core/src/execution/operators/batch_slicer.rs: ########## @@ -0,0 +1,90 @@ +// 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. + +use arrow::array::RecordBatch; + +/// Splits the batches a JVM-fed leaf receives so that none is wider than the session batch +/// size. The JVM sizes those batches itself, so this is the one place a smaller native batch +/// size takes effect on them; see `scalar_batch_rows` in `jni_api` for why it can be smaller. +/// Slices share the input's buffers, so splitting copies nothing. +pub(crate) struct BatchSlicer { + max_rows: usize, + rest: Option<RecordBatch>, +} + +impl BatchSlicer { + pub fn new(max_rows: usize) -> Self { + Self { + max_rows: max_rows.max(1), + rest: None, + } + } + + /// Takes a batch in and returns its first slice, holding the remainder for `pending`. + pub fn slice(&mut self, batch: RecordBatch) -> RecordBatch { + if batch.num_rows() <= self.max_rows { + return batch; + } + let head = batch.slice(0, self.max_rows); + self.rest = Some(batch.slice(self.max_rows, batch.num_rows() - self.max_rows)); Review Comment: Could we use DataFusion’s `BatchSplitStream` here, as `ExplodeExec` does? Making a slice of the entire remainder rescans its validity bitmap to compute its null count. Every subsequent poll scans most of those same bits again. In a release-mode probe with the pinned Arrow 59.3.1, splitting 4,194,304 alternating-null integers into 512-row batches took 164–181 ms with this implementation and about 1 ms when slicing the original batch at successive offsets. This measures just the slicer. It happens even when the scalar cap legitimately requires smaller batches. ########## native/core/src/execution/operators/scan.rs: ########## @@ -365,21 +373,25 @@ impl Stream for ScanStream<'_> { type Item = DataFusionResult<RecordBatch>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { - let mut timer = self.baseline_metrics.elapsed_compute().timer(); - let mut scan_batch = self.scan.batch.try_lock().unwrap(); + let this = self.get_mut(); + if let Some(batch) = this.slicer.pending() { + return Poll::Ready(Some(Ok(batch))); + } + let mut timer = this.baseline_metrics.elapsed_compute().timer(); + let mut scan_batch = this.scan.batch.try_lock().unwrap(); let result = match &*scan_batch { None => { - self.scan.waker.register(cx.waker()); + this.scan.waker.register(cx.waker()); Poll::Pending } // EOF stays buffered: a re-poll ends the stream again and `get_next_batch` has // nothing to pull. Some(InputBatch::EOF) => Poll::Ready(None), Some(InputBatch::Batch(columns, num_rows)) => { - self.baseline_metrics.record_output(*num_rows); - let maybe_batch = self.build_record_batch(columns, *num_rows); - Poll::Ready(Some(maybe_batch)) + this.baseline_metrics.record_output(*num_rows); Review Comment: Could `ScanStream` and `ShuffleScanStream` record `output_rows` for each slice they emit? With a 10-row input and a four-row cap, this records ten on the first poll. If a downstream limit stops after that four-row slice, the remaining six never leave the scan, but its output metric still reports ten. A test that stops polling after the first slice would catch this. ########## native/core/src/execution/operators/scan.rs: ########## @@ -365,21 +373,25 @@ impl Stream for ScanStream<'_> { type Item = DataFusionResult<RecordBatch>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { - let mut timer = self.baseline_metrics.elapsed_compute().timer(); - let mut scan_batch = self.scan.batch.try_lock().unwrap(); + let this = self.get_mut(); + if let Some(batch) = this.slicer.pending() { Review Comment: A pending slice can be skipped by an upstream error. I compared the base and head native libraries on Spark 4.1.3 with the same `LIMIT 3` plan, a two-row batch size, and a JVM reader that returns ten rows on its first load and throws on its second. The base returned all three rows after one load. This head returned two rows, then opened the next JVM batch and threw before returning row three. With a ten-row batch size the head succeeds too. After emitting the first slice the scan clears its shared input slot. On the next `executePlan`, `pull_input_batches` refills that slot before `poll_next` can return the pending slice here. Could both JVM-fed scans defer the next upstream read until the current batch’s slices are exhausted? This also keeps a short-circuiting consumer from paying for an unnecessary read. ########## spark/src/test/resources/sql-tests/operators/large_scalar_string.sql: ########## @@ -0,0 +1,60 @@ +-- 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. The plan runs natively and panicked before the +-- fix; the answer-only mode is because 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 spark_answer_only Review Comment: I ran this fixture with `ENABLE_COMET_STRICT_TESTING=true` on Spark 4.1.3. It failed here with “Plan was fully native in Comet. Call checkSparkAnswerAndOperator instead.” Both aggregate stages ran natively. In the default mode, this directive would also pass if the aggregate fell back to Spark and stopped exercising the original bug. Could we keep an explicit assertion that the grouped count runs in `CometHashAggregate` and make the case pass strict mode? The `missingInput` problem mentioned above can be handled separately. ########## native/core/src/execution/planner.rs: ########## @@ -965,7 +994,18 @@ impl PhysicalPlanner { ExprStruct::Subquery(expr) => { let id = expr.id; let data_type = to_arrow_datatype(expr.datatype.as_ref().unwrap()); - Ok(Arc::new(Subquery::new(self.exec_context_id, id, data_type))) + let subquery = Subquery::new(self.exec_context_id, id, data_type); + // The JVM registers the result before the plan is built, so its size is known + // here and can bound the rows per batch. + if matches!(subquery.data_type, DataType::Utf8 | DataType::Binary) + && self.exec_context_id != TEST_EXEC_CONTEXT_ID + { + let no_rows = RecordBatch::new_empty(Arc::new(Schema::empty())); + if let ColumnarValue::Scalar(value) = subquery.evaluate(&no_rows)? { + self.note_scalar_bytes(&value); Review Comment: The size recorded here is the size of the subquery result. A parent can produce a larger scalar before it is expanded. With the fixture’s 256 KiB `s`, I ran this on Spark 4.1.3: ```sql SELECT sum(length(concat(repeat((SELECT max(s) FROM wide), 8), cast(id AS string)))) FROM range(0, 8192, 1, 1) ``` Spark returned `17179900842`. With a native range and aggregates, this head failed with `byte array offset overflow`. Changing only `spark.comet.batchSize` to 256 returned the Spark result. Here `repeat` creates a 2 MiB scalar before `concat` broadcasts it. Could the expansion use the resulting scalar’s width, or evaluate this case in bounded chunks? -- 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]
