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

[GitHub] [spark] hvanhovell opened a new pull request, #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

hvanhovell opened a new pull request, #40611:
URL: https://github.com/apache/spark/pull/40611

   ### What changes were proposed in this pull request?
   This PR adds direct serialization from user domain objects to arrow batches. This removes the need to go through catalyst.
   
   ### Why are the changes needed?
   We want to minimalize the number of dependencies in connect. Removing catalyst and core is part of this effort.
   
   ### Does this PR introduce _any_ user-facing change?
   No
   
   ### How was this patch tested?
   I added the `ArrowEncoderSuite` to test this.


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


[GitHub] [spark] hvanhovell commented on pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on PR #40611:
URL: https://github.com/apache/spark/pull/40611#issuecomment-1633231644

   Merging.


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


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

Posted by "amaliujia (via GitHub)" <gi...@apache.org>.
amaliujia commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1157907417


##########
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 = {

Review Comment:
   nit: maybe lazy?



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

Review Comment:
   Do we need a way to prevent overflow?



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

Review Comment:
   nit: maybe `recordCount` is better than `i`?



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261147255


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,532 @@
+/*
+ * 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, Objects}
+
+import scala.collection.JavaConverters._
+
+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 rowCount: 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(rowCount)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(rowCount, record)
+    rowCount += 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(rowCount)
+    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 = {
+    rowCount = 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] = {

Review Comment:
   `hasNext` will return `false` and `next` will throw a `NoSuchElementException`.



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


[GitHub] [spark] hvanhovell closed pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell closed pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization
URL: https://github.com/apache/spark/pull/40611


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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261665885


##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,894 @@
+/*
+ * 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.math.BigInteger
+import java.util
+import java.util.{Collections, Objects}
+
+import scala.beans.BeanProperty
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, JavaTypeInference, ScalaReflection}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.arrow.FooEnum.FooEnum
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, IntegerType, Metadata, SQLUserDefinedType, StructType, UserDefinedType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val itr = result.iterator
+      override def close(): Unit = itr.close()
+      override def hasNext: Boolean = itr.hasNext
+      override def next(): E = itr.next()
+    }
+  }
+
+  private def roundTripAndCheck[T](
+      encoder: AgnosticEncoder[T],
+      toInputIterator: () => Iterator[Any],
+      toOutputIterator: () => Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): Unit = {
+    val iterator = roundTrip(
+      encoder,
+      toInputIterator().asInstanceOf[Iterator[T]], // Erasure hack :)
+      maxRecordsPerBatch,
+      maxBatchSize,
+      batchSizeCheckInterval,
+      inspectBatch)
+    try {
+      compareIterators(toOutputIterator(), iterator)
+    } finally {
+      iterator.close()
+    }
+  }
+
+  private def roundTripAndCheckIdentical[T](
+      encoder: AgnosticEncoder[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null)(toIterator: () => Iterator[T]): Unit = {
+    roundTripAndCheck(
+      encoder,
+      toIterator,
+      toIterator,
+      maxRecordsPerBatch,
+      maxBatchSize,
+      batchSizeCheckInterval,
+      inspectBatch)
+  }
+
+  private def serializeToArrow[T](
+      input: Iterator[T],
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator): CloseableIterator[Array[Byte]] = {
+    ArrowSerializer.serialize(
+      input,
+      encoder,
+      allocator,
+      maxRecordsPerBatch = 1024,
+      maxBatchSize = 8 * 1024,
+      timeZoneId = "UTC")
+  }
+
+  private def compareIterators[T](expected: Iterator[T], actual: Iterator[T]): Unit = {
+    expected.zipAll(actual, null, null).foreach { case (expected, actual) =>
+      assert(expected != null)
+      assert(actual != null)
+      assert(actual == expected)
+    }
+  }
+
+  private class CountingBatchInspector extends (Array[Byte] => Unit) {
+    private var _numBatches: Int = 0
+    private var _sizeInBytes: Long = 0
+    def numBatches: Int = _numBatches
+    def sizeInBytes: Long = _sizeInBytes
+    def sizeInBytesPerBatch: Long = sizeInBytes / numBatches
+    override def apply(batch: Array[Byte]): Unit = {
+      _numBatches += 1
+      _sizeInBytes += batch.length
+    }
+  }
+
+  private case class MaybeNull(interval: Int) {
+    assert(interval > 1)
+    private var invocations = 0
+    def apply[T](value: T): T = {
+      val result = if (invocations % interval == 0) {
+        null.asInstanceOf[T]
+      } else {
+        value
+      }
+      invocations += 1
+      result
+    }
+  }
+
+  private def javaBigDecimal(i: Int): java.math.BigDecimal = {
+    javaBigDecimal(i, DecimalType.DEFAULT_SCALE)
+  }
+
+  private def javaBigDecimal(i: Int, scale: Int): java.math.BigDecimal = {
+    java.math.BigDecimal.valueOf(i).setScale(scale)
+  }
+
+  private val singleIntEncoder = RowEncoder(
+    EncoderField("i", BoxedIntEncoder, nullable = false, Metadata.empty) :: Nil)
+
+  /* ******************************************************************** *
+   * Iterator behavior tests.
+   * ******************************************************************** */
+
+  test("empty") {
+    val inspector = new CountingBatchInspector
+    roundTripAndCheckIdentical(singleIntEncoder, inspectBatch = inspector) { () =>
+      Iterator.empty
+    }
+    // We always write a batch with a schema.
+    assert(inspector.numBatches == 1)
+    assert(inspector.sizeInBytes > 0)
+  }
+
+  test("single batch") {
+    val inspector = new CountingBatchInspector
+    roundTripAndCheckIdentical(singleIntEncoder, inspectBatch = inspector) { () =>
+      Iterator.tabulate(10)(i => Row(i))
+    }
+    assert(inspector.numBatches == 1)
+  }
+
+  test("multiple batches - split by record count") {
+    val inspector = new CountingBatchInspector
+    roundTripAndCheckIdentical(
+      singleIntEncoder,
+      inspectBatch = inspector,
+      maxBatchSize = 32 * 1024) { () =>
+      Iterator.tabulate(1024 * 1024)(i => Row(i))
+    }
+    assert(inspector.numBatches == 256)
+  }
+
+  test("multiple batches - split by size") {
+    val dataGen = { () =>
+      Iterator.tabulate(4 * 1024)(i => Row(i))
+    }
+
+    // Normal interval
+    val inspector1 = new CountingBatchInspector
+    roundTripAndCheckIdentical(singleIntEncoder, maxBatchSize = 1024, inspectBatch = inspector1)(
+      dataGen)
+    assert(inspector1.numBatches == 16)
+    assert(inspector1.sizeInBytesPerBatch >= 1024)
+    assert(inspector1.sizeInBytesPerBatch <= 1024 + 128 * 5)
+
+    // Lowest possible interval
+    val inspector2 = new CountingBatchInspector
+    roundTripAndCheckIdentical(
+      singleIntEncoder,
+      maxBatchSize = 1024,
+      batchSizeCheckInterval = 1,
+      inspectBatch = inspector2)(dataGen)
+    assert(inspector2.numBatches == 20)
+    assert(inspector2.sizeInBytesPerBatch >= 1024)
+    assert(inspector2.sizeInBytesPerBatch <= 1024 + 128 * 2)
+    assert(inspector2.sizeInBytesPerBatch < inspector1.sizeInBytesPerBatch)
+  }
+
+  test("use after close") {
+    val iterator = serializeToArrow(Iterator.single(Row(0)), singleIntEncoder, allocator)
+    assert(iterator.hasNext)
+    iterator.close()
+    assert(!iterator.hasNext)
+    intercept[NoSuchElementException](iterator.next())
+  }
+
+  /* ******************************************************************** *
+   * Encoder specification tests
+   * ******************************************************************** */
+  // Lenient mode
+  // Errors
+
+  test("primitive fields") {
+    val encoder = ScalaReflection.encoderFor[PrimitiveData]
+    roundTripAndCheckIdentical(encoder) { () =>
+      Iterator.tabulate(10) { i =>
+        PrimitiveData(i, i, i.toDouble, i.toFloat, i.toShort, i.toByte, i < 4)
+      }
+    }
+  }
+
+  test("boxed primitive fields") {
+    val encoder = ScalaReflection.encoderFor[BoxedData]
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(3)
+      Iterator.tabulate(100) { i =>
+        BoxedData(
+          intField = maybeNull(i),
+          longField = maybeNull(i),
+          doubleField = maybeNull(i.toDouble),
+          floatField = maybeNull(i.toFloat),
+          shortField = maybeNull(i.toShort),
+          byteField = maybeNull(i.toByte),
+          booleanField = maybeNull(i > 4))
+      }
+    }
+  }
+
+  test("special floating point numbers") {
+    val floatIterator = roundTrip(
+      PrimitiveFloatEncoder,
+      Iterator[Float](Float.NaN, Float.NegativeInfinity, Float.PositiveInfinity))
+    assert(java.lang.Float.isNaN(floatIterator.next()))
+    assert(floatIterator.next() == Float.NegativeInfinity)
+    assert(floatIterator.next() == Float.PositiveInfinity)
+    assert(!floatIterator.hasNext)
+    floatIterator.close()
+
+    val doubleIterator = roundTrip(
+      PrimitiveDoubleEncoder,
+      Iterator[Double](Double.NaN, Double.NegativeInfinity, Double.PositiveInfinity))
+    assert(java.lang.Double.isNaN(doubleIterator.next()))
+    assert(doubleIterator.next() == Double.NegativeInfinity)
+    assert(doubleIterator.next() == Double.PositiveInfinity)
+    assert(!doubleIterator.hasNext)
+    doubleIterator.close()
+  }
+
+  test("nullable fields") {
+    val encoder = ScalaReflection.encoderFor[NullableData]
+    val instant = java.time.Instant.now()
+    val now = java.time.LocalDateTime.now()
+    val today = java.time.LocalDate.now()
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(3)
+      Iterator.tabulate(100) { i =>
+        NullableData(
+          string = maybeNull(if (i % 7 == 0) "" else "s" + i),
+          month = maybeNull(java.time.Month.of(1 + (i % 12))),
+          foo = maybeNull(FooEnum(i % FooEnum.maxId)),
+          decimal = maybeNull(Decimal(i)),
+          scalaBigDecimal = maybeNull(BigDecimal(javaBigDecimal(i + 1))),
+          javaBigDecimal = maybeNull(javaBigDecimal(i + 2)),
+          scalaBigInt = maybeNull(BigInt(i + 3)),
+          javaBigInteger = maybeNull(java.math.BigInteger.valueOf(i + 4)),
+          duration = maybeNull(java.time.Duration.ofDays(i)),
+          period = maybeNull(java.time.Period.ofMonths(i)),
+          date = maybeNull(java.sql.Date.valueOf(today.plusDays(i))),
+          localDate = maybeNull(today.minusDays(i)),
+          timestamp = maybeNull(java.sql.Timestamp.valueOf(now.plusSeconds(i))),
+          instant = maybeNull(instant.plusSeconds(i * 100)),
+          localDateTime = maybeNull(now.minusHours(i)))
+      }
+    }
+  }
+
+  test("binary field") {
+    val encoder = ScalaReflection.encoderFor[BinaryData]
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(3)
+      Iterator.tabulate(100) { i =>
+        BinaryData(maybeNull(Array.tabulate(i % 100)(_.toByte)))
+      }
+    }
+  }
+
+  // Row and Scala class are already covered in other tests
+  test("javabean") {
+    val encoder = JavaTypeInference.encoderFor[DummyBean](classOf[DummyBean])
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(6)
+      Iterator.tabulate(100) { i =>
+        val bean = new DummyBean()
+        bean.setBigInteger(maybeNull(java.math.BigInteger.valueOf(i)))
+        bean
+      }
+    }
+  }
+
+  test("defined by constructor parameters") {
+    val encoder = ScalaReflection.encoderFor[NonProduct]
+    roundTripAndCheckIdentical(encoder) { () =>
+      Iterator.tabulate(100) { i =>
+        new NonProduct("k" + i, i.toDouble)
+      }
+    }
+  }
+
+  test("option") {
+    val encoder = ScalaReflection.encoderFor[Option[String]]
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(6)
+      Iterator.tabulate(100) { i =>
+        Option(maybeNull("v" + i))
+      }
+    }
+  }
+
+  test("arrays") {
+    val encoder = ScalaReflection.encoderFor[ArrayData]
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(5)
+      Iterator.tabulate(100) { i =>
+        ArrayData(
+          maybeNull(Array.tabulate[Double](i % 9)(_.toDouble)),
+          maybeNull(Array.tabulate[String](i % 21)(i => maybeNull("s" + i))),
+          maybeNull(Array.tabulate[Array[Int]](i % 13) { i =>
+            maybeNull {
+              Array.fill(i % 29)(i)
+            }
+          }))
+      }
+    }
+  }
+
+  test("scala iterables") {
+    val encoder = ScalaReflection.encoderFor[ListData]
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(5)
+      Iterator.tabulate(100) { i =>
+        ListData(
+          maybeNull(Seq.tabulate[String](i % 9)(i => maybeNull("s" + i))),
+          maybeNull(Seq.tabulate[Int](i % 10)(identity)),
+          maybeNull(Set(i.toLong, i.toLong - 1, i.toLong - 33)),
+          maybeNull(mutable.Queue.tabulate(5 + i % 6) { i =>
+            Option(maybeNull(BigInt(i)))
+          }))
+      }
+    }
+  }
+
+  test("java lists") {
+    def genJavaData[E](n: Int, collection: util.Collection[E])(f: Int => E): Unit = {
+      Iterator.tabulate(n)(f).foreach(collection.add)
+    }
+    val encoder = JavaTypeInference.encoderFor(classOf[JavaListData])
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(7)
+      Iterator.tabulate(1) { i =>
+        val bean = new JavaListData
+        bean.setListOfDecimal(maybeNull {
+          val list = new util.ArrayList[java.math.BigDecimal]
+          genJavaData(i % 7, list) { i => maybeNull(java.math.BigDecimal.valueOf(i * 33)) }
+          list
+        })
+        bean.setListOfBigInt(maybeNull {
+          val list = new util.LinkedList[java.math.BigInteger]
+          genJavaData(10, list) { i => maybeNull(java.math.BigInteger.valueOf(i * 50)) }
+          list
+        })
+        bean.setListOfStrings(maybeNull {
+          val list = new util.ArrayList[String]
+          genJavaData((i + 5) % 50, list) { i => maybeNull("v" + (i * 2)) }
+          list
+        })
+        bean.setListOfBytes(maybeNull(Collections.singletonList(i.toByte)))
+        bean
+      }
+    }
+  }
+
+  test("wrapped array") {
+    val encoder = ScalaReflection.encoderFor[mutable.WrappedArray[Int]]
+    val input = mutable.WrappedArray.make[Int](Array(1, 98, 7, 6))
+    val iterator = roundTrip(encoder, Iterator.single(input))
+    val Seq(result) = iterator.toSeq
+    assert(result == input)
+    assert(result.array.getClass == classOf[Array[Int]])
+    iterator.close()
+  }
+
+  test("wrapped array - empty") {
+    val schema = new StructType().add("names", "array<string>")
+    val encoder = toRowEncoder(schema)
+    val iterator = roundTrip(encoder, Iterator.single(Row(Seq())))
+    val Seq(Row(raw)) = iterator.toSeq
+    val seq = raw.asInstanceOf[mutable.WrappedArray[String]]
+    assert(seq.isEmpty)
+    assert(seq.array.getClass == classOf[Array[String]])
+    iterator.close()
+  }
+
+  test("maps") {
+    val encoder = ScalaReflection.encoderFor[MapData]
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(5)
+      Iterator.tabulate(100) { i =>
+        MapData(
+          maybeNull(
+            Iterator
+              .tabulate(i % 9) { i =>
+                i -> maybeNull("s" + i)
+              }
+              .toMap),
+          maybeNull(
+            Iterator
+              .tabulate(i % 10) { i =>
+                ("s" + 1) -> maybeNull(Array.tabulate[Long]((i + 5) % 20)(_.toLong))
+              }
+              .toMap))
+      }
+    }
+  }
+
+  test("java maps") {
+    val encoder = JavaTypeInference.encoderFor(classOf[JavaMapData])
+    roundTripAndCheckIdentical(encoder) { () =>
+      val maybeNull = MaybeNull(11)
+      Iterator.tabulate(100) { i =>
+        val bean = new JavaMapData
+        bean.setDummyToDoubleListMap(maybeNull {
+          val map = new util.HashMap[DummyBean, java.util.List[java.lang.Double]]
+          (0 until (i % 5)).foreach { j =>
+            val dummy = new DummyBean
+            dummy.setBigInteger(maybeNull(java.math.BigInteger.valueOf(i * j)))
+            val values = Array.tabulate(i % 40) { j =>
+              Double.box(j.toDouble)
+            }
+            map.put(dummy, maybeNull(util.Arrays.asList(values: _*)))
+          }
+          map
+        })
+        bean
+      }
+    }
+  }
+
+  test("map with null key") {
+    val encoder = ScalaReflection.encoderFor[Map[String, String]]
+    withAllocator { allocator =>
+      val iterator = ArrowSerializer.serialize(
+        Iterator(Map((null.asInstanceOf[String], "kaboom?"))),
+        encoder,
+        allocator,
+        maxRecordsPerBatch = 128,
+        maxBatchSize = 1024,
+        timeZoneId = "UTC")
+      intercept[NullPointerException] {
+        iterator.next()
+      }
+      iterator.close()
+    }
+  }
+
+  // TODO follow-up with more null tests here:
+  // - Null primitive
+  // - Non-nullable map value
+  // - Non-nullable structfield
+  // - Non-nullable array element.
+
+  test("lenient field serialization - date/localdate") {
+    val base = java.time.LocalDate.now()
+    val localDates = () => Iterator.tabulate(10)(i => base.plusDays(i * i * 60))
+    val dates = () => localDates().map(java.sql.Date.valueOf)
+    val combo = () => localDates() ++ dates()
+    roundTripAndCheck(DateEncoder(true), dates, dates)
+    roundTripAndCheck(DateEncoder(true), localDates, dates)
+    roundTripAndCheck(DateEncoder(true), combo, () => dates() ++ dates())
+    roundTripAndCheck(LocalDateEncoder(true), dates, localDates)
+    roundTripAndCheck(LocalDateEncoder(true), localDates, localDates)
+    roundTripAndCheck(LocalDateEncoder(true), combo, () => localDates() ++ localDates())
+  }
+
+  test("lenient field serialization - timestamp/instant") {
+    val base = java.time.Instant.now()
+    val instants = () => Iterator.tabulate(10)(i => base.plusSeconds(i * i * 60))
+    val timestamps = () => instants().map(java.sql.Timestamp.from)
+    val combo = () => instants() ++ timestamps()
+    roundTripAndCheck(InstantEncoder(true), instants, instants)
+    roundTripAndCheck(InstantEncoder(true), timestamps, instants)
+    roundTripAndCheck(InstantEncoder(true), combo, () => instants() ++ instants())
+    roundTripAndCheck(TimestampEncoder(true), instants, timestamps)
+    roundTripAndCheck(TimestampEncoder(true), timestamps, timestamps)
+    roundTripAndCheck(TimestampEncoder(true), combo, () => timestamps() ++ timestamps())
+  }
+
+  test("lenient field serialization - decimal") {
+    val base = javaBigDecimal(137, DecimalType.DEFAULT_SCALE)
+    val bigDecimals = () =>
+      Iterator.tabulate(100) { i =>
+        base.multiply(javaBigDecimal(i)).setScale(DecimalType.DEFAULT_SCALE)
+      }
+    val bigInts = () => bigDecimals().map(_.toBigInteger)
+    val scalaBigDecimals = () => bigDecimals().map(BigDecimal.apply)
+    val scalaBigInts = () => bigDecimals().map(v => BigInt(v.toBigInteger))
+    val sparkDecimals = () => bigDecimals().map(Decimal.apply)
+    val encoder = JavaDecimalEncoder(DecimalType.SYSTEM_DEFAULT, lenientSerialization = true)
+    roundTripAndCheck(encoder, bigDecimals, bigDecimals)
+    roundTripAndCheck(encoder, bigInts, bigDecimals)
+    roundTripAndCheck(encoder, scalaBigDecimals, bigDecimals)
+    roundTripAndCheck(encoder, scalaBigInts, bigDecimals)
+    roundTripAndCheck(encoder, sparkDecimals, bigDecimals)
+    roundTripAndCheck(
+      encoder,
+      () => bigDecimals() ++ bigInts() ++ scalaBigDecimals() ++ scalaBigInts() ++ sparkDecimals(),
+      () => Iterator.fill(5)(bigDecimals()).flatten)
+  }
+
+  test("lenient field serialization - iterables") {
+    val encoder = IterableEncoder(
+      classTag[Seq[Int]],
+      BoxedIntEncoder,
+      containsNull = true,
+      lenientSerialization = true)
+    val elements = Seq(Array(1, 7, 8), Array.emptyIntArray, Array(88))
+    val primitiveArrays = () => elements.iterator
+    val genericArrays = () => elements.iterator.map(v => v.map(Int.box))
+    val lists = () => elements.iterator.map(v => java.util.Arrays.asList(v.map(Int.box): _*))
+    val seqs = () => elements.iterator.map(_.toSeq)
+    roundTripAndCheck(encoder, seqs, seqs)
+    roundTripAndCheck(encoder, primitiveArrays, seqs)
+    roundTripAndCheck(encoder, genericArrays, seqs)
+    roundTripAndCheck(encoder, lists, seqs)
+    roundTripAndCheck(
+      encoder,
+      () => lists() ++ seqs() ++ genericArrays() ++ primitiveArrays(),
+      () => Iterator.fill(4)(seqs()).flatten)
+  }
+
+  private val wideSchemaEncoder = toRowEncoder(
+    new StructType()
+      .add("a", "int")
+      .add("b", "string")
+      .add(
+        "c",
+        new StructType()
+          .add("ca", "array<int>")
+          .add("cb", "binary")
+          .add("cc", "float"))
+      .add(
+        "d",
+        ArrayType(
+          new StructType()
+            .add("da", "decimal(20, 10)")
+            .add("db", "string")
+            .add("dc", "boolean"))))
+
+  private val narrowSchemaEncoder = toRowEncoder(
+    new StructType()
+      .add("b", "string")
+      .add(
+        "d",
+        ArrayType(
+          new StructType()
+            .add("da", "decimal(20, 10)")
+            .add("dc", "boolean")))
+      .add(
+        "C",
+        new StructType()
+          .add("Ca", "array<int>")
+          .add("Cb", "binary")))
+
+  /* ******************************************************************** *
+   * Arrow serialization/deserialization specific errors
+   * ******************************************************************** */
+  test("unsupported encoders") {
+    // CalendarIntervalEncoder
+    val data = null.asInstanceOf[AnyRef]
+    intercept[SparkUnsupportedOperationException](
+      ArrowSerializer.serializerFor(CalendarIntervalEncoder, data))
+
+    // UDT
+    val udtEncoder = UDTEncoder(new UDTNotSupported, classOf[UDTNotSupported])
+    intercept[SparkUnsupportedOperationException](ArrowSerializer.serializerFor(udtEncoder, data))
+  }
+
+  test("unsupported encoder/vector combinations") {
+    // Also add a test for the serializer...
+    withAllocator { allocator =>
+      intercept[RuntimeException] {
+        ArrowSerializer.serializerFor(StringEncoder, new VarBinaryVector("bytes", allocator))
+      }
+    }
+  }
+}
+
+// TODO fix actual Null fields, e.g.: nullable: Null
+case class NullableData(
+    string: String,
+    month: java.time.Month,
+    foo: FooEnum,
+    decimal: Decimal,
+    scalaBigDecimal: BigDecimal,
+    javaBigDecimal: java.math.BigDecimal,
+    scalaBigInt: BigInt,
+    javaBigInteger: java.math.BigInteger,
+    duration: java.time.Duration,
+    period: java.time.Period,
+    date: java.sql.Date,
+    localDate: java.time.LocalDate,
+    timestamp: java.sql.Timestamp,
+    instant: java.time.Instant,
+    localDateTime: java.time.LocalDateTime)
+
+case class BinaryData(binary: Array[Byte]) {
+  def canEqual(other: Any): Boolean = other.isInstanceOf[BinaryData]
+
+  override def equals(other: Any): Boolean = other match {
+    case that: BinaryData if that.canEqual(this) =>
+      java.util.Arrays.equals(binary, that.binary)
+    case _ => false
+  }
+
+  override def hashCode(): Int = java.util.Arrays.hashCode(binary)
+}
+
+class NonProduct(val name: String, val value: Double) extends DefinedByConstructorParams {
+
+  def canEqual(other: Any): Boolean = other.isInstanceOf[NonProduct]
+
+  override def equals(other: Any): Boolean = other match {
+    case that: NonProduct =>
+      (that canEqual this) &&
+      name == that.name &&
+      value == that.value
+    case _ => false
+  }
+
+  override def hashCode(): Int = {
+    val state = Seq(name, value)
+    state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
+  }
+}
+
+case class ArrayData(doubles: Array[Double], strings: Array[String], nested: Array[Array[Int]]) {
+  def canEqual(other: Any): Boolean = other.isInstanceOf[ArrayData]
+
+  override def equals(other: Any): Boolean = other match {
+    case that: ArrayData if that.canEqual(this) =>
+      Objects.deepEquals(that.doubles, doubles) &&
+      Objects.deepEquals(that.strings, strings) &&
+      Objects.deepEquals(that.nested, nested)
+    case _ => false
+  }
+
+  override def hashCode(): Int = {
+    val state = Seq(doubles, strings, nested)
+    state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
+  }
+}
+
+case class ListData(
+    seqOfStrings: Seq[String],
+    seqOfInts: Seq[Int],
+    setOfLongs: Set[Long],
+    queueOfBigIntOptions: mutable.Queue[Option[BigInt]])
+
+class JavaListData {
+  @scala.beans.BeanProperty
+  var listOfDecimal: java.util.ArrayList[java.math.BigDecimal] = _
+  @scala.beans.BeanProperty
+  var listOfBigInt: java.util.LinkedList[java.math.BigInteger] = _
+  @scala.beans.BeanProperty
+  var listOfStrings: java.util.AbstractList[String] = _
+  @scala.beans.BeanProperty
+  var listOfBytes: java.util.List[java.lang.Byte] = _
+
+  def canEqual(other: Any): Boolean = other.isInstanceOf[JavaListData]
+
+  override def equals(other: Any): Boolean = other match {
+    case that: JavaListData if that canEqual this =>
+      Objects.equals(listOfDecimal, that.listOfDecimal) &&
+      Objects.equals(listOfBigInt, that.listOfBigInt) &&
+      Objects.equals(listOfStrings, that.listOfStrings) &&
+      Objects.equals(listOfBytes, that.listOfBytes)
+    case _ => false
+  }
+
+  override def hashCode(): Int = {
+    val state = Seq(listOfDecimal, listOfBigInt, listOfStrings, listOfBytes)
+    state.map(Objects.hashCode).foldLeft(0)((a, b) => 31 * a + b)
+  }
+
+  override def toString: String = {
+    s"JavaListData(listOfDecimal=$listOfDecimal, " +
+      s"listOfBigInt=$listOfBigInt, " +
+      s"listOfStrings=$listOfStrings, " +
+      s"listOfBytes=$listOfBytes)"
+  }
+}
+
+case class MapData(intStringMap: Map[Int, String], metricMap: Map[String, Array[Long]]) {
+  def canEqual(other: Any): Boolean = other.isInstanceOf[MapData]
+
+  private def sameMetricMap(other: Map[String, Array[Long]]): Boolean = {
+    if (metricMap == null && other == null) {
+      true
+    } else if (metricMap == null || other == null || metricMap.keySet != other.keySet) {
+      false
+    } else {
+      metricMap.forall { case (key, values) =>
+        java.util.Arrays.equals(values, other(key))
+      }
+    }
+  }
+
+  override def equals(other: Any): Boolean = other match {
+    case that: MapData if that canEqual this =>
+      Objects.deepEquals(intStringMap, that.intStringMap) &&
+      sameMetricMap(that.metricMap)
+    case _ => false
+  }
+
+  override def hashCode(): Int = {
+    java.util.Arrays.deepHashCode(Array(intStringMap, metricMap))
+  }
+}
+
+class JavaMapData {
+  @scala.beans.BeanProperty
+  var dummyToDoubleListMap: java.util.Map[DummyBean, java.util.List[java.lang.Double]] = _
+
+  def canEqual(other: Any): Boolean = other.isInstanceOf[JavaMapData]
+
+  override def equals(other: Any): Boolean = other match {
+    case that: JavaMapData if that canEqual this =>
+      dummyToDoubleListMap == that.dummyToDoubleListMap
+    case _ => false
+  }
+
+  override def hashCode(): Int = Objects.hashCode(dummyToDoubleListMap)
+}
+
+class DummyBean {

Review Comment:
   Temporarily borrowed a couple of classes to mitigate a build issue.



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261121505


##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * 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.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val itr = result.iterator
+      override def close(): Unit = itr.close()
+      override def hasNext: Boolean = itr.hasNext
+      override def next(): E = itr.next()
+    }
+  }
+
+  private def roundTripAndCheck[T](
+      encoder: AgnosticEncoder[T],
+      toInputIterator: () => Iterator[Any],
+      toOutputIterator: () => Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): Unit = {
+    val iterator = roundTrip(
+      encoder,
+      toInputIterator().asInstanceOf[Iterator[T]], // Erasure hack :)
+      maxRecordsPerBatch,
+      maxBatchSize,
+      batchSizeCheckInterval,
+      inspectBatch)
+    try {
+      compareIterators(toOutputIterator(), iterator)
+    } finally {
+      iterator.close()
+    }
+  }
+
+  private def roundTripAndCheckIdentical[T](
+      encoder: AgnosticEncoder[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null)(toIterator: () => Iterator[T]): Unit = {

Review Comment:
   It is used in used in a couple of `Iterator behavior tests.`...



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1260675323


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

Review Comment:
   Arrow already enforces this.



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


[GitHub] [spark] hvanhovell commented on pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on PR #40611:
URL: https://github.com/apache/spark/pull/40611#issuecomment-1631996709

   @LuciferYang PTAL


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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261145969


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala:
##########
@@ -126,9 +127,9 @@ class SparkSession private[sql] (
     newDataset(encoder) { builder =>
       if (data.nonEmpty) {
         val timeZoneId = conf.get("spark.sql.session.timeZone")
-        val (arrowData, arrowDataSize) =
-          ConvertToArrow(encoder, data, timeZoneId, errorOnDuplicatedFieldNames = true, allocator)

Review Comment:
   I have removed it.



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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 scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]

Review Comment:
   Done.



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


[GitHub] [spark] LuciferYang commented on pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on PR #40611:
URL: https://github.com/apache/spark/pull/40611#issuecomment-1632295248

   @hvanhovell checked with Scala 2.13
   
   ```
   dev/change-scala-version.sh 2.13
   build/sbt clean "connect-client-jvm/testOnly org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite" -Pscala-2.13
   ```
   
   There are 2 TESTS FAILED in my local:
   
   ```
   [info] - javabean *** FAILED *** (31 milliseconds)
   [info]   org.apache.spark.sql.catalyst.DummyBean@67edd08e did not equal org.apache.spark.sql.catalyst.DummyBean@4bf9bb36 (ArrowEncoderSuite.scala:192)
   [info]   org.scalatest.exceptions.TestFailedException:
   [info]   at org.scalatest.Assertions.newAssertionFailedException(Assertions.scala:472)
   [info]   at org.scalatest.Assertions.newAssertionFailedException$(Assertions.scala:471)
   [info]   at org.scalatest.Assertions$.newAssertionFailedException(Assertions.scala:1231)
   [info]   at org.scalatest.Assertions$AssertionsHelper.macroAssert(Assertions.scala:1295)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.$anonfun$compareIterators$1(ArrowEncoderSuite.scala:192)
   [info]   at scala.collection.IterableOnceOps.foreach(IterableOnce.scala:576)
   [info]   at scala.collection.IterableOnceOps.foreach$(IterableOnce.scala:574)
   [info]   at scala.collection.AbstractIterator.foreach(Iterator.scala:1300)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.compareIterators(ArrowEncoderSuite.scala:189)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.roundTripAndCheck(ArrowEncoderSuite.scala:153)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.roundTripAndCheckIdentical(ArrowEncoderSuite.scala:172)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.$anonfun$new$26(ArrowEncoderSuite.scala:385)
   ...
   
   [info] - java maps *** FAILED *** (36 milliseconds)
   [info]   org.apache.spark.sql.connect.client.arrow.JavaMapData@10b8bd8b did not equal org.apache.spark.sql.connect.client.arrow.JavaMapData@7de88d79 (ArrowEncoderSuite.scala:192)
   [info]   org.scalatest.exceptions.TestFailedException:
   [info]   at org.scalatest.Assertions.newAssertionFailedException(Assertions.scala:472)
   [info]   at org.scalatest.Assertions.newAssertionFailedException$(Assertions.scala:471)
   [info]   at org.scalatest.Assertions$.newAssertionFailedException(Assertions.scala:1231)
   [info]   at org.scalatest.Assertions$AssertionsHelper.macroAssert(Assertions.scala:1295)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.$anonfun$compareIterators$1(ArrowEncoderSuite.scala:192)
   [info]   at scala.collection.IterableOnceOps.foreach(IterableOnce.scala:576)
   [info]   at scala.collection.IterableOnceOps.foreach$(IterableOnce.scala:574)
   [info]   at scala.collection.AbstractIterator.foreach(Iterator.scala:1300)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.compareIterators(ArrowEncoderSuite.scala:189)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.roundTripAndCheck(ArrowEncoderSuite.scala:153)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.roundTripAndCheckIdentical(ArrowEncoderSuite.scala:172)
   [info]   at org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite.$anonfun$new$63(ArrowEncoderSuite.scala:522)
   [info]   at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
   [info]   at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
   ```
   
   I'm not sure if this is a issue with my local environment ...


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


[GitHub] [spark] LuciferYang commented on pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on PR #40611:
URL: https://github.com/apache/spark/pull/40611#issuecomment-1632477328

   > @LuciferYang I just tried it locally, and it seems to pass on my machine (M2 MBP/Java 11). The weird thing is that both classes override `hashCode` and `equals`, so it might be an actual issue. Can you dig a bit deeper can check if - for example - DummyBean contains different values?
   
   
   Sorry, this is an wrong report. I manually deleted the `sql/catalyst/target` directory and re run the test,  all passed. 
   
   However, this makes me feel a bit strange. Previously, I executed `build/sbt clean "connect-client-jvm/testOnly org.apache.spark.sql.connect.client.arrow.ArrowEncoderSuite" -Pscala-2.13`, but it seems that `spark-catalyst_2.13-3.5.0-SNAPSHOT-tests.jar` has not been re-compiled and repackaged ...
   
   
   
   


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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261116899


##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * 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.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val itr = result.iterator
+      override def close(): Unit = itr.close()
+      override def hasNext: Boolean = itr.hasNext
+      override def next(): E = itr.next()
+    }
+  }
+
+  private def roundTripAndCheck[T](
+      encoder: AgnosticEncoder[T],
+      toInputIterator: () => Iterator[Any],
+      toOutputIterator: () => Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): Unit = {
+    val iterator = roundTrip(
+      encoder,
+      toInputIterator().asInstanceOf[Iterator[T]], // Erasure hack :)
+      maxRecordsPerBatch,
+      maxBatchSize,
+      batchSizeCheckInterval,
+      inspectBatch)
+    try {
+      compareIterators(toOutputIterator(), iterator)
+    } finally {
+      iterator.close()
+    }
+  }
+
+  private def roundTripAndCheckIdentical[T](
+      encoder: AgnosticEncoder[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null)(toIterator: () => Iterator[T]): Unit = {

Review Comment:
   Yeah this is for the next PR :)



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


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

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1154265174


##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator

Review Comment:
   ```suggestion
             mutable.WrappedArray.make(array.asInstanceOf[Array[_]]).iterator
   ```



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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 scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]
+    val SEQ: Class[_] = classOf[scala.collection.Seq[_]]
+    val SET: Class[_] = classOf[scala.collection.Set[_]]
+    val MAP: Class[_] = classOf[scala.collection.Map[_, _]]
+    val JLIST: Class[_] = classOf[java.util.List[_]]
+    val JMAP: Class[_] = classOf[java.util.Map[_, _]]
+  }
+
+  def isSubClass(cls: Class[_], tag: ClassTag[_]): Boolean = {
+    cls.isAssignableFrom(tag.runtimeClass)
+  }
+
+  def unsupportedCollectionType(cls: Class[_]): Nothing = {
+    throw new RuntimeException(s"Unsupported collection type: $cls")
+  }
+}
+
+trait CloseableIterator[E] extends Iterator[E] with AutoCloseable
+
+private[arrow] object StructVectors {
+  def unapply(v: AnyRef): Option[(StructVector, Seq[FieldVector])] = v match {
+    case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala))
+    case struct: StructVector => Option((struct, struct.getChildrenFromFields.asScala))

