You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "amaliujia (via GitHub)" <gi...@apache.org> on 2023/03/30 18:09:35 UTC

[GitHub] [spark] amaliujia commented on a diff in pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

amaliujia commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1153614619


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.connect.client.arrow
+
+import java.io.{ByteArrayOutputStream, OutputStream}
+import java.lang.invoke.{MethodHandles, MethodType}
+import java.math.{BigDecimal => JBigDecimal, BigInteger => JBigInteger}
+import java.nio.channels.Channels
+import java.time.{Duration, Instant, LocalDate, LocalDateTime, Period}
+import java.util.{Map => JMap}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.BufferAllocator
+import org.apache.arrow.vector.{BigIntVector, BitVector, DateDayVector, DecimalVector, DurationVector, FieldVector, Float4Vector, Float8Vector, IntervalYearVector, IntVector, NullVector, SmallIntVector, TimeStampMicroTZVector, TimeStampMicroVector, TinyIntVector, VarBinaryVector, VarCharVector, VectorSchemaRoot, VectorUnloader}
+import org.apache.arrow.vector.complex.{ListVector, MapVector, StructVector}
+import org.apache.arrow.vector.ipc.{ArrowStreamWriter, WriteChannel}
+import org.apache.arrow.vector.ipc.message.{IpcOption, MessageSerializer}
+import org.apache.arrow.vector.util.Text
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.DefinedByConstructorParams
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders._
+import org.apache.spark.sql.catalyst.util.{DateTimeUtils, IntervalUtils}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.types.Decimal
+import org.apache.spark.sql.util.ArrowUtils
+
+/**
+ * Helper class for converting user objects into arrow batches.
+ */
+class ArrowSerializer[T](
+    private[this] val enc: AgnosticEncoder[T],
+    private[this] val allocator: BufferAllocator,
+    private[this] val timeZoneId: String) {
+  private val (root, serializer) = ArrowSerializer.serializerFor(enc, allocator, timeZoneId)
+  private val vectors = root.getFieldVectors.asScala
+  private val unloader = new VectorUnloader(root)
+  private val schemaBytes = {
+    // Only serialize the schema once.
+    val bytes = new ByteArrayOutputStream()
+    MessageSerializer.serialize(newChannel(bytes), root.getSchema)
+    bytes.toByteArray
+  }
+  private var i: Int = 0
+
+  private def newChannel(output: OutputStream): WriteChannel = {
+    new WriteChannel(Channels.newChannel(output))
+  }
+
+  /**
+   * The size of the current batch.
+   *
+   * The size computed consist of the size of the schema and the size of the arrow buffers. The
+   * actual batch will be larger than that because of alignment, written IPC tokens, and the
+   * written record batch metadata. The size of the record batch metadata is proportional to the
+   * complexity of the schema.
+   */
+  def sizeInBytes: Long = {
+    // We need to set the row count for getBufferSize to return the actual value.
+    root.setRowCount(i)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(i, record)
+    i += 1
+  }
+
+  /**
+   * Write the schema and the current batch in Arrow IPC stream format to the [[OutputStream]].
+   */
+  def writeIpcStream(output: OutputStream): Unit = {
+    val channel = newChannel(output)
+    root.setRowCount(i)
+    val batch = unloader.getRecordBatch
+    try {
+      channel.write(schemaBytes)
+      MessageSerializer.serialize(channel, batch)
+      ArrowStreamWriter.writeEndOfStream(channel, IpcOption.DEFAULT)
+    } finally {
+      batch.close()

Review Comment:
   You should also close the `channel`?



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.connect.client.arrow
+
+import java.io.{ByteArrayOutputStream, OutputStream}
+import java.lang.invoke.{MethodHandles, MethodType}
+import java.math.{BigDecimal => JBigDecimal, BigInteger => JBigInteger}
+import java.nio.channels.Channels
+import java.time.{Duration, Instant, LocalDate, LocalDateTime, Period}
+import java.util.{Map => JMap}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.BufferAllocator
+import org.apache.arrow.vector.{BigIntVector, BitVector, DateDayVector, DecimalVector, DurationVector, FieldVector, Float4Vector, Float8Vector, IntervalYearVector, IntVector, NullVector, SmallIntVector, TimeStampMicroTZVector, TimeStampMicroVector, TinyIntVector, VarBinaryVector, VarCharVector, VectorSchemaRoot, VectorUnloader}
+import org.apache.arrow.vector.complex.{ListVector, MapVector, StructVector}
+import org.apache.arrow.vector.ipc.{ArrowStreamWriter, WriteChannel}
+import org.apache.arrow.vector.ipc.message.{IpcOption, MessageSerializer}
+import org.apache.arrow.vector.util.Text
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.DefinedByConstructorParams
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders._
+import org.apache.spark.sql.catalyst.util.{DateTimeUtils, IntervalUtils}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.types.Decimal
+import org.apache.spark.sql.util.ArrowUtils
+
+/**
+ * Helper class for converting user objects into arrow batches.
+ */
+class ArrowSerializer[T](
+    private[this] val enc: AgnosticEncoder[T],
+    private[this] val allocator: BufferAllocator,
+    private[this] val timeZoneId: String) {
+  private val (root, serializer) = ArrowSerializer.serializerFor(enc, allocator, timeZoneId)
+  private val vectors = root.getFieldVectors.asScala
+  private val unloader = new VectorUnloader(root)
+  private val schemaBytes = {
+    // Only serialize the schema once.
+    val bytes = new ByteArrayOutputStream()
+    MessageSerializer.serialize(newChannel(bytes), root.getSchema)
+    bytes.toByteArray
+  }
+  private var i: Int = 0
+
+  private def newChannel(output: OutputStream): WriteChannel = {
+    new WriteChannel(Channels.newChannel(output))
+  }
+
+  /**
+   * The size of the current batch.
+   *
+   * The size computed consist of the size of the schema and the size of the arrow buffers. The
+   * actual batch will be larger than that because of alignment, written IPC tokens, and the
+   * written record batch metadata. The size of the record batch metadata is proportional to the
+   * complexity of the schema.
+   */
+  def sizeInBytes: Long = {
+    // We need to set the row count for getBufferSize to return the actual value.
+    root.setRowCount(i)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(i, record)
+    i += 1
+  }
+
+  /**
+   * Write the schema and the current batch in Arrow IPC stream format to the [[OutputStream]].
+   */
+  def writeIpcStream(output: OutputStream): Unit = {
+    val channel = newChannel(output)
+    root.setRowCount(i)
+    val batch = unloader.getRecordBatch
+    try {
+      channel.write(schemaBytes)
+      MessageSerializer.serialize(channel, batch)
+      ArrowStreamWriter.writeEndOfStream(channel, IpcOption.DEFAULT)
+    } finally {
+      batch.close()
+    }
+  }
+
+  /**
+   * Reset the serializer.
+   */
+  def reset(): Unit = {
+    i = 0
+    vectors.foreach(_.reset())
+  }
+
+  /**
+   * Close the serializer.
+   */
+  def close(): Unit = root.close()
+}
+
+object ArrowSerializer {
+  import ArrowEncoderUtils._
+
+  /**
+   * Create an [[Iterator]] that converts the input [[Iterator]] of type `T` into an [[Iterator]]
+   * of Arrow IPC Streams.
+   */
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      maxRecordsPerBatch: Int,
+      maxBatchSize: Long,
+      timeZoneId: String,
+      batchSizeCheckInterval: Int = 128): CloseableIterator[Array[Byte]] = {
+    assert(maxRecordsPerBatch > 0)
+    assert(maxBatchSize > 0)
+    assert(batchSizeCheckInterval > 0)
+    new CloseableIterator[Array[Byte]] {
+      private val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+      private val bytes = new ByteArrayOutputStream
+      private var hasWrittenFirstBatch = false
+
+      /**
+       * Periodical check to make sure we don't go over the size threshold by too much.
+       */
+      private def sizeOk(i: Int): Boolean = {
+        if (i > 0 && i % batchSizeCheckInterval == 0) {
+          return serializer.sizeInBytes < maxBatchSize
+        }
+        true
+      }
+
+      override def hasNext: Boolean = input.hasNext || !hasWrittenFirstBatch
+
+      override def next(): Array[Byte] = {
+        if (!hasNext) {
+          throw new NoSuchElementException()

Review Comment:
   Should it throw or just return?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org