comphead commented on code in PR #6988:
URL: https://github.com/apache/datafusion-comet/pull/6988#discussion_r4414768011


##########
spark/src/test/scala/org/apache/spark/sql/comet/execution/arrow/CacheBatchCoalescerSuite.scala:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.comet.execution.arrow
+
+import java.nio.charset.StandardCharsets.UTF_8
+
+import org.scalatest.funsuite.AnyFunSuite
+
+import org.apache.arrow.memory.RootAllocator
+import org.apache.spark.sql.catalyst.expressions.AttributeReference
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.types.StringType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+
+class CacheBatchCoalescerSuite extends AnyFunSuite {
+
+  private val numColumns = 4
+  private val attrs = (0 until numColumns).map(i => AttributeReference(s"s$i", 
StringType)())
+
+  // A batch of Spark's own on-heap vectors, which the coalescer always 
copies. Row `i` of column
+  // `c` holds "c<c>r<first + i>", so the output order can be checked.
+  private def sparkBatch(first: Int, rows: Int): ColumnarBatch = {
+    val columns = (0 until numColumns).map { c =>
+      val vector = new OnHeapColumnVector(rows, StringType)
+      (0 until rows).foreach(i => vector.putByteArray(i, s"c${c}r${first + 
i}".getBytes(UTF_8)))
+      vector: ColumnVector
+    }
+    new ColumnarBatch(columns.toArray, rows)
+  }
+
+  // Runs `f` on a coalescer over `inputs`, checks that closing it returns 
every byte it took, and
+  // returns the most the allocator held at once.
+  private def withCoalescer(limit: Long, inputs: Seq[ColumnarBatch], target: 
Int)(

Review Comment:
   Every test here, and the new `CometInMemoryCacheSuite` cases, drains the 
coalescer before `close()` runs, so the release paths for a partly consumed one 
have no test: `pending`, `filled`, a held `readyRoot` and `emitted` at close 
time, and the `NonFatal` cleanup in `startPending`. A change that made 
`close()` skip `pending` or `filled` would still pass. Could one case take a 
single batch from a multi-batch input (a 25-row `sparkBatch` at target 10 
leaves a partial `pending` and a non-empty `filled`) and then close, and 
another use an allocator limit small enough that `startPending` or 
`writeColumns` throws, both checking the allocator returns to zero?



##########
spark/src/main/scala/org/apache/spark/sql/comet/execution/arrow/CacheBatchCoalescer.scala:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.comet.execution.arrow
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.util.control.NonFatal
+
+import org.apache.arrow.memory.BufferAllocator
+import org.apache.arrow.vector.VectorSchemaRoot
+import org.apache.spark.TaskContext
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.comet.util.Utils
+import org.apache.spark.sql.vectorized.ColumnarBatch
+
+import org.apache.comet.vector.NativeUtil
+
+/**
+ * The columnar input of a cache build, with its small batches combined.
+ *
+ * The columnar write stores each batch it is handed as one cached batch, and 
nothing upstream
+ * bounds how small a batch can be. A shuffle read returns at least one batch 
per map output
+ * block, so a relation cached from a shuffle over many map tasks would 
otherwise hold thousands
+ * of batches of a few hundred rows. Each carries its own message metadata, 
compression framing
+ * and statistics row, and every read of the cache pays for the batch count.
+ *
+ * A batch the writer can store as it stands, Arrow-backed and laid out the 
way the reader reads
+ * it, is passed through when it holds at least half of `targetRows`, so full 
native batches are
+ * still written without a copy. Every other batch is copied into batches of 
`targetRows` rows,
+ * the size the row path cuts at, and split where it crosses that size. A 
small batch is worth the
+ * copy, and a batch the writer cannot store as it stands has to be copied 
into Arrow anyway, so
+ * combining it costs nothing more. The copy reads each column through the 
`ColumnVector`
+ * interface, as `ArrowWriter.writeColumns` does for any input, so it handles 
dictionary-encoded
+ * and nested columns, and offsets that do not start at zero, as a native 
producer's sliced arrays
+ * can have. Arrow's `VectorAppender` assumes they start at zero.
+ *
+ * Row order is kept: the rows copied so far are emitted before a batch that 
passes through. A
+ * large input is copied one output batch at a time, as the consumer asks for 
them, so the batches
+ * open at once do not grow with its size. The input is not advanced until it 
has been copied in
+ * full, because a native producer releases the batch it returned last when it 
is asked for the
+ * next one.
+ *
+ * The batches built here are owned here. Each is released when the next batch 
is requested, and
+ * whatever is still open when the task completes is released then. A batch 
passed through still
+ * belongs to its producer.
+ */
+private[arrow] class CacheBatchCoalescer(
+    input: Iterator[ColumnarBatch],
+    attrs: Seq[Attribute],
+    targetRows: Int,
+    allocator: BufferAllocator)
+    extends Iterator[ColumnarBatch] {
+
+  require(targetRows > 0, s"The target batch size must be positive, but was 
$targetRows")
+
+  private val arrowSchema =
+    Utils.toArrowSchema(Utils.fromAttributes(attrs), 
CometArrowStream.NATIVE_TIMEZONE)
+  private val readerFields = arrowSchema.getFields.asScala.toIndexedSeq
+
+  // A batch at least this large that the writer can store as it stands is not 
copied.
+  private val passThroughRows = math.max(1, targetRows / 2)

Review Comment:
   The threshold follows `spark.sql.inMemoryColumnarStorage.batchSize`, so it 
is 5000 rows by default, and default 8192-row native batches pass through. With 
`spark.comet.batchSize` at 4096 or lower, or the cache batch size above 16384, 
every native Arrow batch now takes the `ArrowWriter.writeColumns` copy, where 
before it was written without one. The table in the description measures inputs 
of 250 to 775 rows, where the copy clearly pays. Could you measure the build at 
4096-row native batches against main, or tie the threshold to Comet's batch 
size? I have not measured the copy cost.



##########
docs/source/user-guide/latest/in-memory-cache.md:
##########
@@ -77,6 +77,14 @@ metrics only through that scan.
 
 Each cached batch is stored as a single Arrow IPC record batch message and its 
body.
 
+A cache built from rows cuts its batches at 
`spark.sql.inMemoryColumnarStorage.batchSize` rows,
+10000 by default, as Spark's own format does. A cache built from the Arrow 
batches of Comet

Review Comment:
   Spark's row path also ends a batch once it reaches about 4 MiB 
(`ColumnBuilder.MAX_BATCH_SIZE_IN_BYTE` in `InMemoryRelation`, in 3.4, 3.5 and 
4.1), while Comet's row path and this coalescer cut by rows only. Could the 
sentence say that, so readers know wide rows give larger cached batches than 
Spark's format?



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