pan3793 commented on code in PR #59566:
URL: https://github.com/apache/spark/pull/59566#discussion_r4623768787


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/ParquetStringWriteBenchmark.scala:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.execution.benchmark
+
+import java.lang.management.ManagementFactory
+import java.util.concurrent.atomic.AtomicLong
+
+import com.sun.management.ThreadMXBean
+import org.apache.hadoop.fs.Path
+import org.apache.parquet.column.ParquetProperties
+
+import org.apache.spark.benchmark.Benchmark
+import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd}
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.functions.col
+
+/**
+ * Measures Parquet string writes from heap-backed row slices after a shuffle.
+ * Compare unmodified and patched writers in fresh JVMs with the same settings.
+ * Allocation counts cover the whole JVM, including driver work; CPU counts 
cover executor tasks.
+ *
+ * To run:
+ * {{{
+ * build/sbt "sql/Test/runMain 
org.apache.spark.sql.execution.benchmark.ParquetStringWriteBenchmark"
+ * }}}
+ * An optional argument selects one workload: short, wide, long, or 
low-cardinality.
+ */
+object ParquetStringWriteBenchmark extends SqlBasedBenchmark {

Review Comment:
   Suggest removing this benchmark and keeping its code and results in the PR 
description. It is a one-off before/after allocation measurement with custom 
instrumentation, which isn't worth keeping in the repo.
   
   This also fixes the failing "Java 25 build with Maven" check: with Maven's 
`-release 21`, L94 and L103 fail with `value getTotalThreadAllocatedBytes is 
not a member of com.sun.management.ThreadMXBean`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetWriteSupport.scala:
##########
@@ -243,8 +244,20 @@ class ParquetWriteSupport extends 
WriteSupport[InternalRow] with Logging {
 
       case _: StringType =>
         (row: SpecializedGetters, ordinal: Int) =>
-          recordConsumer.addBinary(
-            Binary.fromReusedByteArray(row.getUTF8String(ordinal).getBytes))
+          val value = row.getUTF8String(ordinal)
+          // Mark the bytes as reused so Parquet copies values that it retains.
+          recordConsumer.addBinary(value.getBaseObject match {
+            case bytes: Array[Byte] =>
+              if (value.getBaseOffset == Platform.BYTE_ARRAY_OFFSET &&
+                  value.numBytes() == bytes.length) {
+                // Use the smaller wrapper for whole-array strings to avoid 
extra allocation.
+                Binary.fromReusedByteArray(bytes)
+              } else {
+                Binary.fromReusedByteArray(bytes,
+                  (value.getBaseOffset - Platform.BYTE_ARRAY_OFFSET).toInt, 
value.numBytes())
+              }

Review Comment:
   nit: this repeats `UTF8String.getByteBuffer()`, minus its bounds and 
int-narrowing checks. Reusing it keeps the checks and drops the whole-array 
branch, whose comment doesn't hold anyway: both branches allocate one `Binary`.
   ```suggestion
               case _: Array[Byte] =>
                 val buf = value.getByteBuffer
                 Binary.fromReusedByteArray(
                   buf.array(), buf.arrayOffset() + buf.position(), 
buf.remaining())
   ```
   The `Platform` import then becomes unused. The short-lived `ByteBuffer` 
should be scalar-replaced, but worth confirming with your allocation numbers.
   
   If you keep the whole-array branch instead, please add a prefix-slice test 
(offset 0, `numBytes < bytes.length`): no current test catches a check that 
looks only at the offset.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetWriteSupport.scala:
##########
@@ -243,8 +244,20 @@ class ParquetWriteSupport extends 
WriteSupport[InternalRow] with Logging {
 
       case _: StringType =>
         (row: SpecializedGetters, ordinal: Int) =>
-          recordConsumer.addBinary(
-            Binary.fromReusedByteArray(row.getUTF8String(ordinal).getBytes))
+          val value = row.getUTF8String(ordinal)
+          // Mark the bytes as reused so Parquet copies values that it retains.
+          recordConsumer.addBinary(value.getBaseObject match {
+            case bytes: Array[Byte] =>
+              if (value.getBaseOffset == Platform.BYTE_ARRAY_OFFSET &&
+                  value.numBytes() == bytes.length) {
+                // Use the smaller wrapper for whole-array strings to avoid 
extra allocation.
+                Binary.fromReusedByteArray(bytes)
+              } else {
+                Binary.fromReusedByteArray(bytes,
+                  (value.getBaseOffset - Platform.BYTE_ARRAY_OFFSET).toInt, 
value.numBytes())
+              }
+            case _ => Binary.fromReusedByteArray(value.getBytes)

Review Comment:
   Here the base isn't a `byte[]`, so `value.getBytes` always returns a fresh 
array that nothing else holds. Marking it constant saves Parquet's second copy 
on dictionary insert, statistics update, and DELTA_BYTE_ARRAY writes.
   ```suggestion
               case _ => Binary.fromConstantByteArray(value.getBytes)
   ```



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetIOSuite.scala:
##########
@@ -164,6 +173,124 @@ class ParquetIOSuite extends ParquetTest with 
SharedSparkSession {
     withSQLConf(SQLConf.PARQUET_BINARY_AS_STRING.key -> 
"true")(checkParquetFile(data))
   }
 
+  test("SPARK-60321: string writer reuses the backing array of a UTF8String 
slice") {
+    val consumer = mock(classOf[RecordConsumer])
+    val support = new ParquetWriteSupport
+    support.init(parquetStringWriterConf)
+    support.prepareForWrite(consumer)
+    val bytes = "prefix-value-suffix".getBytes(UTF_8)
+    support.write(InternalRow(UTF8String.fromBytes(bytes, 7, 5)))
+
+    val argument = ArgumentCaptor.forClass(classOf[Binary])
+    verify(consumer).addBinary(argument.capture())
+    val binary = argument.getValue
+    assert(binary.isBackingBytesReused)
+    assert(binary.toByteBuffer.array() eq bytes)
+    assert(binary.toStringUsingUTF8 == "value")
+  }
+
+  for {
+    storage <- Seq("array", "slice", "offheap")
+    dictionary <- Seq("off", "on", "fallback")
+    version <- ParquetProperties.WriterVersion.values()
+  } {
+    test(s"SPARK-60321: strings with reused $storage memory, " +
+        s"dictionary $dictionary, writer $version") {
+      val expected = reusedStringTestValues
+      val offHeap = storage == "offheap"
+      withTempPath { file =>
+        val conf = parquetStringWriterConf
+        val path = new Path(file.toURI)
+        val padding = 13
+        val shared = new Array[Byte](64 * 1024)
+        val address = if (offHeap) Platform.allocateMemory(shared.length) else 
0L
+        try {
+          // Surround each payload with sentinel bytes, so that an off-by-one 
offset or length
+          // corrupts the output instead of silently passing.
+          Arrays.fill(shared, '!'.toByte)
+          if (offHeap) {
+            Platform.setMemory(address, '!'.toByte, shared.length)
+          }
+          val writer = new InternalRowParquetWriterBuilder(path)
+            .withConf(conf)
+            .withWriterVersion(version)
+            .withCompressionCodec(SNAPPY)
+            .withDictionaryEncoding(dictionary != "off")
+            .withDictionaryPageSize(if (dictionary == "fallback") 4096 else 
1024 * 1024)
+            .withPageRowCountLimit(64)
+            .withMinRowCountForPageSizeCheck(1)
+            .withMaxRowCountForPageSizeCheck(64)
+            .withStatisticsTruncateLength(stringStatisticsTruncateLength)
+            .build()
+          try {
+            expected.foreach { text =>
+              if (text == null) {
+                writer.write(InternalRow(null))
+              } else {
+                // Each case writes into the storage it exercises and then 
overwrites just the
+                // range it wrote: retained values must survive the producer 
reusing its storage.
+                val bytes = text.getBytes(UTF_8)
+                storage match {
+                  case "array" =>
+                    writer.write(InternalRow(UTF8String.fromBytes(bytes)))
+                    Arrays.fill(bytes, '?'.toByte)
+                  case "slice" =>
+                    System.arraycopy(bytes, 0, shared, padding, bytes.length)
+                    writer.write(InternalRow(UTF8String.fromBytes(shared, 
padding, bytes.length)))
+                    Arrays.fill(shared, padding, padding + bytes.length, 
'?'.toByte)
+                  case "offheap" =>
+                    Platform.copyMemory(
+                      bytes, Platform.BYTE_ARRAY_OFFSET, null, address + 
padding, bytes.length)
+                    writer.write(
+                      InternalRow(UTF8String.fromAddress(null, address + 
padding, bytes.length)))
+                    Platform.setMemory(address + padding, '?'.toByte, 
bytes.length)
+                }
+              }
+            }
+          } finally {
+            writer.close()
+          }
+        } finally {
+          if (offHeap) {
+            Platform.freeMemory(address)
+          }
+        }
+
+        withAllParquetReaders {
+          checkAnswer(spark.read.parquet(file.toString), expected.map(Row(_)))
+        }
+        val reader = ParquetFileReader.open(HadoopInputFile.fromPath(path, 
conf))
+        try {
+          val blocks = reader.getFooter.getBlocks
+          assert(blocks.size() == 1)
+          val column = blocks.get(0).getColumns.get(0)
+          val encodings = column.getEncodingStats
+          assert(encodings.hasDictionaryEncodedPages == (dictionary != "off"))
+          assert(encodings.hasNonDictionaryEncodedPages == (dictionary != 
"on"))
+          val ordering: Ordering[Binary] =
+            
Ordering.comparatorToOrdering(UNSIGNED_LEXICOGRAPHICAL_BINARY_COMPARATOR)
+          val values = expected.filter(_ != 
null).distinct.map(Binary.fromString)
+          assert(column.getStatistics.genericGetMin == values.min(ordering))
+          assert(column.getStatistics.genericGetMax == values.max(ordering))
+          assert(column.getStatistics.getNumNulls == expected.count(_ == null))
+        } finally {
+          reader.close()
+        }
+      }
+    }
+  }
+
+  test("string slices in nested Parquet values") {

Review Comment:
   nit: this looks covered by the existing nested round-trip tests, since every 
DataFrame write already passes nested strings as 
`UnsafeArrayData`/`UnsafeMapData` slices. Suggest dropping it; if it stays, it 
needs the `SPARK-60321:` prefix.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetIOSuite.scala:
##########
@@ -2569,6 +2696,53 @@ class ParquetIOSuite extends ParquetTest with 
SharedSparkSession {
     val e = readCorruptedRleSection("id >= 0 as b", writerVersion = 
"PARQUET_2_0")(setMaxLength)
     assertInvalidLengthReportsColumn(e, "b")
   }
+
+  // Larger than the longest value in `reusedStringTestValues`, so that 
min/max statistics hold
+  // the exact values rather than truncated prefixes.
+  private val stringStatisticsTruncateLength = 64 * 1024

Review Comment:
   Parquet's default statistics truncate length is already `Integer.MAX_VALUE`, 
so this lowers the limit and the comment above doesn't hold. Suggest dropping 
this val, its comment, and `.withStatisticsTruncateLength(...)` at L223.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetIOSuite.scala:
##########
@@ -2569,6 +2696,53 @@ class ParquetIOSuite extends ParquetTest with 
SharedSparkSession {
     val e = readCorruptedRleSection("id >= 0 as b", writerVersion = 
"PARQUET_2_0")(setMaxLength)
     assertInvalidLengthReportsColumn(e, "b")
   }
+
+  // Larger than the longest value in `reusedStringTestValues`, so that 
min/max statistics hold
+  // the exact values rather than truncated prefixes.
+  private val stringStatisticsTruncateLength = 64 * 1024
+
+  /**
+   * Values covering what a Parquet string writer has to get right: nulls, 
empty and repeated
+   * values that feed the dictionary, multi-byte and surrogate-pair UTF-8, 
values long enough to
+   * force dictionary fallback, and embedded NULs. Independent of the writer 
settings and of how
+   * a test stores each value, so it is built once for the whole suite.
+   */
+  private lazy val reusedStringTestValues: Seq[String] = {

Review Comment:
   nit: these helpers (L2700-2746) are only used by the SPARK-60321 tests at 
L176-292. This file keeps helpers next to their tests (e.g. 
`createParquetWriter`, `readCorruptedRleSection`), so suggest moving them there.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetIOSuite.scala:
##########
@@ -164,6 +173,124 @@ class ParquetIOSuite extends ParquetTest with 
SharedSparkSession {
     withSQLConf(SQLConf.PARQUET_BINARY_AS_STRING.key -> 
"true")(checkParquetFile(data))
   }
 
+  test("SPARK-60321: string writer reuses the backing array of a UTF8String 
slice") {
+    val consumer = mock(classOf[RecordConsumer])
+    val support = new ParquetWriteSupport
+    support.init(parquetStringWriterConf)
+    support.prepareForWrite(consumer)
+    val bytes = "prefix-value-suffix".getBytes(UTF_8)
+    support.write(InternalRow(UTF8String.fromBytes(bytes, 7, 5)))
+
+    val argument = ArgumentCaptor.forClass(classOf[Binary])
+    verify(consumer).addBinary(argument.capture())
+    val binary = argument.getValue
+    assert(binary.isBackingBytesReused)
+    assert(binary.toByteBuffer.array() eq bytes)
+    assert(binary.toStringUsingUTF8 == "value")
+  }
+
+  for {
+    storage <- Seq("array", "slice", "offheap")
+    dictionary <- Seq("off", "on", "fallback")
+    version <- ParquetProperties.WriterVersion.values()
+  } {
+    test(s"SPARK-60321: strings with reused $storage memory, " +
+        s"dictionary $dictionary, writer $version") {
+      val expected = reusedStringTestValues
+      val offHeap = storage == "offheap"
+      withTempPath { file =>
+        val conf = parquetStringWriterConf
+        val path = new Path(file.toURI)

Review Comment:
   Writing the file directly at the `withTempPath` path makes Hadoop's checksum 
FS create a `.<name>.crc` file in the parent temp dir, which `withTempPath` 
never deletes. Suggest writing into a directory, as L156 does: `new 
Path(dir.toURI.toString, "part-r-0.parquet")`.



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