Review Comment:
   ```suggestion
       case struct: StructVector => Option((struct, struct.getChildrenFromFields.asScala.toSeq))
   ```



##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * 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.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val iterator = result.iterator

Review Comment:
   ```suggestion
         private val closeableIterator = result.iterator
   ```



##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * 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.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val iterator = result.iterator

Review Comment:
   `iterator`  in Scala 2.13 is a final



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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 scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]
+    val SEQ: Class[_] = classOf[scala.collection.Seq[_]]
+    val SET: Class[_] = classOf[scala.collection.Set[_]]
+    val MAP: Class[_] = classOf[scala.collection.Map[_, _]]
+    val JLIST: Class[_] = classOf[java.util.List[_]]
+    val JMAP: Class[_] = classOf[java.util.Map[_, _]]
+  }
+
+  def isSubClass(cls: Class[_], tag: ClassTag[_]): Boolean = {
+    cls.isAssignableFrom(tag.runtimeClass)
+  }
+
+  def unsupportedCollectionType(cls: Class[_]): Nothing = {
+    throw new RuntimeException(s"Unsupported collection type: $cls")
+  }
+}
+
+trait CloseableIterator[E] extends Iterator[E] with AutoCloseable
+
+private[arrow] object StructVectors {
+  def unapply(v: AnyRef): Option[(StructVector, Seq[FieldVector])] = v match {
+    case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala))
+    case struct: StructVector => Option((struct, struct.getChildrenFromFields.asScala))

Review Comment:
   for Scala 2.13



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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 scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]
+    val SEQ: Class[_] = classOf[scala.collection.Seq[_]]
+    val SET: Class[_] = classOf[scala.collection.Set[_]]
+    val MAP: Class[_] = classOf[scala.collection.Map[_, _]]
+    val JLIST: Class[_] = classOf[java.util.List[_]]
+    val JMAP: Class[_] = classOf[java.util.Map[_, _]]
+  }
+
+  def isSubClass(cls: Class[_], tag: ClassTag[_]): Boolean = {
+    cls.isAssignableFrom(tag.runtimeClass)
+  }
+
+  def unsupportedCollectionType(cls: Class[_]): Nothing = {
+    throw new RuntimeException(s"Unsupported collection type: $cls")
+  }
+}
+
+trait CloseableIterator[E] extends Iterator[E] with AutoCloseable
+
+private[arrow] object StructVectors {
+  def unapply(v: AnyRef): Option[(StructVector, Seq[FieldVector])] = v match {
+    case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala))

Review Comment:
   ```suggestion
       case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala.toSeq))
   ```



##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator

Review Comment:
   for Scala 2.13



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


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

Posted by "amaliujia (via GitHub)" <gi...@apache.org>.
amaliujia commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1153615770


##########
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 or assert?



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


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

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1154283195


##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (IterableEncoder(tag, element, _, lenient), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator: Any => Iterator[_] = if (lenient) {
+          {
+            case i: scala.collection.Iterable[_] => i.toIterator

Review Comment:
   `.toIterator` ->` iterator`,  `.toIterator` is deprecated after Scala 2.13.0



##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (IterableEncoder(tag, element, _, lenient), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator: Any => Iterator[_] = if (lenient) {
+          {
+            case i: scala.collection.Iterable[_] => i.toIterator
+            case l: java.util.List[_] => l.iterator().asScala
+            case a: Array[_] => a.iterator
+            case o => unsupportedCollectionType(o.getClass)
+          }
+        } else if (isSubClass(Classes.ITERABLE, tag)) { v =>
+          v.asInstanceOf[scala.collection.Iterable[_]].toIterator

Review Comment:
   ditto



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


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

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1260834369


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,532 @@
+/*
+ * 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, Objects}
+
+import scala.collection.JavaConverters._
+
+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 rowCount: 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(rowCount)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(rowCount, record)
+    rowCount += 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(rowCount)
+    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 = {
+    rowCount = 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] = {

Review Comment:
   What will happens if we call `hasNext` or `next()` after calling `close()`?
   
   



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,532 @@
+/*
+ * 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, Objects}
+
+import scala.collection.JavaConverters._
+
+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 rowCount: 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(rowCount)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(rowCount, record)
+    rowCount += 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(rowCount)
+    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 = {
+    rowCount = 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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()

Review Comment:
   Should we also calling `serializer.reset()` and `bytes.reset()` before `serializer.close()`?



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala:
##########
@@ -126,9 +127,9 @@ class SparkSession private[sql] (
     newDataset(encoder) { builder =>
       if (data.nonEmpty) {
         val timeZoneId = conf.get("spark.sql.session.timeZone")
-        val (arrowData, arrowDataSize) =
-          ConvertToArrow(encoder, data, timeZoneId, errorOnDuplicatedFieldNames = true, allocator)
-        if (arrowDataSize <= conf.get("spark.sql.session.localRelationCacheThreshold").toInt) {
+        // TODO add errorOnDuplicatedFieldNames?

Review Comment:
   Will this TODO not be completed in the current pr? 
   Make it a with JiraId TODO?
   
   



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * 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 scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]

Review Comment:
   Except for `ITERABLE` and `JLIST`, other types will have clear purposes?



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala:
##########
@@ -126,9 +127,9 @@ class SparkSession private[sql] (
     newDataset(encoder) { builder =>
       if (data.nonEmpty) {
         val timeZoneId = conf.get("spark.sql.session.timeZone")
-        val (arrowData, arrowDataSize) =
-          ConvertToArrow(encoder, data, timeZoneId, errorOnDuplicatedFieldNames = true, allocator)

Review Comment:
   Should we remove `ConvertToArrow` in this pr? Should it be useless?
   
   



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,532 @@
+/*
+ * 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, Objects}
+
+import scala.collection.JavaConverters._
+
+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 rowCount: 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(rowCount)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(rowCount, record)
+    rowCount += 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(rowCount)
+    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 = {
+    rowCount = 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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema =
+      ArrowUtils.toArrowSchema(encoder.schema, timeZoneId, errorOnDuplicatedFieldNames = true)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          array.asInstanceOf[Array[_]].iterator
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (IterableEncoder(tag, element, _, lenient), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator: Any => Iterator[_] = if (lenient) {
+          {
+            case i: scala.collection.Iterable[_] => i.iterator
+            case l: java.util.List[_] => l.iterator().asScala
+            case a: Array[_] => a.iterator
+            case o => unsupportedCollectionType(o.getClass)
+          }
+        } else if (isSubClass(Classes.ITERABLE, tag)) { v =>
+          v.asInstanceOf[scala.collection.Iterable[_]].iterator
+        } else if (isSubClass(Classes.JLIST, tag)) { v =>
+          v.asInstanceOf[java.util.List[_]].iterator().asScala
+        } else {
+          unsupportedCollectionType(tag.runtimeClass)
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (MapEncoder(tag, key, value, _), v: MapVector) =>
+        val structVector = v.getDataVector.asInstanceOf[StructVector]
+        val extractor = if (isSubClass(classOf[scala.collection.Map[_, _]], tag)) { (v: Any) =>
+          v.asInstanceOf[scala.collection.Map[_, _]].iterator
+        } else if (isSubClass(classOf[JMap[_, _]], tag)) { (v: Any) =>
+          v.asInstanceOf[JMap[Any, Any]].asScala.iterator
+        } else {
+          unsupportedCollectionType(tag.runtimeClass)
+        }
+        val structSerializer = new StructSerializer(
+          structVector,
+          new StructFieldSerializer(
+            extractKey,
+            serializerFor(key, structVector.getChild(MapVector.KEY_NAME))) ::
+            new StructFieldSerializer(
+              extractValue,
+              serializerFor(value, structVector.getChild(MapVector.VALUE_NAME))) :: Nil)
+        new ArraySerializer(v, extractor, structSerializer)
+
+      case (ProductEncoder(tag, fields), StructVectors(struct, vectors)) =>
+        if (isSubClass(classOf[Product], tag)) {
+          structSerializerFor(fields, struct, vectors) { (_, i) => p =>
+            p.asInstanceOf[Product].productElement(i)
+          }
+        } else if (isSubClass(classOf[DefinedByConstructorParams], tag)) {
+          structSerializerFor(fields, struct, vectors) { (field, _) =>
+            val getter = methodLookup.findVirtual(

Review Comment:
   This should be more efficient than reflection. Nice ~ :)
   
   



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261116899


##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * 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.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val itr = result.iterator
+      override def close(): Unit = itr.close()
+      override def hasNext: Boolean = itr.hasNext
+      override def next(): E = itr.next()
+    }
+  }
+
+  private def roundTripAndCheck[T](
+      encoder: AgnosticEncoder[T],
+      toInputIterator: () => Iterator[Any],
+      toOutputIterator: () => Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): Unit = {
+    val iterator = roundTrip(
+      encoder,
+      toInputIterator().asInstanceOf[Iterator[T]], // Erasure hack :)
+      maxRecordsPerBatch,
+      maxBatchSize,
+      batchSizeCheckInterval,
+      inspectBatch)
+    try {
+      compareIterators(toOutputIterator(), iterator)
+    } finally {
+      iterator.close()
+    }
+  }
+
+  private def roundTripAndCheckIdentical[T](
+      encoder: AgnosticEncoder[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null)(toIterator: () => Iterator[T]): Unit = {

Review Comment:
   Yeah this is for the next PR :)



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261109640


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala:
##########
@@ -126,9 +127,9 @@ class SparkSession private[sql] (
     newDataset(encoder) { builder =>
       if (data.nonEmpty) {
         val timeZoneId = conf.get("spark.sql.session.timeZone")
-        val (arrowData, arrowDataSize) =
-          ConvertToArrow(encoder, data, timeZoneId, errorOnDuplicatedFieldNames = true, allocator)

Review Comment:
   Let's do it in a follow-up.



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


[GitHub] [spark] hvanhovell commented on pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on PR #40611:
URL: https://github.com/apache/spark/pull/40611#issuecomment-1632443727

   @LuciferYang I just tried it locally, and it seems to pass on my machine (M2 MBP/Java 11). The weird thing is that both classes override `hashCode` and `equals`, so it might be an actual issue. Can you dig a bit deeper can check if - for example - DummyBean contains different values?


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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1260674595


##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (IterableEncoder(tag, element, _, lenient), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator: Any => Iterator[_] = if (lenient) {
+          {
+            case i: scala.collection.Iterable[_] => i.toIterator
+            case l: java.util.List[_] => l.iterator().asScala
+            case a: Array[_] => a.iterator
+            case o => unsupportedCollectionType(o.getClass)
+          }
+        } else if (isSubClass(Classes.ITERABLE, tag)) { v =>
+          v.asInstanceOf[scala.collection.Iterable[_]].toIterator

Review Comment:
   Done.



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1260675533


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

Review Comment:
   named it `rowCount`.



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261109925


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala:
##########
@@ -126,9 +127,9 @@ class SparkSession private[sql] (
     newDataset(encoder) { builder =>
       if (data.nonEmpty) {
         val timeZoneId = conf.get("spark.sql.session.timeZone")
-        val (arrowData, arrowDataSize) =
-          ConvertToArrow(encoder, data, timeZoneId, errorOnDuplicatedFieldNames = true, allocator)
-        if (arrowDataSize <= conf.get("spark.sql.session.localRelationCacheThreshold").toInt) {
+        // TODO add errorOnDuplicatedFieldNames?

Review Comment:
   Fixing it.



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


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

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1154282542


##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (IterableEncoder(tag, element, _, lenient), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator: Any => Iterator[_] = if (lenient) {
+          {
+            case i: scala.collection.Iterable[_] => i.toIterator
+            case l: java.util.List[_] => l.iterator().asScala
+            case a: Array[_] => a.iterator
+            case o => unsupportedCollectionType(o.getClass)
+          }
+        } else if (isSubClass(Classes.ITERABLE, tag)) { v =>
+          v.asInstanceOf[scala.collection.Iterable[_]].toIterator

Review Comment:
   `.toIterator` -> `iterator`, `.toIterator`  is deprecated after Scala 2.13



##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (IterableEncoder(tag, element, _, lenient), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator: Any => Iterator[_] = if (lenient) {
+          {
+            case i: scala.collection.Iterable[_] => i.toIterator
+            case l: java.util.List[_] => l.iterator().asScala
+            case a: Array[_] => a.iterator
+            case o => unsupportedCollectionType(o.getClass)
+          }
+        } else if (isSubClass(Classes.ITERABLE, tag)) { v =>
+          v.asInstanceOf[scala.collection.Iterable[_]].toIterator

Review Comment:
   `.toIterator` -> `iterator`, `.toIterator`  is deprecated after Scala 2.13.0



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


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

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1154304836


##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator

Review Comment:
   And can we just use`array.asInstanceOf[Array[_]].iterator` ?



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


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

Posted by "amaliujia (via GitHub)" <gi...@apache.org>.
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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1153984573


##########
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:
   The channels used do not hold any state. 



##########
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:
   It should throw. 



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1153602634


##########
connector/connect/client/jvm/pom.xml:
##########
@@ -120,6 +120,19 @@
         </exclusion>
       </exclusions>
     </dependency>
+    <dependency>

Review Comment:
   Needed for a couple of classes used during tests.



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1260674303


##########
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 = {

Review Comment:
   You always need to write the schema, and we also need this for (byte) size checks.



##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator
+        }
+        new ArraySerializer(v, toIterator, elementSerializer)
+
+      case (IterableEncoder(tag, element, _, lenient), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator: Any => Iterator[_] = if (lenient) {
+          {
+            case i: scala.collection.Iterable[_] => i.toIterator

Review Comment:
   Done.



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1260674847


##########
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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator

Review Comment:
   Yeah that is better.



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


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

Posted by "haiyangsun-db (via GitHub)" <gi...@apache.org>.
haiyangsun-db commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1260745063


##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * 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.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val itr = result.iterator
+      override def close(): Unit = itr.close()
+      override def hasNext: Boolean = itr.hasNext
+      override def next(): E = itr.next()
+    }
+  }
+
+  private def roundTripAndCheck[T](
+      encoder: AgnosticEncoder[T],
+      toInputIterator: () => Iterator[Any],
+      toOutputIterator: () => Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): Unit = {
+    val iterator = roundTrip(
+      encoder,
+      toInputIterator().asInstanceOf[Iterator[T]], // Erasure hack :)
+      maxRecordsPerBatch,
+      maxBatchSize,
+      batchSizeCheckInterval,
+      inspectBatch)
+    try {
+      compareIterators(toOutputIterator(), iterator)
+    } finally {
+      iterator.close()
+    }
+  }
+
+  private def roundTripAndCheckIdentical[T](
+      encoder: AgnosticEncoder[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null)(toIterator: () => Iterator[T]): Unit = {

Review Comment:
   It seems that `inspectBatch` is not used in the tests. Maybe add a TODO here to enrich the tests to verify the converted results are expected (even though the round trip works).



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


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

Posted by "hvanhovell (via GitHub)" <gi...@apache.org>.
hvanhovell commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261132180


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,532 @@
+/*
+ * 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, Objects}
+
+import scala.collection.JavaConverters._
+
+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 rowCount: 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(rowCount)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(rowCount, record)
+    rowCount += 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(rowCount)
+    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 = {
+    rowCount = 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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()

Review Comment:
   It is not really needed:
   - Bytes holds on to an on-heap byte array. That will get picked-up by GC.
   - Reset reinitializes buffers which is more expensive than just closing them.



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


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

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1261139401


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,532 @@
+/*
+ * 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, Objects}
+
+import scala.collection.JavaConverters._
+
+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 rowCount: 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(rowCount)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(rowCount, record)
+    rowCount += 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(rowCount)
+    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 = {
+    rowCount = 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()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()

Review Comment:
   Got it



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