You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by BryanCutler <gi...@git.apache.org> on 2016/11/09 01:13:19 UTC

[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

GitHub user BryanCutler opened a pull request:

    https://github.com/apache/spark/pull/15821

    [SPARK-13534][WIP][PySpark] Using Apache Arrow to increase performance of DataFrame.toPandas

    ## What changes were proposed in this pull request?
    WIP to integrate Apache Arrow with Spark to increase performance of DataFrame.toPandas
    
    ## How was this patch tested?
    Added new unittests, conditional on if PyArrow is installed

You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/BryanCutler/spark wip-toPandas_with_arrow-SPARK-13534

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/spark/pull/15821.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #15821
    
----
commit 155c26db728391a45f8d890413c1393cd9655d82
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-24T17:54:16Z

    Added Arrow 0.1.0 as dependency to Spark-SQL and stub for collectAsArrow()

commit d556970429355b92844c12446406461fc6ae3ca4
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-24T18:28:19Z

    added function collectAsArrowToPython for python API

commit a6171d7b0ea83b39025f6febfbaa0688618b678f
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-26T19:27:56Z

    Changed conversion to use ArrowRecordBatch in Scala

commit 54ac65b397076d63afd201765578372319309adf
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-26T21:39:17Z

    added framework for PySpark toPandas using pyarrow, untested

commit 4f9943ff10fcd82640661ea5f29f3f908b3cf1b0
Author: Xusen Yin <yi...@gmail.com>
Date:   2016-10-27T04:49:09Z

    prototype code to reuse serveIterator and _load_from_socket

commit da5ea5b4ebda86d40167cb03e7f8fb3f744cf2f7
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-27T06:07:44Z

    Merge pull request #3 from yinxusen/wip-toPandas_with_arrow-SPARK-13534
    
    reusable collect

commit 89f87c17520470dfb1e25b73b21e6f355627deec
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-31T18:02:16Z

    Fixed compilation error, now using case class intead of tuple in iterator

commit 20b5aa0f07037c06cbf1bda1a1940d960e145fb2
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-31T18:24:14Z

    removed unused imports

commit 3c112f6d3dbe2a4c5b76b04bc57999484b5959ac
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-10-31T23:38:25Z

    added dependency exclusions for arrow-vector, uses conflicting jackson lib

commit 06b19caff4e0174c92501ea0942bffd8b63ea3a2
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-01T00:28:07Z

    started adding roundtrip test using DataFrame.toPandas

commit 1657928d9878e6f8769adc5d50802053eb660af5
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-01T00:31:56Z

    fixed some minor issues with toPandas pipeline

commit 842b620a19e3f51e6c9f3bdaaa69e3a5bf0f382b
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-01T00:58:19Z

    fixed spacing

commit 795684e9f4e8fd0458fd4a056e2d68417fb37306
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-01T19:46:04Z

    Need to pass instance of ArrowSerializer to _load_from_socket

commit 39b4f02c764c14bea46ca91ba3c2e0143543b53c
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-03T23:55:52Z

    Simplified by serving byte array to PythonRDD

commit f4ed56fdeafe4805d8541f36aa876c3c4c530436
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-04T00:51:26Z

    added in hard-coded test batch, not quite working

commit af63fc263f4a6a5dd59d7b3b8d8ccee44fd67cc9
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-08T01:02:13Z

    pyspark df had incorrect method name for ArrowRecordBatch.to_pandas()

commit 8180a95f1178ace76643fd5e57302185bb8b730e
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-08T01:04:23Z

    added test to exercise the Python API of Arrow by sending a bytearray through Spark DataFrame without serialization

commit 35a32c2bda210cd3aeeb207bcb9dc55b112c17ae
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-09T01:02:22Z

    moved pyarrow import, since it will most likely not be a required dependency.  some minor cleanup

commit 275602c9fe83e1eb595ca7ae70dcc340b99a8916
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-09T01:07:43Z

    accidentally removed newlines in import

commit a35a441ce01ec1cc95d384b6a008780a61768b08
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-09T01:08:48Z

    Arrow no longer a dependency in PythonRDD

commit 4227ec6696af2289c47eb0bd0f7872d50f69d302
Author: Bryan Cutler <cu...@gmail.com>
Date:   2016-11-09T01:12:03Z

    minor cleanup of test case

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112382152
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/ArrowConvertersSuite.scala ---
    @@ -0,0 +1,568 @@
    +/*
    + * 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
    +
    +import java.io.File
    +import java.nio.charset.StandardCharsets
    +import java.sql.{Date, Timestamp}
    +import java.text.SimpleDateFormat
    +import java.util.Locale
    +
    +import com.google.common.io.Files
    +import org.apache.arrow.vector.{VectorLoader, VectorSchemaRoot}
    +import org.apache.arrow.vector.file.json.JsonFileReader
    +import org.apache.arrow.vector.util.Validator
    +import org.json4s.jackson.JsonMethods._
    +import org.json4s.JsonAST._
    +import org.json4s.JsonDSL._
    +import org.scalatest.BeforeAndAfterAll
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.StructType
    +import org.apache.spark.util.Utils
    +
    +
    +class ArrowConvertersSuite extends SharedSQLContext with BeforeAndAfterAll {
    +  import testImplicits._
    +
    +  private var tempDataPath: String = _
    +
    +  private def collectAsArrow(df: DataFrame,
    +                             converter: Option[ArrowConverters] = None): ArrowPayload = {
    +    val cnvtr = converter.getOrElse(new ArrowConverters)
    +    val payloadByteArrays = df.toArrowPayloadBytes().collect()
    +    cnvtr.readPayloadByteArrays(payloadByteArrays)
    +  }
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    tempDataPath = Utils.createTempDir(namePrefix = "arrow").getAbsolutePath
    +  }
    +
    +  test("collect to arrow record batch") {
    +    val indexData = (1 to 6).toDF("i")
    +    val arrowPayload = collectAsArrow(indexData)
    +    assert(arrowPayload.nonEmpty)
    +    val arrowBatches = arrowPayload.toArray
    +    assert(arrowBatches.length == indexData.rdd.getNumPartitions)
    +    val rowCount = arrowBatches.map(batch => batch.getLength).sum
    +    assert(rowCount === indexData.count())
    +    arrowBatches.foreach(batch => assert(batch.getNodes.size() > 0))
    +    arrowBatches.foreach(batch => batch.close())
    +  }
    +
    +  test("numeric type conversion") {
    +    collectAndValidate(indexData)
    +    collectAndValidate(shortData)
    +    collectAndValidate(intData)
    +    collectAndValidate(longData)
    +    collectAndValidate(floatData)
    +    collectAndValidate(doubleData)
    +  }
    +
    +  test("mixed numeric type conversion") {
    +    collectAndValidate(mixedNumericData)
    +  }
    +
    +  test("boolean type conversion") {
    +    collectAndValidate(boolData)
    +  }
    +
    +  test("string type conversion") {
    +    collectAndValidate(stringData)
    +  }
    +
    +  test("byte type conversion") {
    +    collectAndValidate(byteData)
    +  }
    +
    +  ignore("timestamp conversion") {
    +    collectAndValidate(timestampData)
    +  }
    +
    +  // TODO: Not currently supported in Arrow JSON reader
    +  ignore("date conversion") {
    +    // collectAndValidate(dateTimeData)
    +  }
    +
    +  // TODO: Not currently supported in Arrow JSON reader
    +  ignore("binary type conversion") {
    +    // collectAndValidate(binaryData)
    +  }
    +
    +  test("floating-point NaN") {
    +    collectAndValidate(floatNaNData)
    +  }
    +
    +  test("partitioned DataFrame") {
    +    val converter = new ArrowConverters
    +    val schema = testData2.schema
    +    val arrowPayload = collectAsArrow(testData2, Some(converter))
    +    val arrowBatches = arrowPayload.toArray
    +    // NOTE: testData2 should have 2 partitions -> 2 arrow batches in payload
    +    assert(arrowBatches.length === 2)
    +    val pl1 = new ArrowStaticPayload(arrowBatches(0))
    +    val pl2 = new ArrowStaticPayload(arrowBatches(1))
    +    // Generate JSON files
    +    val a = List[Int](1, 1, 2, 2, 3, 3)
    +    val b = List[Int](1, 2, 1, 2, 1, 2)
    +    val fields = Seq(new IntegerType("a", is_signed = true, 32, nullable = false),
    +      new IntegerType("b", is_signed = true, 32, nullable = false))
    +    def getBatch(x: Seq[Int], y: Seq[Int]): JSONRecordBatch = {
    +      val columns = Seq(new PrimitiveColumn("a", x.length, x.map(_ => true), x),
    +        new PrimitiveColumn("b", y.length, y.map(_ => true), y))
    +      new JSONRecordBatch(x.length, columns)
    +    }
    +    val json1 = new JSONFile(new JSONSchema(fields), Seq(getBatch(a.take(3), b.take(3))))
    +    val json2 = new JSONFile(new JSONSchema(fields), Seq(getBatch(a.takeRight(3), b.takeRight(3))))
    +    val tempFile1 = new File(tempDataPath, "testData2-ints-part1.json")
    +    val tempFile2 = new File(tempDataPath, "testData2-ints-part2.json")
    +    json1.write(tempFile1)
    +    json2.write(tempFile2)
    +    validateConversion(schema, pl1, tempFile1, Some(converter))
    +    validateConversion(schema, pl2, tempFile2, Some(converter))
    +  }
    +
    +  test("empty frame collect") {
    +    val arrowPayload = collectAsArrow(spark.emptyDataFrame)
    +    assert(arrowPayload.isEmpty)
    +  }
    +
    +  test("empty partition collect") {
    +    val emptyPart = spark.sparkContext.parallelize(Seq(1), 2).toDF("i")
    +    val arrowPayload = collectAsArrow(emptyPart)
    +    val arrowBatches = arrowPayload.toArray
    +    assert(arrowBatches.length === 2)
    +    assert(arrowBatches.count(_.getLength == 0) === 1)
    +    assert(arrowBatches.count(_.getLength == 1) === 1)
    +  }
    +
    +  test("unsupported types") {
    +    def runUnsupported(block: => Unit): Unit = {
    +      val msg = intercept[SparkException] {
    +        block
    +      }
    +      assert(msg.getMessage.contains("Unsupported data type"))
    +      assert(msg.getCause.getClass === classOf[UnsupportedOperationException])
    +    }
    +
    +    runUnsupported { collectAsArrow(decimalData) }
    +    runUnsupported { collectAsArrow(arrayData.toDF()) }
    +    runUnsupported { collectAsArrow(mapData.toDF()) }
    +    runUnsupported { collectAsArrow(complexData) }
    +  }
    +
    +  test("test Arrow Validator") {
    +    val sdata = shortData
    +    val idata = intData
    +
    +    // Different schema
    +    intercept[IllegalArgumentException] {
    +      collectAndValidate(DataTuple(sdata.df, idata.json, idata.file))
    +    }
    +
    +    // Different values
    +    intercept[IllegalArgumentException] {
    +      collectAndValidate(DataTuple(idata.df.sort($"a_i".desc), idata.json, idata.file))
    +    }
    +  }
    +
    +  /** Test that a converted DataFrame to Arrow record batch equals batch read from JSON file */
    +  private def collectAndValidate(data: DataTuple): Unit = {
    +    val converter = new ArrowConverters
    +    // NOTE: coalesce to single partition because can only load 1 batch in validator
    +    val arrowPayload = collectAsArrow(data.df.coalesce(1), Some(converter))
    +    val tempFile = new File(tempDataPath, data.file)
    +    data.json.write(tempFile)
    +    validateConversion(data.df.schema, arrowPayload, tempFile, Some(converter))
    +  }
    +
    +  private def validateConversion(sparkSchema: StructType,
    +                                 arrowPayload: ArrowPayload,
    +                                 jsonFile: File,
    +                                 converterOpt: Option[ArrowConverters] = None): Unit = {
    +    val converter = converterOpt.getOrElse(new ArrowConverters)
    +    val jsonReader = new JsonFileReader(jsonFile, converter.allocator)
    +
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(sparkSchema)
    +    val jsonSchema = jsonReader.start()
    +    Validator.compareSchemas(arrowSchema, jsonSchema)
    +
    +    val arrowRoot = new VectorSchemaRoot(arrowSchema, converter.allocator)
    +    val vectorLoader = new VectorLoader(arrowRoot)
    +    arrowPayload.foreach(vectorLoader.load)
    +    val jsonRoot = jsonReader.read()
    +    Validator.compareVectorSchemaRoot(arrowRoot, jsonRoot)
    +  }
    +
    +  // Create Spark DataFrame and matching Arrow JSON at same time for validation
    +  private case class DataTuple(df: DataFrame, json: JSONFile, file: String)
    +
    +  private def indexData: DataTuple = {
    +    val data = List[Int](1, 2, 3, 4, 5, 6)
    +    val fields = Seq(new IntegerType("i", is_signed = true, 32, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("i", data.length, data.map(_ => true), data))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("i"), new JSONFile(schema, Seq(batch)), "indexData-ints.json")
    +  }
    +
    +  private def shortData: DataTuple = {
    +    val a_s = List[Short](1, -1, 2, -2, 32767, -32768)
    +    val b_s = List[Option[Short]](Some(1), None, None, Some(-2), None, Some(-32768))
    +    val fields = Seq(new IntegerType("a_s", is_signed = true, 16, nullable = false),
    +      new IntegerType("b_s", is_signed = true, 16, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val b_s_values = b_s.map(_.map(_.toInt).getOrElse(0))
    +    val columns = Seq(
    +      new PrimitiveColumn("a_s", a_s.length, a_s.map(_ => true), a_s.map(_.toInt)),
    +      new PrimitiveColumn("b_s", b_s.length, b_s.map(_.isDefined), b_s_values))
    +    val batch = new JSONRecordBatch(a_s.length, columns)
    +    val df = a_s.zip(b_s).toDF("a_s", "b_s")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-16bit.json")
    +  }
    +
    +  private def intData: DataTuple = {
    +    val a_i = List[Int](1, -1, 2, -2, 2147483647, -2147483648)
    +    val b_i = List[Option[Int]](Some(1), None, None, Some(-2), None, Some(-2147483648))
    +    val fields = Seq(new IntegerType("a_i", is_signed = true, 32, nullable = false),
    +      new IntegerType("b_i", is_signed = true, 32, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_i", a_i.length, a_i.map(_ => true), a_i),
    +      new PrimitiveColumn("b_i", b_i.length, b_i.map(_.isDefined), b_i.map(_.getOrElse(0))))
    +    val batch = new JSONRecordBatch(a_i.length, columns)
    +    val df = a_i.zip(b_i).toDF("a_i", "b_i")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-32bit.json")
    +  }
    +
    +  private def longData: DataTuple = {
    +    val a_l = List[Long](1, -1, 2, -2, 9223372036854775807L, -9223372036854775808L)
    +    val b_l = List[Option[Long]](Some(1), None, None, Some(-2), None, Some(-9223372036854775808L))
    +    val fields = Seq(new IntegerType("a_l", is_signed = true, 64, nullable = false),
    +      new IntegerType("b_l", is_signed = true, 64, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_l", a_l.length, a_l.map(_ => true), a_l),
    +      new PrimitiveColumn("b_l", b_l.length, b_l.map(_.isDefined), b_l.map(_.getOrElse(0L))))
    +    val batch = new JSONRecordBatch(a_l.length, columns)
    +    val df = a_l.zip(b_l).toDF("a_l", "b_l")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-64bit.json")
    +  }
    +
    +  private def floatData: DataTuple = {
    +    val a_f = List(1.0f, 2.0f, 0.01f, 200.0f, 0.0001f, 20000.0f)
    +    val b_f = List[Option[Float]](Some(1.1f), None, None, Some(2.2f), None, Some(3.3f))
    +    val fields = Seq(new FloatingPointType("a_f", 32, nullable = false),
    +      new FloatingPointType("b_f", 32, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_f", a_f.length, a_f.map(_ => true), a_f),
    +      new PrimitiveColumn("b_f", b_f.length, b_f.map(_.isDefined), b_f.map(_.getOrElse(0.0f))))
    +    val batch = new JSONRecordBatch(a_f.length, columns)
    +    val df = a_f.zip(b_f).toDF("a_f", "b_f")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "floating_point-single_precision.json")
    +  }
    +
    +  private def doubleData: DataTuple = {
    +    val a_d = List(1.0, 2.0, 0.01, 200.0, 0.0001, 20000.0)
    +    val b_d = List[Option[Double]](Some(1.1), None, None, Some(2.2), None, Some(3.3))
    +    val fields = Seq(new FloatingPointType("a_d", 64, nullable = false),
    +      new FloatingPointType("b_d", 64, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_d", a_d.length, a_d.map(_ => true), a_d),
    +      new PrimitiveColumn("b_d", b_d.length, b_d.map(_.isDefined), b_d.map(_.getOrElse(0.0))))
    +    val batch = new JSONRecordBatch(a_d.length, columns)
    +    val df = a_d.zip(b_d).toDF("a_d", "b_d")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "floating_point-double_precision.json")
    +  }
    +
    +  private def mixedNumericData: DataTuple = {
    +    val data = List(1, 2, 3, 4, 5, 6)
    +    val fields = Seq(new IntegerType("a", is_signed = true, 16, nullable = false),
    +      new FloatingPointType("b", 32, nullable = false),
    +      new IntegerType("c", is_signed = true, 32, nullable = false),
    +      new FloatingPointType("d", 64, nullable = false),
    +      new IntegerType("e", is_signed = true, 64, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a", data.length, data.map(_ => true), data),
    +      new PrimitiveColumn("b", data.length, data.map(_ => true), data.map(_.toFloat)),
    +      new PrimitiveColumn("c", data.length, data.map(_ => true), data),
    +      new PrimitiveColumn("d", data.length, data.map(_ => true), data.map(_.toDouble)),
    +      new PrimitiveColumn("e", data.length, data.map(_ => true), data)
    +    )
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    val data_tuples = for (d <- data) yield {
    +      (d.toShort, d.toFloat, d.toInt, d.toDouble, d.toLong)
    +    }
    +    val df = data_tuples.toDF("a", "b", "c", "d", "e")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "mixed_numeric_types.json")
    +  }
    +
    +  private def boolData: DataTuple = {
    +    val data = Seq(true, true, false, true)
    +    val fields = Seq(new BooleanType("a_bool", nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_bool", data.length, data.map(_ => true), data))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("a_bool"), new JSONFile(schema, Seq(batch)), "boolData.json")
    +  }
    +
    +  private def stringData: DataTuple = {
    +    val upperCase = Seq("A", "B", "C")
    +    val lowerCase = Seq("a", "b", "c")
    +    val nullStr = Seq("ab", "CDE", null)
    +    val fields = Seq(new StringType("upper_case", nullable = true),
    +      new StringType("lower_case", nullable = true),
    +      new StringType("null_str", nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new StringColumn("upper_case", upperCase.length, upperCase.map(_ => true), upperCase),
    +      new StringColumn("lower_case", lowerCase.length, lowerCase.map(_ => true), lowerCase),
    +      new StringColumn("null_str", nullStr.length, nullStr.map(_ != null),
    +        nullStr.map { s => if (s == null) "" else s}
    +      ))
    +    val batch = new JSONRecordBatch(upperCase.length, columns)
    +    val df = (upperCase, lowerCase, nullStr).zipped.toList
    +      .toDF("upper_case", "lower_case", "null_str")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "stringData.json")
    +  }
    +
    +  private def byteData: DataTuple = {
    +    val data = List[Byte](1.toByte, (-1).toByte, 64.toByte, Byte.MaxValue)
    +    val fields = Seq(new IntegerType("a_byte", is_signed = true, 8, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_byte", data.length, data.map(_ => true), data.map(_.toInt)))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("a_byte"), new JSONFile(schema, Seq(batch)), "byteData.json")
    +  }
    +
    +  private def floatNaNData: DataTuple = {
    +    val fnan = Seq(1.2F, Float.NaN)
    +    val dnan = Seq(Double.NaN, 1.2)
    +    val fields = Seq(new FloatingPointType("NaN_f", 32, nullable = false),
    +      new FloatingPointType("NaN_d", 64, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("NaN_f", fnan.length, fnan.map(_ => true), fnan),
    +      new PrimitiveColumn("NaN_d", dnan.length, dnan.map(_ => true), dnan))
    +    val batch = new JSONRecordBatch(fnan.length, columns)
    +    val df = fnan.zip(dnan).toDF("NaN_f", "NaN_d")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "nanData-floating_point.json")
    +  }
    +
    +  private def timestampData: DataTuple = {
    +    val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z", Locale.US)
    +    val ts1 = new Timestamp(sdf.parse("2013-04-08 01:10:15.567 UTC").getTime)
    +    val ts2 = new Timestamp(sdf.parse("2013-04-08 13:10:10.789 UTC").getTime)
    +    val data = Seq(ts1, ts2)
    +    val schema = new JSONSchema(Seq(new TimestampType("c_timestamp")))
    +    val columns = Seq(
    +      new PrimitiveColumn("c_timestamp", data.length, data.map(_ => true), data.map(_.getTime)))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("c_timestamp"), new JSONFile(schema, Seq(batch)), "timestampData.json")
    +  }
    +
    +  private def dateData: DataTuple = {
    +    val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z", Locale.US)
    +    val d1 = new Date(sdf.parse("2015-04-08 13:10:15.000 UTC").getTime)
    +    val d2 = new Date(sdf.parse("2015-04-08 13:10:15.000 UTC").getTime)
    +    val ts1 = new Timestamp(sdf.parse("2013-04-08 01:10:15.567 UTC").getTime)
    +    val ts2 = new Timestamp(sdf.parse("2013-04-08 13:10:10.789 UTC").getTime)
    +    val df = Seq((d1, sdf.format(d1), ts1), (d2, sdf.format(d2), ts2))
    +      .toDF("a_date", "b_string", "c_timestamp")
    +    val jsonFile = new JSONFile(new JSONSchema(Seq.empty[DataType]), Seq.empty[JSONRecordBatch])
    +    DataTuple(df, jsonFile, "dateData.json")
    +  }
    +
    +  /**
    +   * Arrow JSON Format Data Generation
    +   * Referenced from https://github.com/apache/arrow/blob/master/integration/integration_test.py
    +   * TODO: Look into using JSON generation from parquet-vector.jar
    +   */
    +
    +  private abstract class DataType(name: String, nullable: Boolean) {
    --- End diff --
    
    rather than defining the json using objects and serialize them, can we just put the json as a string inline? that'd be much easier to inspect ...



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112373858
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +
    +    // Iterate over payload batches to write each one, ensure all batches get closed
    +    var batch: ArrowRecordBatch = null
    +    Utils.tryWithSafeFinallyAndFailureCallbacks {
    --- End diff --
    
    in what conditions would this fail? explain as inline comment


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    No problem @rxin , I will restructure the tests so that the json data is local to each test, and ping you when done.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #73308 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/73308/testReport)** for PR 15821 at commit [`42af1d5`](https://github.com/apache/spark/commit/42af1d59c6c8e6fbb0f38cd8d1b1afbe86076aa1).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r98075898
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Arrow.scala ---
    @@ -0,0 +1,310 @@
    +/*
    +* 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
    +
    +import scala.collection.JavaConverters._
    +import scala.language.implicitConversions
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +object Arrow {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: ${dataType}")
    +    }
    +  }
    +
    +  /**
    +   * Transfer an array of InternalRow to an ArrowRecordBatch.
    +   */
    +  private[sql] def internalRowsToArrowRecordBatch(
    +      rows: Array[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +    val fieldAndBuf = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      internalRowToArrowBuf(rows, ordinal, field, allocator)
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1.flatten
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val recordBatch = new ArrowRecordBatch(rows.length,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Write a Field from array of InternalRow to an ArrowBuf.
    +   */
    +  private def internalRowToArrowBuf(
    +      rows: Array[InternalRow],
    +      ordinal: Int,
    +      field: StructField,
    +      allocator: RootAllocator): (Array[ArrowFieldNode], Array[ArrowBuf]) = {
    +    val numOfRows = rows.length
    +    val columnWriter = ColumnWriter(allocator, field.dataType)
    +    columnWriter.init(numOfRows)
    +    var index = 0
    +
    +    while(index < numOfRows) {
    +      val row = rows(index)
    +      if (row.isNullAt(ordinal)) {
    +        columnWriter.writeNull()
    +      } else {
    +        columnWriter.write(row, ordinal)
    +      }
    +      index += 1
    +    }
    +
    +    val (arrowFieldNodes, arrowBufs) = columnWriter.finish()
    +    (arrowFieldNodes.toArray, arrowBufs.toArray)
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(initialSize: Int): Unit
    +  def writeNull(): Unit
    +  def write(row: InternalRow, ordinal: Int): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(protected val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  protected def valueVector: BaseDataValueVector
    +  protected def valueMutator: BaseMutator
    +
    +  protected def setNull(): Unit
    +  protected def setValue(row: InternalRow, ordinal: Int): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(initialSize: Int): Unit = {
    +    valueVector.allocateNew()
    +  }
    +
    +  override def writeNull(): Unit = {
    +    setNull()
    +    nullCount += 1
    +    count += 1
    +  }
    +
    +  override def write(row: InternalRow, ordinal: Int): Unit = {
    +    setValue(row, ordinal)
    +    count += 1
    +  }
    +
    +  override def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers: Seq[ArrowBuf] = valueVector.getBuffers(true)
    +    (List(fieldNode), valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    +
    +  override protected val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", allocator)
    +  override protected val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, bool2int(row.getBoolean(ordinal)))
    +}
    +
    +private[sql] class ShortColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", allocator)
    +  override protected val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[sql] class IntegerColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", allocator)
    +  override protected val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[sql] class LongColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", allocator)
    +  override protected val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[sql] class FloatColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", allocator)
    +  override protected val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[sql] class DoubleColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", allocator)
    +  override protected val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[sql] class ByteColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", allocator)
    +  override protected val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[sql] class UTF8StringColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    +  override protected val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    val bytes = row.getUTF8String(ordinal).getBytes
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class BinaryColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    +  override protected val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    val bytes = row.getBinary(ordinal)
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class DateColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableDateVector
    +    = new NullableDateVector("DateValue", allocator)
    +  override protected val valueMutator: NullableDateVector#Mutator = valueVector.getMutator
    +
    +  override protected def setNull(): Unit = valueMutator.setNull(count)
    +  override protected def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    valueMutator.setSafe(count, row.getInt(ordinal).toLong * 24 * 3600 * 1000)
    --- End diff --
    
    Can you add a comment explaining the difference between the value representations (date ordinal vs. Joda-compatible milliseconds timestamp)?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by julienledem <gi...@git.apache.org>.
Github user julienledem commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105322283
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val fieldAndBuf = columnWriters.map { writer =>
    +      writer.finish()
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1
    +    val buffers = fieldAndBuf._2.flatten
    --- End diff --
    
    how about
    ```
    val (fieldNodes, buf) = columnWriters.map( _.finish()).unzip
    val buffers = buf.flatten
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112365872
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1635,21 +1636,49 @@ def toDF(self, *cols):
             return DataFrame(jdf, self.sql_ctx)
     
         @since(1.3)
    -    def toPandas(self):
    -        """Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.
    +    def toPandas(self, useArrow=False):
    +        """
    +        Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.
     
             This is only available if Pandas is installed and available.
     
    +        :param useArrow: Make use of Apache Arrow for conversion, pyarrow must be installed
    +            and available on the calling Python process (Experimental).
    +
             .. note:: This method should only be used if the resulting Pandas's DataFrame is expected
                 to be small, as all the data is loaded into the driver's memory.
     
    +        .. note:: Using pyarrow is experimental and currently supports the following data types:
    --- End diff --
    
    remove this after you moved the control to a SQLConf.



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    >  An instance of this must be used each time a ArrowRecordBatch is created and then the batch and allocator must be released/closed after they have been processed
    
    I think it would useful to add test to check memory leaks in error cases, for instance:
    * Have a dataframe that throws exception after n rows. Invoke the arrow conversion function, and check allocator memory usage.
    * Have a dataframe that is slow, invoke the arrow conversion function, cancel the task, and check allocator memory usage.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #68381 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/68381/consoleFull)** for PR 15821 at commit [`4227ec6`](https://github.com/apache/spark/commit/4227ec6696af2289c47eb0bd0f7872d50f69d302).
     * This patch **fails Scala style tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by mariusvniekerk <gi...@git.apache.org>.
Github user mariusvniekerk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Probably a good thing to look at is the R pieces since that is effectively constrained to InternalRow


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121831432
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as an Array[Byte].
    +   */
    +  def toByteArray: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    --- End diff --
    
    do you know what's the difference between Arrow decimal and Spark decimal? In Spark, the decimal will be stored as int if precision is less than 9, and be stored as long if precision is less than 18, and be stored as byte array otherwise


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #71950 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/71950/testReport)** for PR 15821 at commit [`9bb75de`](https://github.com/apache/spark/commit/9bb75de474f5e97f5dbc67481f7339b01c25380a).
     * This patch **fails Python style tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    the last build still failed, shall we update `dev/run-pip-tests` to use pip?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/68806/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r108582862
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2747,6 +2747,17 @@ class Dataset[T] private[sql](
         }
       }
     
    +  /**
    +   * Collect a Dataset as ArrowPayload byte arrays and serve to PySpark.
    +   */
    +  private[sql] def collectAsArrowToPython(): Int = {
    +    val payloadRdd = toArrowPayloadBytes()
    +    val payloadByteArrays = payloadRdd.collect()
    --- End diff --
    
    Can it be better to use`PythonRDD.toLocalIteratorAndServe` to serve a local iterator of the rdd to python side?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/76210/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112376143
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +
    +    // Iterate over payload batches to write each one, ensure all batches get closed
    +    var batch: ArrowRecordBatch = null
    +    Utils.tryWithSafeFinallyAndFailureCallbacks {
    +      while (payload.hasNext) {
    +        batch = payload.next()
    +        writer.writeRecordBatch(batch)
    +        batch.close()
    +      }
    +    }(catchBlock = {
    +      Option(batch).foreach(_.close())
    +      payload.foreach(_.close())
    +    }, finallyBlock = writer.close())
    +
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    +
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, bool2int(row.getBoolean(ordinal)))
    +}
    +
    +private[sql] class ShortColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", allocator)
    +  override val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[sql] class IntegerColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", allocator)
    +  override val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[sql] class LongColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", allocator)
    +  override val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[sql] class FloatColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", allocator)
    +  override val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[sql] class DoubleColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", allocator)
    +  override val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[sql] class ByteColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", allocator)
    +  override val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[sql] class UTF8StringColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    +  override val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    val bytes = row.getUTF8String(ordinal).getBytes
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class BinaryColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("BinaryValue", allocator)
    +  override val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    val bytes = row.getBinary(ordinal)
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class DateColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableDateVector
    +    = new NullableDateVector("DateValue", allocator)
    +  override val valueMutator: NullableDateVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    // TODO: comment on diff btw value representations of date/timestamp
    --- End diff --
    
    just resolve this todo?



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks for doing this @shaneknapp and @holdenk!  I'm about to hop on a
    plane but should be online later this afternoon.  I can switch out the
    pyarrow tests then if it still needs to be done.
    
    On Jun 27, 2017 11:41 AM, "shane" <no...@github.com> wrote:
    
    (py3k)-bash-4.1$ pip install pyarrow
    Requirement already satisfied: pyarrow in
    /home/anaconda/envs/py3k/lib/python3.4/site-packages
    Requirement already satisfied: six>=1.0.0 in
    /home/anaconda/envs/py3k/lib/python3.4/site-packages (from pyarrow)
    Requirement already satisfied: numpy>=1.9 in
    /home/anaconda/envs/py3k/lib/python3.4/site-packages (from pyarrow)
    
    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    <https://github.com/apache/spark/pull/15821#issuecomment-311448005>, or mute
    the thread
    <https://github.com/notifications/unsubscribe-auth/AEUwdY89qgk_vgXme5GE1LFif_KDi183ks5sIUzngaJpZM4KtGBc>
    .



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #77401 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/77401/testReport)** for PR 15821 at commit [`d49a14d`](https://github.com/apache/spark/commit/d49a14daea3a5e92c2cfdf579373ca13b96c20e5).
     * This patch **fails build dependency tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r115635616
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as an Array[Byte].
    +   */
    +  def toByteArray: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload. Limit ArrowRecordBatch size in ArrowPayload
    +   * by setting maxRecordsPerBatch or use 0 to fully consume rowIter.
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      maxRecordsPerBatch: Int): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator, maxRecordsPerBatch)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch, stopping when rowIter is consumed
    +   * or the number of records in the batch equals maxRecordsInBatch.  If maxRecordsPerBatch is 0,
    +   * then rowIter will be fully consumed.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator,
    +      maxRecordsPerBatch: Int = 0): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(field.dataType, ordinal, allocator).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    var recordsInBatch = 0
    +    while (rowIter.hasNext && (maxRecordsPerBatch <= 0 || recordsInBatch < maxRecordsPerBatch)) {
    --- End diff --
    
    rows with different schema have very different sizes, e.g. a row with a single int column should be much smaller than a row with 10 string columns. Should we bound the batch by data size instead of by the number of records?
    
    cc @liancheng, do you know how parquet writer works in this case?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r101218456
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2729,6 +2749,18 @@ class Dataset[T] private[sql](
         }
       }
     
    +  /**
    +   * Collect a Dataset as an ArrowRecordBatch, and serve the ArrowRecordBatch to PySpark.
    +   */
    +  private[sql] def collectAsArrowToPython(): Int = {
    +    val payload = collectAsArrow()
    +    val payloadBytes = ArrowConverters.payloadToByteArray(payload, this.schema)
    +
    +    withNewExecutionId {
    +      PythonRDD.serveIterator(Iterator(payloadBytes), "serve-Arrow")
    --- End diff --
    
    Can we convert dataset to payload without collecting them back to driver?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r113600926
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/ArrowConvertersSuite.scala ---
    @@ -0,0 +1,568 @@
    +/*
    + * 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
    +
    +import java.io.File
    +import java.nio.charset.StandardCharsets
    +import java.sql.{Date, Timestamp}
    +import java.text.SimpleDateFormat
    +import java.util.Locale
    +
    +import com.google.common.io.Files
    +import org.apache.arrow.vector.{VectorLoader, VectorSchemaRoot}
    +import org.apache.arrow.vector.file.json.JsonFileReader
    +import org.apache.arrow.vector.util.Validator
    +import org.json4s.jackson.JsonMethods._
    +import org.json4s.JsonAST._
    +import org.json4s.JsonDSL._
    +import org.scalatest.BeforeAndAfterAll
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.StructType
    +import org.apache.spark.util.Utils
    +
    +
    +class ArrowConvertersSuite extends SharedSQLContext with BeforeAndAfterAll {
    +  import testImplicits._
    +
    +  private var tempDataPath: String = _
    +
    +  private def collectAsArrow(df: DataFrame,
    +                             converter: Option[ArrowConverters] = None): ArrowPayload = {
    +    val cnvtr = converter.getOrElse(new ArrowConverters)
    +    val payloadByteArrays = df.toArrowPayloadBytes().collect()
    +    cnvtr.readPayloadByteArrays(payloadByteArrays)
    +  }
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    tempDataPath = Utils.createTempDir(namePrefix = "arrow").getAbsolutePath
    +  }
    +
    +  test("collect to arrow record batch") {
    +    val indexData = (1 to 6).toDF("i")
    +    val arrowPayload = collectAsArrow(indexData)
    +    assert(arrowPayload.nonEmpty)
    +    val arrowBatches = arrowPayload.toArray
    +    assert(arrowBatches.length == indexData.rdd.getNumPartitions)
    +    val rowCount = arrowBatches.map(batch => batch.getLength).sum
    +    assert(rowCount === indexData.count())
    +    arrowBatches.foreach(batch => assert(batch.getNodes.size() > 0))
    +    arrowBatches.foreach(batch => batch.close())
    +  }
    +
    +  test("numeric type conversion") {
    +    collectAndValidate(indexData)
    +    collectAndValidate(shortData)
    +    collectAndValidate(intData)
    +    collectAndValidate(longData)
    +    collectAndValidate(floatData)
    +    collectAndValidate(doubleData)
    +  }
    +
    +  test("mixed numeric type conversion") {
    +    collectAndValidate(mixedNumericData)
    +  }
    +
    +  test("boolean type conversion") {
    +    collectAndValidate(boolData)
    +  }
    +
    +  test("string type conversion") {
    +    collectAndValidate(stringData)
    +  }
    +
    +  test("byte type conversion") {
    +    collectAndValidate(byteData)
    +  }
    +
    +  ignore("timestamp conversion") {
    +    collectAndValidate(timestampData)
    +  }
    +
    +  // TODO: Not currently supported in Arrow JSON reader
    +  ignore("date conversion") {
    +    // collectAndValidate(dateTimeData)
    +  }
    +
    +  // TODO: Not currently supported in Arrow JSON reader
    +  ignore("binary type conversion") {
    +    // collectAndValidate(binaryData)
    +  }
    +
    +  test("floating-point NaN") {
    +    collectAndValidate(floatNaNData)
    +  }
    +
    +  test("partitioned DataFrame") {
    +    val converter = new ArrowConverters
    +    val schema = testData2.schema
    +    val arrowPayload = collectAsArrow(testData2, Some(converter))
    +    val arrowBatches = arrowPayload.toArray
    +    // NOTE: testData2 should have 2 partitions -> 2 arrow batches in payload
    +    assert(arrowBatches.length === 2)
    +    val pl1 = new ArrowStaticPayload(arrowBatches(0))
    +    val pl2 = new ArrowStaticPayload(arrowBatches(1))
    +    // Generate JSON files
    +    val a = List[Int](1, 1, 2, 2, 3, 3)
    +    val b = List[Int](1, 2, 1, 2, 1, 2)
    +    val fields = Seq(new IntegerType("a", is_signed = true, 32, nullable = false),
    +      new IntegerType("b", is_signed = true, 32, nullable = false))
    +    def getBatch(x: Seq[Int], y: Seq[Int]): JSONRecordBatch = {
    +      val columns = Seq(new PrimitiveColumn("a", x.length, x.map(_ => true), x),
    +        new PrimitiveColumn("b", y.length, y.map(_ => true), y))
    +      new JSONRecordBatch(x.length, columns)
    +    }
    +    val json1 = new JSONFile(new JSONSchema(fields), Seq(getBatch(a.take(3), b.take(3))))
    +    val json2 = new JSONFile(new JSONSchema(fields), Seq(getBatch(a.takeRight(3), b.takeRight(3))))
    +    val tempFile1 = new File(tempDataPath, "testData2-ints-part1.json")
    +    val tempFile2 = new File(tempDataPath, "testData2-ints-part2.json")
    +    json1.write(tempFile1)
    +    json2.write(tempFile2)
    +    validateConversion(schema, pl1, tempFile1, Some(converter))
    +    validateConversion(schema, pl2, tempFile2, Some(converter))
    +  }
    +
    +  test("empty frame collect") {
    +    val arrowPayload = collectAsArrow(spark.emptyDataFrame)
    +    assert(arrowPayload.isEmpty)
    +  }
    +
    +  test("empty partition collect") {
    +    val emptyPart = spark.sparkContext.parallelize(Seq(1), 2).toDF("i")
    +    val arrowPayload = collectAsArrow(emptyPart)
    +    val arrowBatches = arrowPayload.toArray
    +    assert(arrowBatches.length === 2)
    +    assert(arrowBatches.count(_.getLength == 0) === 1)
    +    assert(arrowBatches.count(_.getLength == 1) === 1)
    +  }
    +
    +  test("unsupported types") {
    +    def runUnsupported(block: => Unit): Unit = {
    +      val msg = intercept[SparkException] {
    +        block
    +      }
    +      assert(msg.getMessage.contains("Unsupported data type"))
    +      assert(msg.getCause.getClass === classOf[UnsupportedOperationException])
    +    }
    +
    +    runUnsupported { collectAsArrow(decimalData) }
    +    runUnsupported { collectAsArrow(arrayData.toDF()) }
    +    runUnsupported { collectAsArrow(mapData.toDF()) }
    +    runUnsupported { collectAsArrow(complexData) }
    +  }
    +
    +  test("test Arrow Validator") {
    +    val sdata = shortData
    +    val idata = intData
    +
    +    // Different schema
    +    intercept[IllegalArgumentException] {
    +      collectAndValidate(DataTuple(sdata.df, idata.json, idata.file))
    +    }
    +
    +    // Different values
    +    intercept[IllegalArgumentException] {
    +      collectAndValidate(DataTuple(idata.df.sort($"a_i".desc), idata.json, idata.file))
    +    }
    +  }
    +
    +  /** Test that a converted DataFrame to Arrow record batch equals batch read from JSON file */
    +  private def collectAndValidate(data: DataTuple): Unit = {
    +    val converter = new ArrowConverters
    +    // NOTE: coalesce to single partition because can only load 1 batch in validator
    +    val arrowPayload = collectAsArrow(data.df.coalesce(1), Some(converter))
    +    val tempFile = new File(tempDataPath, data.file)
    +    data.json.write(tempFile)
    +    validateConversion(data.df.schema, arrowPayload, tempFile, Some(converter))
    +  }
    +
    +  private def validateConversion(sparkSchema: StructType,
    +                                 arrowPayload: ArrowPayload,
    +                                 jsonFile: File,
    +                                 converterOpt: Option[ArrowConverters] = None): Unit = {
    +    val converter = converterOpt.getOrElse(new ArrowConverters)
    +    val jsonReader = new JsonFileReader(jsonFile, converter.allocator)
    +
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(sparkSchema)
    +    val jsonSchema = jsonReader.start()
    +    Validator.compareSchemas(arrowSchema, jsonSchema)
    +
    +    val arrowRoot = new VectorSchemaRoot(arrowSchema, converter.allocator)
    +    val vectorLoader = new VectorLoader(arrowRoot)
    +    arrowPayload.foreach(vectorLoader.load)
    +    val jsonRoot = jsonReader.read()
    +    Validator.compareVectorSchemaRoot(arrowRoot, jsonRoot)
    +  }
    +
    +  // Create Spark DataFrame and matching Arrow JSON at same time for validation
    +  private case class DataTuple(df: DataFrame, json: JSONFile, file: String)
    +
    +  private def indexData: DataTuple = {
    +    val data = List[Int](1, 2, 3, 4, 5, 6)
    +    val fields = Seq(new IntegerType("i", is_signed = true, 32, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("i", data.length, data.map(_ => true), data))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("i"), new JSONFile(schema, Seq(batch)), "indexData-ints.json")
    +  }
    +
    +  private def shortData: DataTuple = {
    +    val a_s = List[Short](1, -1, 2, -2, 32767, -32768)
    +    val b_s = List[Option[Short]](Some(1), None, None, Some(-2), None, Some(-32768))
    +    val fields = Seq(new IntegerType("a_s", is_signed = true, 16, nullable = false),
    +      new IntegerType("b_s", is_signed = true, 16, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val b_s_values = b_s.map(_.map(_.toInt).getOrElse(0))
    +    val columns = Seq(
    +      new PrimitiveColumn("a_s", a_s.length, a_s.map(_ => true), a_s.map(_.toInt)),
    +      new PrimitiveColumn("b_s", b_s.length, b_s.map(_.isDefined), b_s_values))
    +    val batch = new JSONRecordBatch(a_s.length, columns)
    +    val df = a_s.zip(b_s).toDF("a_s", "b_s")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-16bit.json")
    +  }
    +
    +  private def intData: DataTuple = {
    +    val a_i = List[Int](1, -1, 2, -2, 2147483647, -2147483648)
    +    val b_i = List[Option[Int]](Some(1), None, None, Some(-2), None, Some(-2147483648))
    +    val fields = Seq(new IntegerType("a_i", is_signed = true, 32, nullable = false),
    +      new IntegerType("b_i", is_signed = true, 32, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_i", a_i.length, a_i.map(_ => true), a_i),
    +      new PrimitiveColumn("b_i", b_i.length, b_i.map(_.isDefined), b_i.map(_.getOrElse(0))))
    +    val batch = new JSONRecordBatch(a_i.length, columns)
    +    val df = a_i.zip(b_i).toDF("a_i", "b_i")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-32bit.json")
    +  }
    +
    +  private def longData: DataTuple = {
    +    val a_l = List[Long](1, -1, 2, -2, 9223372036854775807L, -9223372036854775808L)
    +    val b_l = List[Option[Long]](Some(1), None, None, Some(-2), None, Some(-9223372036854775808L))
    +    val fields = Seq(new IntegerType("a_l", is_signed = true, 64, nullable = false),
    +      new IntegerType("b_l", is_signed = true, 64, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_l", a_l.length, a_l.map(_ => true), a_l),
    +      new PrimitiveColumn("b_l", b_l.length, b_l.map(_.isDefined), b_l.map(_.getOrElse(0L))))
    +    val batch = new JSONRecordBatch(a_l.length, columns)
    +    val df = a_l.zip(b_l).toDF("a_l", "b_l")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-64bit.json")
    +  }
    +
    +  private def floatData: DataTuple = {
    +    val a_f = List(1.0f, 2.0f, 0.01f, 200.0f, 0.0001f, 20000.0f)
    +    val b_f = List[Option[Float]](Some(1.1f), None, None, Some(2.2f), None, Some(3.3f))
    +    val fields = Seq(new FloatingPointType("a_f", 32, nullable = false),
    +      new FloatingPointType("b_f", 32, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_f", a_f.length, a_f.map(_ => true), a_f),
    +      new PrimitiveColumn("b_f", b_f.length, b_f.map(_.isDefined), b_f.map(_.getOrElse(0.0f))))
    +    val batch = new JSONRecordBatch(a_f.length, columns)
    +    val df = a_f.zip(b_f).toDF("a_f", "b_f")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "floating_point-single_precision.json")
    +  }
    +
    +  private def doubleData: DataTuple = {
    +    val a_d = List(1.0, 2.0, 0.01, 200.0, 0.0001, 20000.0)
    +    val b_d = List[Option[Double]](Some(1.1), None, None, Some(2.2), None, Some(3.3))
    +    val fields = Seq(new FloatingPointType("a_d", 64, nullable = false),
    +      new FloatingPointType("b_d", 64, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_d", a_d.length, a_d.map(_ => true), a_d),
    +      new PrimitiveColumn("b_d", b_d.length, b_d.map(_.isDefined), b_d.map(_.getOrElse(0.0))))
    +    val batch = new JSONRecordBatch(a_d.length, columns)
    +    val df = a_d.zip(b_d).toDF("a_d", "b_d")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "floating_point-double_precision.json")
    +  }
    +
    +  private def mixedNumericData: DataTuple = {
    +    val data = List(1, 2, 3, 4, 5, 6)
    +    val fields = Seq(new IntegerType("a", is_signed = true, 16, nullable = false),
    +      new FloatingPointType("b", 32, nullable = false),
    +      new IntegerType("c", is_signed = true, 32, nullable = false),
    +      new FloatingPointType("d", 64, nullable = false),
    +      new IntegerType("e", is_signed = true, 64, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a", data.length, data.map(_ => true), data),
    +      new PrimitiveColumn("b", data.length, data.map(_ => true), data.map(_.toFloat)),
    +      new PrimitiveColumn("c", data.length, data.map(_ => true), data),
    +      new PrimitiveColumn("d", data.length, data.map(_ => true), data.map(_.toDouble)),
    +      new PrimitiveColumn("e", data.length, data.map(_ => true), data)
    +    )
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    val data_tuples = for (d <- data) yield {
    +      (d.toShort, d.toFloat, d.toInt, d.toDouble, d.toLong)
    +    }
    +    val df = data_tuples.toDF("a", "b", "c", "d", "e")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "mixed_numeric_types.json")
    +  }
    +
    +  private def boolData: DataTuple = {
    +    val data = Seq(true, true, false, true)
    +    val fields = Seq(new BooleanType("a_bool", nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_bool", data.length, data.map(_ => true), data))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("a_bool"), new JSONFile(schema, Seq(batch)), "boolData.json")
    +  }
    +
    +  private def stringData: DataTuple = {
    +    val upperCase = Seq("A", "B", "C")
    +    val lowerCase = Seq("a", "b", "c")
    +    val nullStr = Seq("ab", "CDE", null)
    +    val fields = Seq(new StringType("upper_case", nullable = true),
    +      new StringType("lower_case", nullable = true),
    +      new StringType("null_str", nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new StringColumn("upper_case", upperCase.length, upperCase.map(_ => true), upperCase),
    +      new StringColumn("lower_case", lowerCase.length, lowerCase.map(_ => true), lowerCase),
    +      new StringColumn("null_str", nullStr.length, nullStr.map(_ != null),
    +        nullStr.map { s => if (s == null) "" else s}
    +      ))
    +    val batch = new JSONRecordBatch(upperCase.length, columns)
    +    val df = (upperCase, lowerCase, nullStr).zipped.toList
    +      .toDF("upper_case", "lower_case", "null_str")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "stringData.json")
    +  }
    +
    +  private def byteData: DataTuple = {
    +    val data = List[Byte](1.toByte, (-1).toByte, 64.toByte, Byte.MaxValue)
    +    val fields = Seq(new IntegerType("a_byte", is_signed = true, 8, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_byte", data.length, data.map(_ => true), data.map(_.toInt)))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("a_byte"), new JSONFile(schema, Seq(batch)), "byteData.json")
    +  }
    +
    +  private def floatNaNData: DataTuple = {
    +    val fnan = Seq(1.2F, Float.NaN)
    +    val dnan = Seq(Double.NaN, 1.2)
    +    val fields = Seq(new FloatingPointType("NaN_f", 32, nullable = false),
    +      new FloatingPointType("NaN_d", 64, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("NaN_f", fnan.length, fnan.map(_ => true), fnan),
    +      new PrimitiveColumn("NaN_d", dnan.length, dnan.map(_ => true), dnan))
    +    val batch = new JSONRecordBatch(fnan.length, columns)
    +    val df = fnan.zip(dnan).toDF("NaN_f", "NaN_d")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "nanData-floating_point.json")
    +  }
    +
    +  private def timestampData: DataTuple = {
    +    val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z", Locale.US)
    +    val ts1 = new Timestamp(sdf.parse("2013-04-08 01:10:15.567 UTC").getTime)
    +    val ts2 = new Timestamp(sdf.parse("2013-04-08 13:10:10.789 UTC").getTime)
    +    val data = Seq(ts1, ts2)
    +    val schema = new JSONSchema(Seq(new TimestampType("c_timestamp")))
    +    val columns = Seq(
    +      new PrimitiveColumn("c_timestamp", data.length, data.map(_ => true), data.map(_.getTime)))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("c_timestamp"), new JSONFile(schema, Seq(batch)), "timestampData.json")
    +  }
    +
    +  private def dateData: DataTuple = {
    +    val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z", Locale.US)
    +    val d1 = new Date(sdf.parse("2015-04-08 13:10:15.000 UTC").getTime)
    +    val d2 = new Date(sdf.parse("2015-04-08 13:10:15.000 UTC").getTime)
    +    val ts1 = new Timestamp(sdf.parse("2013-04-08 01:10:15.567 UTC").getTime)
    +    val ts2 = new Timestamp(sdf.parse("2013-04-08 13:10:10.789 UTC").getTime)
    +    val df = Seq((d1, sdf.format(d1), ts1), (d2, sdf.format(d2), ts2))
    +      .toDF("a_date", "b_string", "c_timestamp")
    +    val jsonFile = new JSONFile(new JSONSchema(Seq.empty[DataType]), Seq.empty[JSONRecordBatch])
    +    DataTuple(df, jsonFile, "dateData.json")
    +  }
    +
    +  /**
    +   * Arrow JSON Format Data Generation
    +   * Referenced from https://github.com/apache/arrow/blob/master/integration/integration_test.py
    +   * TODO: Look into using JSON generation from parquet-vector.jar
    +   */
    +
    +  private abstract class DataType(name: String, nullable: Boolean) {
    --- End diff --
    
    I thought the easiest and most compact strategy for testing was to 1) define common data, 2) write the data as JSON, 3) make a DataFrame from data and convert to ArrowRecordBatch, 4) send batch and JSON file to Arrow validator where it can be checked.
    
    I think the JSON files are too big to inline and would create a huge file if have them as strings.  I could try this out for one of the test cases if you like and we can see how it turns out?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    The 0.2 Maven artifacts have been posted. I'll try to update the conda-forge packages this week -- if anyone can help with conda-forge maintenance that would be a big help.
    
    Thanks!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122280237
  
    --- Diff: python/pyspark/serializers.py ---
    @@ -182,6 +182,23 @@ def loads(self, obj):
             raise NotImplementedError
     
     
    +class ArrowSerializer(FramedSerializer):
    +    """
    +    Serializes an Arrow stream.
    +    """
    +
    +    def dumps(self, obj):
    +        raise NotImplementedError
    +
    +    def loads(self, obj):
    +        import pyarrow as pa
    +        reader = pa.RecordBatchFileReader(pa.BufferReader(obj))
    +        return reader.read_all()
    --- End diff --
    
    This will read all batches in a framed byte array from a stream and return.  The stream can have multiple framed byte arrays, so it repeats until end of stream.  
    
    How many batches this reads depends on how it serialized.  When calling `toPandas()`, it collects all batches and then serializes each one to Python as an iterator.  So in this case, `reader.read_all()` will read 1 batch at a time.  


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Would you mind opening a PR for this? I guess updating it would probably be done by a followup but this one sounds rather a semi-hotfix. If both timeout and adding chennel are all we need, I can propose the change now instead if you happen to be busy for this.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121202886
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as an Array[Byte].
    +   */
    +  def toByteArray: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload. Limit ArrowRecordBatch size in ArrowPayload
    +   * by setting maxRecordsPerBatch or use 0 to fully consume rowIter.
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      maxRecordsPerBatch: Int): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator, maxRecordsPerBatch)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch, stopping when rowIter is consumed
    +   * or the number of records in the batch equals maxRecordsInBatch.  If maxRecordsPerBatch is 0,
    +   * then rowIter will be fully consumed.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator,
    +      maxRecordsPerBatch: Int = 0): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(field.dataType, ordinal, allocator).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    var recordsInBatch = 0
    +    while (rowIter.hasNext && (maxRecordsPerBatch <= 0 || recordsInBatch < maxRecordsPerBatch)) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +      recordsInBatch += 1
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert an ArrowRecordBatch to a byte array and close batch to release resources. Once closed,
    +   * the batch can no longer be used.
    +   */
    +  private[arrow] def batchToByteArray(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val root = VectorSchemaRoot.create(arrowSchema, allocator)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowFileWriter(root, null, Channels.newChannel(out))
    +
    +    // Write a batch to byte stream, ensure the batch, allocator and writer are closed
    +    Utils.tryWithSafeFinally {
    +      val loader = new VectorLoader(root)
    +      loader.load(batch)
    +      writer.writeBatch()  // writeBatch can throw IOException
    +    } {
    +      batch.close()
    +      root.close()
    +      writer.close()
    +    }
    +    out.toByteArray
    +  }
    +
    +  /**
    +   * Convert a byte array to an ArrowRecordBatch.
    +   */
    +  private[arrow] def byteArrayToBatch(
    +      batchBytes: Array[Byte],
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +    val in = new ByteArrayReadableSeekableByteChannel(batchBytes)
    +    val reader = new ArrowFileReader(in, allocator)
    +
    +    // Read a batch from a byte stream, ensure the reader is closed
    +    Utils.tryWithSafeFinally {
    +      val root = reader.getVectorSchemaRoot  // throws IOException
    +      val unloader = new VectorUnloader(root)
    +      reader.loadNextBatch()  // throws IOException
    +      unloader.getRecordBatch
    +    } {
    +      reader.close()
    +    }
    +  }
    +}
    +
    +/**
    + * Interface for writing InternalRows to Arrow Buffers.
    + */
    +private[arrow] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[arrow] abstract class PrimitiveColumnWriter(val ordinal: Int)
    +  extends ColumnWriter {
    +
    +  def getFieldType(dtype: ArrowType): FieldType = FieldType.nullable(dtype)
    +
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[arrow] class BooleanColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, if (row.getBoolean(ordinal)) 1 else 0 )
    +}
    +
    +private[arrow] class ShortColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", getFieldType(dtype: ArrowType), allocator)
    +  override val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[arrow] class IntegerColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[arrow] class LongColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[arrow] class FloatColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[arrow] class DoubleColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[arrow] class ByteColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[arrow] class UTF8StringColumnWriter(
    +    dtype: ArrowType,
    +    ordinal: Int,
    +    allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    val bytes = row.getUTF8String(ordinal).getBytes
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[arrow] class BinaryColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("BinaryValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    val bytes = row.getBinary(ordinal)
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[arrow] class DateColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableDateDayVector
    +    = new NullableDateDayVector("DateValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableDateDayVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    valueMutator.setSafe(count, row.getInt(ordinal))
    +  }
    +}
    +
    +private[arrow] class TimeStampColumnWriter(
    +    dtype: ArrowType,
    +    ordinal: Int,
    +    allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableTimeStampMicroVector
    +    = new NullableTimeStampMicroVector("TimeStampValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableTimeStampMicroVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    valueMutator.setSafe(count, row.getLong(ordinal))
    +  }
    +}
    +
    +private[arrow] object ColumnWriter {
    +
    +  /**
    +   * Create an Arrow ColumnWriter given the type and ordinal of row.
    +   */
    +  def apply(dataType: DataType, ordinal: Int, allocator: BufferAllocator): ColumnWriter = {
    +    val dtype = ArrowConverters.sparkTypeToArrowType(dataType)
    +    dataType match {
    +      case BooleanType => new BooleanColumnWriter(dtype, ordinal, allocator)
    +      case ShortType => new ShortColumnWriter(dtype, ordinal, allocator)
    +      case IntegerType => new IntegerColumnWriter(dtype, ordinal, allocator)
    +      case LongType => new LongColumnWriter(dtype, ordinal, allocator)
    +      case FloatType => new FloatColumnWriter(dtype, ordinal, allocator)
    +      case DoubleType => new DoubleColumnWriter(dtype, ordinal, allocator)
    +      case ByteType => new ByteColumnWriter(dtype, ordinal, allocator)
    +      case StringType => new UTF8StringColumnWriter(dtype, ordinal, allocator)
    +      case BinaryType => new BinaryColumnWriter(dtype, ordinal, allocator)
    +      case DateType => new DateColumnWriter(dtype, ordinal, allocator)
    +      case TimestampType => new TimeStampColumnWriter(dtype, ordinal, allocator)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    --- End diff --
    
    do you have a plan to support complex types? what will the API look like?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #73366 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/73366/testReport)** for PR 15821 at commit [`9c8ea63`](https://github.com/apache/spark/commit/9c8ea63ccec4ceb9dd40834bca530a6265385579).
     * This patch **fails PySpark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    ```
    (py3k)-bash-4.1$ pip install pyarrow
    Requirement already satisfied: pyarrow in /home/anaconda/envs/py3k/lib/python3.4/site-packages
    Requirement already satisfied: six>=1.0.0 in /home/anaconda/envs/py3k/lib/python3.4/site-packages (from pyarrow)
    Requirement already satisfied: numpy>=1.9 in /home/anaconda/envs/py3k/lib/python3.4/site-packages (from pyarrow)
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r106042486
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1610,8 +1623,14 @@ def toPandas(self):
             0    2  Alice
             1    5    Bob
             """
    -        import pandas as pd
    -        return pd.DataFrame.from_records(self.collect(), columns=self.columns)
    +        if useArrow:
    +            from pyarrow.table import concat_tables
    --- End diff --
    
    re-ping @BryanCutler 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Sorry I didn't know there is a PR fixing the issue, and I already reverted it. Please cherry-pick this commit in the new PR and apply the pip fixing. Sorry for the trouble.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler , is Timestamp and Date type supported now with Arrow 0.3?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122326641
  
    --- Diff: dev/run-pip-tests ---
    @@ -120,6 +122,10 @@ for python in "${PYTHON_EXECS[@]}"; do
         python "$FWDIR"/dev/pip-sanity-check.py
         echo "Run the tests for context.py"
         python "$FWDIR"/python/pyspark/context.py
    +    if [ -n "$TEST_PYARROW" ]; then
    +      echo "Run tests for pyarrow"
    +      SPARK_TESTING=1 "$FWDIR"/bin/pyspark pyspark.sql.tests ArrowTests
    --- End diff --
    
    Yeah, this will definitely be removed at some point.  I was working with @holdenk to set this up as a temporary way to get the Python Arrow tests to run.  I'll look into using the pip packages and see if that can be used instead of this.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122282802
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -2473,6 +2482,69 @@ def range_frame_match():
     
             importlib.reload(window)
     
    +
    +@unittest.skipIf(not _have_arrow, "Arrow not installed")
    +class ArrowTests(ReusedPySparkTestCase):
    +
    +    @classmethod
    +    def setUpClass(cls):
    +        ReusedPySparkTestCase.setUpClass()
    +        cls.spark = SparkSession(cls.sc)
    +        cls.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        cls.schema = StructType([
    +            StructField("1_str_t", StringType(), True),
    +            StructField("2_int_t", IntegerType(), True),
    +            StructField("3_long_t", LongType(), True),
    +            StructField("4_float_t", FloatType(), True),
    +            StructField("5_double_t", DoubleType(), True)])
    +        cls.data = [("a", 1, 10, 0.2, 2.0),
    +                    ("b", 2, 20, 0.4, 4.0),
    +                    ("c", 3, 30, 0.8, 6.0)]
    +
    +    def assertFramesEqual(self, df_with_arrow, df_without):
    +        msg = ("DataFrame from Arrow is not equal" +
    +               ("\n\nWith Arrow:\n%s\n%s" % (df_with_arrow, df_with_arrow.dtypes)) +
    +               ("\n\nWithout:\n%s\n%s" % (df_without, df_without.dtypes)))
    +        self.assertTrue(df_without.equals(df_with_arrow), msg=msg)
    +
    +    def test_unsupported_datatype(self):
    +        schema = StructType([StructField("array", ArrayType(IntegerType(), False), True)])
    +        df = self.spark.createDataFrame([([1, 2, 3],)], schema=schema)
    +        with QuietTest(self.sc):
    +            self.assertRaises(Exception, lambda: df.toPandas())
    +
    +    def test_null_conversion(self):
    +        df_null = self.spark.createDataFrame([tuple([None for _ in range(len(self.data[0]))])] +
    +                                             self.data)
    +        pdf = df_null.toPandas()
    +        null_counts = pdf.isnull().sum().tolist()
    +        self.assertTrue(all([c == 1 for c in null_counts]))
    +
    +    def test_toPandas_arrow_toggle(self):
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        # NOTE - toPandas() without pyarrow will infer standard python data types
    +        df_sel = df.select("1_str_t", "3_long_t", "5_double_t")
    +        self.spark.conf.set("spark.sql.execution.arrow.enable", "false")
    +        pdf = df_sel.toPandas()
    +        self.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        pdf_arrow = df_sel.toPandas()
    +        self.assertFramesEqual(pdf_arrow, pdf)
    +
    +    def test_pandas_round_trip(self):
    +        import pandas as pd
    +        import numpy as np
    +        data_dict = {}
    +        for j, name in enumerate(self.schema.names):
    +            data_dict[name] = [self.data[i][j] for i in range(len(self.data))]
    +        # need to convert these to numpy types first
    +        data_dict["2_int_t"] = np.int32(data_dict["2_int_t"])
    +        data_dict["4_float_t"] = np.float32(data_dict["4_float_t"])
    +        pdf = pd.DataFrame(data=data_dict)
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        pdf_arrow = df.toPandas()
    --- End diff --
    
    that's done in the `setUpClass` so it's already enabled for all tests.  There is a test where it's toggled, off then back on though to test that behavior.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r123122759
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,429 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark and served to a Python process.
    + */
    +private[sql] class ArrowPayload private[arrow] (payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as a type that can be served to Python.
    +   */
    +  def asPythonSerializable: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowPayload {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def apply(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowPayload = {
    +    new ArrowPayload(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    --- End diff --
    
    I was working on it but things were getting a little messy because of differences with time-zone usage in Spark (there have been some recent discussions on the mailing list about it).  So after discussing with @holdenk , we thought it would be best to keep this PR simple with support for primitive types and work on timestamps on a followup.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/72180/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/71950/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r89198929
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1508,7 +1518,7 @@ def toDF(self, *cols):
             return DataFrame(jdf, self.sql_ctx)
     
         @since(1.3)
    -    def toPandas(self):
    +    def toPandas(self, useArrow=True):
    --- End diff --
    
    Would it maybe make more sense to default this to false or have more thorough checking that the dataframe being written with arrow is supported? At least initially the set of supported dataframes might be rather small.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #78265 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/78265/testReport)** for PR 15821 at commit [`8bff966`](https://github.com/apache/spark/commit/8bff966b637ee35a8c1cb051c7eb700f017e4d71).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    BTW should we need to update `setup.py` too?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #76754 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/76754/testReport)** for PR 15821 at commit [`934c147`](https://github.com/apache/spark/commit/934c147cf41752d382ee6ae304ed18ca5bed73e4).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r103047241
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -391,6 +392,15 @@ def collect(self):
             return list(_load_from_socket(port, BatchedSerializer(PickleSerializer())))
     
         @ignore_unicode_prefix
    +    @since(2.2)
    +    def collectAsArrow(self):
    --- End diff --
    
    For now we might want to mark this as experimental & mention supported data types.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r108744852
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2828,4 +2839,16 @@ class Dataset[T] private[sql](
           Dataset(sparkSession, logicalPlan)
         }
       }
    +
    +  /** Convert to an RDD of ArrowPayload byte arrays */
    +  private[sql] def toArrowPayloadBytes(): RDD[Array[Byte]] = {
    +    val schema_captured = this.schema
    +    queryExecution.toRdd.mapPartitionsInternal { iter =>
    +      val converter = new ArrowConverters
    +      val payload = converter.interalRowIterToPayload(iter, schema_captured)
    +      val payloadBytes = ArrowConverters.payloadToByteArray(payload, schema_captured)
    --- End diff --
    
    Yes, that is a good idea.  It does support having multiple payloads so that would not be too difficult to change, but the only question is how big to make the groups?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks for the review @julienledem!  I'll work on an update.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by julienledem <gi...@git.apache.org>.
Github user julienledem commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105321731
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    --- End diff --
    
    if we create an allocator we should have a way to close it in the end.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Here are some rough benchmarks done locally on machine with 16GB mem and 8 cores, using Spark config defaults and taken from 50 trials of calling `toPandas()` with and without Arrow enabled:
    
    ## 1mm Longs
     _ | With Arrow | Without Arrow
    --|------------|-------------------
    count  |   50.000000 |    50.000000
    mean   |   0.190573 |      2.576587
    std   |    0.078450 |       0.114455
    min   |    0.139911 |       2.259916
    25%   |    0.148212 |        2.516289
    50%   |    0.163769 |        2.555433
    75%   |    0.184402 |        2.631316
    max    |   0.518090 |       2.946415
    
    **13.52x speedup** on average
    
    ## 1mm Doubles
     _ | With Arrow | Without Arrow
    --|------------|-------------------
    count  |  50.000000 | 50.000000
    mean   |   0.259145 | 2.090295
    std  |     0.069620 | 0.123091
    min  |     0.196666 | 1.998588
    25%  |     0.209051 | 2.015083
    50%   |    0.230751 | 2.032701
    75%    |   0.270519 | 2.122219
    max    |   0.439556 | 2.485232
    
    **8.07x speedup** on average
    
    Script to generate these can be found [here](https://issues.apache.org/jira/secure/attachment/12849193/benchmark.py)
    



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler -- i'm ok w/holding out to discuss this in more detail tomorrow.  in the meantime, i'll look over this PR and build failures and get myself up to speed w/what's going on.
    



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Very nice to see the improved wall clock times. I have been busy engineering the pipeline between the byte stream from Spark and the resulting DataFrame -- the only major thing still left on the table that might help is converting in C++ to pandas.Categorical rather than returning a dense array of strings. 
    
    I'll review this patch in more detail when I can
    
    I do a bit of performance analysis (esp. on the Python side) and flesh out some of the architectural next-steps (e.g. what @leifwalsh has described) in advance of Spark Summit in a couple weeks. Parallelizing the record batch conversion and streaming it to Python would be another significant perf win. Having these tools should also be helpful for speeding up UDF evaluation


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #74118 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/74118/testReport)** for PR 15821 at commit [`44ca3ff`](https://github.com/apache/spark/commit/44ca3ffc37711225a64fd57dca2ba747debf8c3d).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112375496
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +
    +    // Iterate over payload batches to write each one, ensure all batches get closed
    +    var batch: ArrowRecordBatch = null
    +    Utils.tryWithSafeFinallyAndFailureCallbacks {
    +      while (payload.hasNext) {
    +        batch = payload.next()
    +        writer.writeRecordBatch(batch)
    +        batch.close()
    +      }
    +    }(catchBlock = {
    +      Option(batch).foreach(_.close())
    +      payload.foreach(_.close())
    +    }, finallyBlock = writer.close())
    +
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    --- End diff --
    
    isn't the implementation of setNull the same across all implementations?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    thanks, merging to master!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122305824
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/arrow/ArrowConvertersSuite.scala ---
    @@ -0,0 +1,1218 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.File
    +import java.nio.charset.StandardCharsets
    +import java.sql.{Date, Timestamp}
    +import java.text.SimpleDateFormat
    +import java.util.Locale
    +
    +import com.google.common.io.Files
    +import org.apache.arrow.memory.RootAllocator
    +import org.apache.arrow.vector.{VectorLoader, VectorSchemaRoot}
    +import org.apache.arrow.vector.file.json.JsonFileReader
    +import org.apache.arrow.vector.util.Validator
    +import org.scalatest.BeforeAndAfterAll
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.{DataFrame, Row}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{BinaryType, StructField, StructType}
    +import org.apache.spark.util.Utils
    +
    +
    +class ArrowConvertersSuite extends SharedSQLContext with BeforeAndAfterAll {
    +  import testImplicits._
    +
    +  private var tempDataPath: String = _
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    tempDataPath = Utils.createTempDir(namePrefix = "arrow").getAbsolutePath
    +  }
    +
    +  test("collect to arrow record batch") {
    +    val indexData = (1 to 6).toDF("i")
    +    val arrowPayloads = indexData.toArrowPayload.collect()
    +    assert(arrowPayloads.nonEmpty)
    +    assert(arrowPayloads.length == indexData.rdd.getNumPartitions)
    +    val allocator = new RootAllocator(Long.MaxValue)
    +    val arrowRecordBatches = arrowPayloads.map(_.loadBatch(allocator))
    +    val rowCount = arrowRecordBatches.map(_.getLength).sum
    +    assert(rowCount === indexData.count())
    +    arrowRecordBatches.foreach(batch => assert(batch.getNodes.size() > 0))
    +    arrowRecordBatches.foreach(_.close())
    +    allocator.close()
    +  }
    +
    +  test("short conversion") {
    +    val json =
    +      s"""
    +         |{
    +         |  "schema" : {
    +         |    "fields" : [ {
    +         |      "name" : "a_s",
    +         |      "type" : {
    +         |        "name" : "int",
    +         |        "isSigned" : true,
    +         |        "bitWidth" : 16
    +         |      },
    +         |      "nullable" : false,
    +         |      "children" : [ ],
    +         |      "typeLayout" : {
    +         |        "vectors" : [ {
    +         |          "type" : "VALIDITY",
    +         |          "typeBitWidth" : 1
    +         |        }, {
    +         |          "type" : "DATA",
    +         |          "typeBitWidth" : 16
    +         |        } ]
    +         |      }
    +         |    }, {
    +         |      "name" : "b_s",
    +         |      "type" : {
    +         |        "name" : "int",
    +         |        "isSigned" : true,
    +         |        "bitWidth" : 16
    +         |      },
    +         |      "nullable" : true,
    +         |      "children" : [ ],
    +         |      "typeLayout" : {
    +         |        "vectors" : [ {
    +         |          "type" : "VALIDITY",
    +         |          "typeBitWidth" : 1
    +         |        }, {
    +         |          "type" : "DATA",
    +         |          "typeBitWidth" : 16
    +         |        } ]
    +         |      }
    +         |    } ]
    +         |  },
    +         |  "batches" : [ {
    +         |    "count" : 6,
    +         |    "columns" : [ {
    +         |      "name" : "a_s",
    +         |      "count" : 6,
    +         |      "VALIDITY" : [ 1, 1, 1, 1, 1, 1 ],
    +         |      "DATA" : [ 1, -1, 2, -2, 32767, -32768 ]
    +         |    }, {
    +         |      "name" : "b_s",
    +         |      "count" : 6,
    +         |      "VALIDITY" : [ 1, 0, 0, 1, 0, 1 ],
    +         |      "DATA" : [ 1, 0, 0, -2, 0, -32768 ]
    +         |    } ]
    +         |  } ]
    +         |}
    +       """.stripMargin
    +
    +    val a_s = List[Short](1, -1, 2, -2, 32767, -32768)
    +    val b_s = List[Option[Short]](Some(1), None, None, Some(-2), None, Some(-32768))
    +    val df = a_s.zip(b_s).toDF("a_s", "b_s")
    --- End diff --
    
    Not sure I follow, this will create a DataFrame with a MapType right?  I want 2 columns, 1 short and 1 nullable short.  I have the columns defined separately so it's easier to visually compare with the JSON.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by leifwalsh <gi...@git.apache.org>.
Github user leifwalsh commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121922149
  
    --- Diff: dev/run-pip-tests ---
    @@ -120,6 +122,10 @@ for python in "${PYTHON_EXECS[@]}"; do
         python "$FWDIR"/dev/pip-sanity-check.py
         echo "Run the tests for context.py"
         python "$FWDIR"/python/pyspark/context.py
    +    if [ -n "$TEST_PYARROW" ]; then
    +      echo "Run tests for pyarrow"
    +      SPARK_TESTING=1 "$FWDIR"/bin/pyspark pyspark.sql.tests ArrowTests
    --- End diff --
    
    pyarrow has pip packages now, does that help? @BryanCutler I can't read your comment and understand why they required a conda env but maybe that's it? 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r108835232
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2747,6 +2747,17 @@ class Dataset[T] private[sql](
         }
       }
     
    +  /**
    +   * Collect a Dataset as ArrowPayload byte arrays and serve to PySpark.
    +   */
    +  private[sql] def collectAsArrowToPython(): Int = {
    +    val payloadRdd = toArrowPayloadBytes()
    +    val payloadByteArrays = payloadRdd.collect()
    --- End diff --
    
    @BryanCutler Btw, it is not for performance gain I think. `toLocalIteratorAndServe` can avoid collect all data at once into the driver. So it may be good for the memory usage on the driver side.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    ## Future Work
    
    The support of all Spark data types to include complex types will be a quick follow up to ensure full compatibility.  With the added ability to convert a Dataset on the executor JVM to an Arrow payload, it allows for the possibility to use the same routines in Python UDF exchange, which is currently a huge bottleneck and a pain-point with users.  Also, the transferring of data to R could take advatage of this to see similar speedups over current serialization.  



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Hey @BryanCutler can you look at the test failure?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    the test currently fails with the stack trace
    ```
    Traceback (most recent call last):
      File "/home/bryan/git/spark/python/pyspark/sql/tests.py", line 2000, in test_arrow_round_trip
        pdf_arrow = df.toPandas(useArrow=True)
      File "/home/bryan/git/spark/python/pyspark/sql/dataframe.py", line 1535, in toPandas
        return self.collectAsArrow().to_pandas()
      File "/home/bryan/git/spark/python/pyspark/sql/dataframe.py", line 353, in collectAsArrow
        return list(_load_from_socket(port, ArrowSerializer()))[0]
      File "/home/bryan/git/spark/python/pyspark/rdd.py", line 140, in _load_from_socket
        for item in serializer.load_stream(rf):
      File "/home/bryan/git/spark/python/pyspark/serializers.py", line 139, in load_stream
        yield self._read_with_length(stream)
      File "/home/bryan/git/spark/python/pyspark/serializers.py", line 164, in _read_with_length
        return self.loads(obj)
      File "/home/bryan/git/spark/python/pyspark/serializers.py", line 192, in loads
        return reader.get_record_batch(0)
      File "pyarrow/ipc.pyx", line 150, in pyarrow.ipc.ArrowFileReader.get_record_batch (/home/bryan/git/arrow/python/build/temp.linux-x86_64-2.7/ipc.cxx:3074)
        check_status(self.reader.get().GetRecordBatch(i, &batch))
      File "pyarrow/error.pyx", line 31, in pyarrow.error.check_status (/home/bryan/git/arrow/python/build/temp.linux-x86_64-2.7/error.cxx:1185)
        raise ArrowException(frombytes(c_message))
    ArrowException: Invalid: metadata size invalid
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121830292
  
    --- Diff: python/pyspark/serializers.py ---
    @@ -182,6 +182,23 @@ def loads(self, obj):
             raise NotImplementedError
     
     
    +class ArrowSerializer(FramedSerializer):
    +    """
    +    Serializes an Arrow stream.
    +    """
    +
    +    def dumps(self, obj):
    +        raise NotImplementedError
    +
    +    def loads(self, obj):
    +        import pyarrow as pa
    +        reader = pa.RecordBatchFileReader(pa.BufferReader(obj))
    +        return reader.read_all()
    --- End diff --
    
    since we are sending multiple batches from JVM, does `reader.read_all()` wait for all the bacthes?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    we can update the test after merging https://github.com/apache/spark/pull/18378


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112368367
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +
    +    // Iterate over payload batches to write each one, ensure all batches get closed
    +    var batch: ArrowRecordBatch = null
    +    Utils.tryWithSafeFinallyAndFailureCallbacks {
    +      while (payload.hasNext) {
    +        batch = payload.next()
    +        writer.writeRecordBatch(batch)
    +        batch.close()
    +      }
    +    }(catchBlock = {
    +      Option(batch).foreach(_.close())
    +      payload.foreach(_.close())
    +    }, finallyBlock = writer.close())
    +
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    --- End diff --
    
    your indentation style doesn't match Spark's.
    
    ```
    private[sql] abstract class PrimitiveColumnWriter(val ordinal: Int, val allocator: BaseAllocator)
      extends ColumnWriter{
    
    }
    ```
        


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @icexelloss, @wesm I branched off here for us to integrate our changes https://github.com/BryanCutler/spark/tree/arrow-integration 
    cc @yinxusen 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #68425 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/68425/consoleFull)** for PR 15821 at commit [`3f855ec`](https://github.com/apache/spark/commit/3f855eccd2c65b513e0f48cd3a25f08bb3205d75).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by julienledem <gi...@git.apache.org>.
Github user julienledem commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105323172
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val fieldAndBuf = columnWriters.map { writer =>
    +      writer.finish()
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +    payload.foreach { batch =>
    +      try {
    +        writer.writeRecordBatch(batch)
    +      } finally {
    +        batch.close()
    +      }
    +    }
    +    writer.close()
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow, ordinal: Int): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row, ordinal)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    +
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, bool2int(row.getBoolean(ordinal)))
    --- End diff --
    
    there's ordinal the field of this class and ordinal the parameter of this method.
    What is the meaning of each of them? 
    Possibly rename them to be more specific.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r98077366
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2729,6 +2755,29 @@ class Dataset[T] private[sql](
         }
       }
     
    +  /**
    +   * Collect a Dataset as an ArrowRecordBatch, and serve the ArrowRecordBatch to PySpark.
    +   */
    +  private[sql] def collectAsArrowToPython(): Int = {
    +    val recordBatch = collectAsArrow()
    +    val arrowSchema = Arrow.schemaToArrowSchema(this.schema)
    +    val out = new ByteArrayOutputStream()
    +    try {
    +      val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +      writer.writeRecordBatch(recordBatch)
    +      writer.close()
    +    } catch {
    +      case e: Exception =>
    +        throw e
    +    } finally {
    +      recordBatch.close()
    +    }
    +
    +    withNewExecutionId {
    +      PythonRDD.serveIterator(Iterator(out.toByteArray), "serve-Arrow")
    +    }
    --- End diff --
    
    The mechanics of taking an `ArrowPayload` (as described above) and serving it to Python could be pushed down into either `Arrow.scala` (whatever that ends up being called) or in `PythonRDD`. e.g.
    
    ```scala
    val payload = collectAsArrow()
    payload.serveToPython()
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #73355 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/73355/testReport)** for PR 15821 at commit [`9c8ea63`](https://github.com/apache/spark/commit/9c8ea63ccec4ceb9dd40834bca530a6265385579).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Bryan,
    
    I am working on:
    (1) Add more numbers to benchmark.py
    (2) Add support for date/timestamp/binary type
    (3) Fix memory leaking in the code.
    
    All these should be done soon (tomorrow, if not today), but I think we can
    start getting feedbacks from Spark committers.
    
    What do you think? Is there anything else you want to be done before
    updating the PR to Spark committers?
    
    Li
    
    On Wed, Jan 18, 2017 at 7:52 PM, Bryan Cutler <no...@github.com>
    wrote:
    
    > Shall we update this PR to the latest and solicit from involvement from
    > Spark committers?
    >
    > Yeah, I think it's about ready for that. After we integrate the latest
    > changes, I'll go over once more for some minor cleanup and update this.
    > Probably in the next day or so.
    >
    > \u2014
    > You are receiving this because you were mentioned.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15821#issuecomment-273649530>, or mute
    > the thread
    > <https://github.com/notifications/unsubscribe-auth/AAwbrDkFMHPoyXOD0H-OYSyeAx_1EL2Jks5rTrO4gaJpZM4KtGBc>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105463346
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/ArrowConvertersSuite.scala ---
    @@ -0,0 +1,567 @@
    +/*
    + * 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
    +
    +import java.io.File
    +import java.nio.charset.StandardCharsets
    +import java.sql.{Date, Timestamp}
    +import java.text.SimpleDateFormat
    +import java.util.Locale
    +
    +import com.google.common.io.Files
    +import org.apache.arrow.vector.{VectorLoader, VectorSchemaRoot}
    +import org.apache.arrow.vector.file.json.JsonFileReader
    +import org.apache.arrow.vector.util.Validator
    +import org.json4s.jackson.JsonMethods._
    +import org.json4s.JsonAST._
    +import org.json4s.JsonDSL._
    +import org.scalatest.BeforeAndAfterAll
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.StructType
    +import org.apache.spark.util.Utils
    +
    +
    +class ArrowConvertersSuite extends SharedSQLContext with BeforeAndAfterAll {
    +  import testImplicits._
    +
    +  private var tempDataPath: String = _
    +
    +  private def collectAsArrow(df: DataFrame,
    +                             converter: Option[ArrowConverters] = None): ArrowPayload = {
    +    val cnvtr = converter.getOrElse(new ArrowConverters)
    +    val payloadByteArrays = df.toArrowPayloadBytes().collect()
    +    cnvtr.readPayloadByteArrays(payloadByteArrays)
    +  }
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    tempDataPath = Utils.createTempDir(namePrefix = "arrow").getAbsolutePath
    +  }
    +
    +  test("collect to arrow record batch") {
    +    val indexData = (1 to 6).toDF("i")
    +    val arrowPayload = collectAsArrow(indexData)
    +    assert(arrowPayload.nonEmpty)
    +    val arrowBatches = arrowPayload.toArray
    +    assert(arrowBatches.length == indexData.rdd.getNumPartitions)
    +    val rowCount = arrowBatches.map(batch => batch.getLength).sum
    +    assert(rowCount === indexData.count())
    +    arrowBatches.foreach(batch => assert(batch.getNodes.size() > 0))
    +    arrowBatches.foreach(batch => batch.close())
    +  }
    +
    +  test("numeric type conversion") {
    +    collectAndValidate(indexData)
    +    collectAndValidate(shortData)
    +    collectAndValidate(intData)
    +    collectAndValidate(longData)
    +    collectAndValidate(floatData)
    +    collectAndValidate(doubleData)
    +  }
    +
    +  test("mixed numeric type conversion") {
    +    collectAndValidate(mixedNumericData)
    +  }
    +
    +  test("boolean type conversion") {
    +    collectAndValidate(boolData)
    +  }
    +
    +  test("string type conversion") {
    +    collectAndValidate(stringData)
    +  }
    +
    +  test("byte type conversion") {
    +    collectAndValidate(byteData)
    +  }
    +
    +  test("timestamp conversion") {
    +    collectAndValidate(timestampData)
    +  }
    +
    +  // TODO: Not currently supported in Arrow JSON reader
    +  ignore("date conversion") {
    +    // collectAndValidate(dateTimeData)
    +  }
    +
    +  // TODO: Not currently supported in Arrow JSON reader
    +  ignore("binary type conversion") {
    +    // collectAndValidate(binaryData)
    +  }
    +
    +  test("floating-point NaN") {
    +    collectAndValidate(floatNaNData)
    +  }
    +
    +  test("partitioned DataFrame") {
    +    val converter = new ArrowConverters
    +    val schema = testData2.schema
    +    val arrowPayload = collectAsArrow(testData2, Some(converter))
    +    val arrowBatches = arrowPayload.toArray
    +    // NOTE: testData2 should have 2 partitions -> 2 arrow batches in payload
    +    assert(arrowBatches.length === 2)
    +    val pl1 = new ArrowStaticPayload(arrowBatches(0))
    +    val pl2 = new ArrowStaticPayload(arrowBatches(1))
    +    // Generate JSON files
    +    val a = List[Int](1, 1, 2, 2, 3, 3)
    +    val b = List[Int](1, 2, 1, 2, 1, 2)
    +    val fields = Seq(new IntegerType("a", is_signed = true, 32, nullable = false),
    +      new IntegerType("b", is_signed = true, 32, nullable = false))
    +    def getBatch(x: Seq[Int], y: Seq[Int]): JSONRecordBatch = {
    +      val columns = Seq(new PrimitiveColumn("a", x.length, x.map(_ => true), x),
    +        new PrimitiveColumn("b", y.length, y.map(_ => true), y))
    +      new JSONRecordBatch(x.length, columns)
    +    }
    +    val json1 = new JSONFile(new JSONSchema(fields), Seq(getBatch(a.take(3), b.take(3))))
    +    val json2 = new JSONFile(new JSONSchema(fields), Seq(getBatch(a.takeRight(3), b.takeRight(3))))
    +    val tempFile1 = new File(tempDataPath, "testData2-ints-part1.json")
    +    val tempFile2 = new File(tempDataPath, "testData2-ints-part2.json")
    +    json1.write(tempFile1)
    +    json2.write(tempFile2)
    +    validateConversion(schema, pl1, tempFile1, Some(converter))
    +    validateConversion(schema, pl2, tempFile2, Some(converter))
    +  }
    +
    +  test("empty frame collect") {
    +    val arrowPayload = collectAsArrow(spark.emptyDataFrame)
    +    assert(arrowPayload.isEmpty)
    +  }
    +
    +  test("empty partition collect") {
    +    val emptyPart = spark.sparkContext.parallelize(Seq(1), 2).toDF("i")
    +    val arrowPayload = collectAsArrow(emptyPart)
    +    val arrowBatches = arrowPayload.toArray
    +    assert(arrowBatches.length === 2)
    +    assert(arrowBatches.count(_.getLength == 0) === 1)
    +    assert(arrowBatches.count(_.getLength == 1) === 1)
    +  }
    +
    +  test("unsupported types") {
    +    def runUnsupported(block: => Unit): Unit = {
    +      val msg = intercept[SparkException] {
    +        block
    +      }
    +      assert(msg.getMessage.contains("Unsupported data type"))
    +      assert(msg.getCause.getClass === classOf[UnsupportedOperationException])
    +    }
    +
    +    runUnsupported { collectAsArrow(decimalData) }
    +    runUnsupported { collectAsArrow(arrayData.toDF()) }
    +    runUnsupported { collectAsArrow(mapData.toDF()) }
    +    runUnsupported { collectAsArrow(complexData) }
    +  }
    +
    +  test("test Arrow Validator") {
    +    val sdata = shortData
    +    val idata = intData
    +
    +    // Different schema
    +    intercept[IllegalArgumentException] {
    +      collectAndValidate(DataTuple(sdata.df, idata.json, idata.file))
    +    }
    +
    +    // Different values
    +    intercept[IllegalArgumentException] {
    +      collectAndValidate(DataTuple(idata.df.sort($"a_i".desc), idata.json, idata.file))
    +    }
    +  }
    +
    +  /** Test that a converted DataFrame to Arrow record batch equals batch read from JSON file */
    +  private def collectAndValidate(data: DataTuple): Unit = {
    +    val converter = new ArrowConverters
    +    // NOTE: coalesce to single partition because can only load 1 batch in validator
    +    val arrowPayload = collectAsArrow(data.df.coalesce(1), Some(converter))
    +    val tempFile = new File(tempDataPath, data.file)
    +    data.json.write(tempFile)
    +    validateConversion(data.df.schema, arrowPayload, tempFile, Some(converter))
    +  }
    +
    +  private def validateConversion(sparkSchema: StructType,
    +                                 arrowPayload: ArrowPayload,
    +                                 jsonFile: File,
    +                                 converterOpt: Option[ArrowConverters] = None): Unit = {
    +    val converter = converterOpt.getOrElse(new ArrowConverters)
    +    val jsonReader = new JsonFileReader(jsonFile, converter.allocator)
    +
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(sparkSchema)
    +    val jsonSchema = jsonReader.start()
    +    Validator.compareSchemas(arrowSchema, jsonSchema)
    +
    +    val arrowRoot = new VectorSchemaRoot(arrowSchema, converter.allocator)
    +    val vectorLoader = new VectorLoader(arrowRoot)
    +    arrowPayload.foreach(vectorLoader.load)
    +    val jsonRoot = jsonReader.read()
    +    Validator.compareVectorSchemaRoot(arrowRoot, jsonRoot)
    +  }
    +
    +  // Create Spark DataFrame and matching Arrow JSON at same time for validation
    +  private case class DataTuple(df: DataFrame, json: JSONFile, file: String)
    +
    +  private def indexData: DataTuple = {
    +    val data = List[Int](1, 2, 3, 4, 5, 6)
    +    val fields = Seq(new IntegerType("i", is_signed = true, 32, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("i", data.length, data.map(_ => true), data))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("i"), new JSONFile(schema, Seq(batch)), "indexData-ints.json")
    +  }
    +
    +  private def shortData: DataTuple = {
    +    val a_s = List[Short](1, -1, 2, -2, 32767, -32768)
    +    val b_s = List[Option[Short]](Some(1), None, None, Some(-2), None, Some(-32768))
    +    val fields = Seq(new IntegerType("a_s", is_signed = true, 16, nullable = false),
    +      new IntegerType("b_s", is_signed = true, 16, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val b_s_values = b_s.map(_.map(_.toInt).getOrElse(0))
    +    val columns = Seq(
    +      new PrimitiveColumn("a_s", a_s.length, a_s.map(_ => true), a_s.map(_.toInt)),
    +      new PrimitiveColumn("b_s", b_s.length, b_s.map(_.isDefined), b_s_values))
    +    val batch = new JSONRecordBatch(a_s.length, columns)
    +    val df = a_s.zip(b_s).toDF("a_s", "b_s")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-16bit.json")
    +  }
    +
    +  private def intData: DataTuple = {
    +    val a_i = List[Int](1, -1, 2, -2, 2147483647, -2147483648)
    +    val b_i = List[Option[Int]](Some(1), None, None, Some(-2), None, Some(-2147483648))
    +    val fields = Seq(new IntegerType("a_i", is_signed = true, 32, nullable = false),
    +      new IntegerType("b_i", is_signed = true, 32, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_i", a_i.length, a_i.map(_ => true), a_i),
    +      new PrimitiveColumn("b_i", b_i.length, b_i.map(_.isDefined), b_i.map(_.getOrElse(0))))
    +    val batch = new JSONRecordBatch(a_i.length, columns)
    +    val df = a_i.zip(b_i).toDF("a_i", "b_i")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-32bit.json")
    +  }
    +
    +  private def longData: DataTuple = {
    +    val a_l = List[Long](1, -1, 2, -2, 9223372036854775807L, -9223372036854775808L)
    +    val b_l = List[Option[Long]](Some(1), None, None, Some(-2), None, Some(-9223372036854775808L))
    +    val fields = Seq(new IntegerType("a_l", is_signed = true, 64, nullable = false),
    +      new IntegerType("b_l", is_signed = true, 64, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_l", a_l.length, a_l.map(_ => true), a_l),
    +      new PrimitiveColumn("b_l", b_l.length, b_l.map(_.isDefined), b_l.map(_.getOrElse(0L))))
    +    val batch = new JSONRecordBatch(a_l.length, columns)
    +    val df = a_l.zip(b_l).toDF("a_l", "b_l")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "integer-64bit.json")
    +  }
    +
    +  private def floatData: DataTuple = {
    +    val a_f = List(1.0f, 2.0f, 0.01f, 200.0f, 0.0001f, 20000.0f)
    +    val b_f = List[Option[Float]](Some(1.1f), None, None, Some(2.2f), None, Some(3.3f))
    +    val fields = Seq(new FloatingPointType("a_f", 32, nullable = false),
    +      new FloatingPointType("b_f", 32, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_f", a_f.length, a_f.map(_ => true), a_f),
    +      new PrimitiveColumn("b_f", b_f.length, b_f.map(_.isDefined), b_f.map(_.getOrElse(0.0f))))
    +    val batch = new JSONRecordBatch(a_f.length, columns)
    +    val df = a_f.zip(b_f).toDF("a_f", "b_f")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "floating_point-single_precision.json")
    +  }
    +
    +  private def doubleData: DataTuple = {
    +    val a_d = List(1.0, 2.0, 0.01, 200.0, 0.0001, 20000.0)
    +    val b_d = List[Option[Double]](Some(1.1), None, None, Some(2.2), None, Some(3.3))
    +    val fields = Seq(new FloatingPointType("a_d", 64, nullable = false),
    +      new FloatingPointType("b_d", 64, nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_d", a_d.length, a_d.map(_ => true), a_d),
    +      new PrimitiveColumn("b_d", b_d.length, b_d.map(_.isDefined), b_d.map(_.getOrElse(0.0))))
    +    val batch = new JSONRecordBatch(a_d.length, columns)
    +    val df = a_d.zip(b_d).toDF("a_d", "b_d")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "floating_point-double_precision.json")
    +  }
    +
    +  private def mixedNumericData: DataTuple = {
    +    val data = List(1, 2, 3, 4, 5, 6)
    +    val fields = Seq(new IntegerType("a", is_signed = true, 16, nullable = false),
    +      new FloatingPointType("b", 32, nullable = false),
    +      new IntegerType("c", is_signed = true, 32, nullable = false),
    +      new FloatingPointType("d", 64, nullable = false),
    +      new IntegerType("e", is_signed = true, 64, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a", data.length, data.map(_ => true), data),
    +      new PrimitiveColumn("b", data.length, data.map(_ => true), data.map(_.toFloat)),
    +      new PrimitiveColumn("c", data.length, data.map(_ => true), data),
    +      new PrimitiveColumn("d", data.length, data.map(_ => true), data.map(_.toDouble)),
    +      new PrimitiveColumn("e", data.length, data.map(_ => true), data)
    +    )
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    val data_tuples = for (d <- data) yield {
    +      (d.toShort, d.toFloat, d.toInt, d.toDouble, d.toLong)
    +    }
    +    val df = data_tuples.toDF("a", "b", "c", "d", "e")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "mixed_numeric_types.json")
    +  }
    +
    +  private def boolData: DataTuple = {
    +    val data = Seq(true, true, false, true)
    +    val fields = Seq(new BooleanType("a_bool", nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("a_bool", data.length, data.map(_ => true), data))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("a_bool"), new JSONFile(schema, Seq(batch)), "boolData.json")
    +  }
    +
    +  private def stringData: DataTuple = {
    +    val upperCase = Seq("A", "B", "C")
    +    val lowerCase = Seq("a", "b", "c")
    +    val nullStr = Seq("ab", "CDE", null)
    +    val fields = Seq(new StringType("upper_case", nullable = true),
    +      new StringType("lower_case", nullable = true),
    +      new StringType("null_str", nullable = true))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new StringColumn("upper_case", upperCase.length, upperCase.map(_ => true), upperCase),
    +      new StringColumn("lower_case", lowerCase.length, lowerCase.map(_ => true), lowerCase),
    +      new StringColumn("null_str", nullStr.length, nullStr.map(_ != null),
    +        nullStr.map { s => if (s == null) "" else s}
    +      ))
    +    val batch = new JSONRecordBatch(upperCase.length, columns)
    +    val df = (upperCase, lowerCase, nullStr).zipped.toList
    +      .toDF("upper_case", "lower_case", "null_str")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "stringData.json")
    +  }
    +
    +  private def byteData: DataTuple = {
    +    val data = List[Byte](1.toByte, (-1).toByte, 64.toByte, Byte.MaxValue)
    +    val fields = Seq(new IntegerType("a_byte", is_signed = true, 8, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(
    +      new PrimitiveColumn("a_byte", data.length, data.map(_ => true), data.map(_.toInt)))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("a_byte"), new JSONFile(schema, Seq(batch)), "byteData.json")
    +  }
    +
    +  private def floatNaNData: DataTuple = {
    +    val fnan = Seq(1.2F, Float.NaN)
    +    val dnan = Seq(Double.NaN, 1.2)
    +    val fields = Seq(new FloatingPointType("NaN_f", 32, nullable = false),
    +      new FloatingPointType("NaN_d", 64, nullable = false))
    +    val schema = new JSONSchema(fields)
    +    val columns = Seq(new PrimitiveColumn("NaN_f", fnan.length, fnan.map(_ => true), fnan),
    +      new PrimitiveColumn("NaN_d", dnan.length, dnan.map(_ => true), dnan))
    +    val batch = new JSONRecordBatch(fnan.length, columns)
    +    val df = fnan.zip(dnan).toDF("NaN_f", "NaN_d")
    +    DataTuple(df, new JSONFile(schema, Seq(batch)), "nanData-floating_point.json")
    +  }
    +
    +  private def timestampData: DataTuple = {
    +    val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z", Locale.US)
    +    val ts1 = new Timestamp(sdf.parse("2013-04-08 01:10:15.567 UTC").getTime)
    +    val ts2 = new Timestamp(sdf.parse("2013-04-08 13:10:10.789 UTC").getTime)
    +    val data = Seq(ts1, ts2)
    +    val schema = new JSONSchema(Seq(new TimestampType("c_timestamp")))
    +    val columns = Seq(
    +      new PrimitiveColumn("c_timestamp", data.length, data.map(_ => true), data.map(_.getTime)))
    +    val batch = new JSONRecordBatch(data.length, columns)
    +    DataTuple(data.toDF("c_timestamp"), new JSONFile(schema, Seq(batch)), "timestampData.json")
    +  }
    +
    +  private def dateData: DataTuple = {
    +    val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z", Locale.US)
    +    val d1 = new Date(sdf.parse("2015-04-08 13:10:15.000 UTC").getTime)
    +    val d2 = new Date(sdf.parse("2015-04-08 13:10:15.000 UTC").getTime)
    +    val ts1 = new Timestamp(sdf.parse("2013-04-08 01:10:15.567 UTC").getTime)
    +    val ts2 = new Timestamp(sdf.parse("2013-04-08 13:10:10.789 UTC").getTime)
    +    val df = Seq((d1, sdf.format(d1), ts1), (d2, sdf.format(d2), ts2))
    +      .toDF("a_date", "b_string", "c_timestamp")
    +    val jsonFile = new JSONFile(new JSONSchema(Seq.empty[DataType]), Seq.empty[JSONRecordBatch])
    +    DataTuple(df, jsonFile, "dateData.json")
    +  }
    +
    +  /**
    +   * Arrow JSON Format Data Generation
    +   * Referenced from https://github.com/apache/arrow/blob/master/integration/integration_test.py
    +   */
    --- End diff --
    
    Thanks, I'll take a look


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #76754 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/76754/testReport)** for PR 15821 at commit [`934c147`](https://github.com/apache/spark/commit/934c147cf41752d382ee6ae304ed18ca5bed73e4).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r113600552
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +
    +    // Iterate over payload batches to write each one, ensure all batches get closed
    +    var batch: ArrowRecordBatch = null
    +    Utils.tryWithSafeFinallyAndFailureCallbacks {
    +      while (payload.hasNext) {
    +        batch = payload.next()
    +        writer.writeRecordBatch(batch)
    +        batch.close()
    +      }
    +    }(catchBlock = {
    +      Option(batch).foreach(_.close())
    +      payload.foreach(_.close())
    +    }, finallyBlock = writer.close())
    +
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    +
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, bool2int(row.getBoolean(ordinal)))
    +}
    +
    +private[sql] class ShortColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", allocator)
    +  override val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[sql] class IntegerColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", allocator)
    +  override val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[sql] class LongColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", allocator)
    +  override val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[sql] class FloatColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", allocator)
    +  override val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[sql] class DoubleColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", allocator)
    +  override val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[sql] class ByteColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", allocator)
    +  override val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[sql] class UTF8StringColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    +  override val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    val bytes = row.getUTF8String(ordinal).getBytes
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class BinaryColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("BinaryValue", allocator)
    +  override val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    val bytes = row.getBinary(ordinal)
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class DateColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  override val valueVector: NullableDateVector
    +    = new NullableDateVector("DateValue", allocator)
    +  override val valueMutator: NullableDateVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit = {
    +    // TODO: comment on diff btw value representations of date/timestamp
    --- End diff --
    
    The Arrow classes are defined more clearly now, so I don't think an explanation will be needed in my next update.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    ## Benchmarks with Conversion done on Executor (updated)
    
    ## 1mm Longs
     _ | With Arrow | Without Arrow
    --|------------|-------------------
    count  |   50.000000 |    50.000000
    mean   | 0.047912  |   2.570021
    std   | 0.032028   |    0.115858
    min   | 0.033034   |  2.207390
    25%   |  0.039604   |     2.517681
    50%   |  0.042581   |    2.546360    
    75%   |  0.044779  |    2.631391
    max    | 0.257348   |    2.933432


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by leifwalsh <gi...@git.apache.org>.
Github user leifwalsh commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler awesome, thanks. I'll test ASAP but I believe you, don't block merge on my account. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/68954/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122359743
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    --- End diff --
    
    sounds good


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/76708/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/68427/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105978151
  
    --- Diff: python/pyspark/serializers.py ---
    @@ -182,6 +182,23 @@ def loads(self, obj):
             raise NotImplementedError
     
     
    +class ArrowSerializer(FramedSerializer):
    +    """
    +    Serializes an Arrow stream.
    +    """
    +
    +    def dumps(self, obj):
    +        raise NotImplementedError
    +
    +    def loads(self, obj):
    +        from pyarrow import FileReader, BufferReader
    --- End diff --
    
    @BryanCutler what do you think of gracefully failing when PyArrow isn't installed?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122929684
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,429 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark and served to a Python process.
    + */
    +private[sql] class ArrowPayload private[arrow] (payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as a type that can be served to Python.
    +   */
    +  def asPythonSerializable: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowPayload {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def apply(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowPayload = {
    +    new ArrowPayload(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload. Limit ArrowRecordBatch size in ArrowPayload
    +   * by setting maxRecordsPerBatch or use 0 to fully consume rowIter.
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      maxRecordsPerBatch: Int): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator, maxRecordsPerBatch)
    +        ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch, stopping when rowIter is consumed
    +   * or the number of records in the batch equals maxRecordsInBatch.  If maxRecordsPerBatch is 0,
    +   * then rowIter will be fully consumed.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator,
    +      maxRecordsPerBatch: Int = 0): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(field.dataType, ordinal, allocator).init()
    --- End diff --
    
    I'm not quite sure about the best practice of arrow writing, but wouldn't it be better to write the [root batch](https://github.com/apache/spark/pull/15821/files#diff-52cca47e7a940849b28d476ddf99d65eR182) directly? 
    
    We can also address this in followup


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Updated to work with the latest Arrow to prepare for 0.3 release (tests should fail because that artifact is not yet available).  Also improved consistency of ArrowConverters and did some cleanup.  From @rxin 's comments:
    
    > Move ArrowConverters.scala somewhere else that's not top level, e.g. execution.arrow
    
    It is now in the o.a.s.sql.execution.arrow package
    
    > Update this to arrow 0.3
    
    Ready to do this, should just need to update the pom again
    
    >Use SQLConf rather than a parameter for toPandas.
    
    I removed this flag and used the conf "spark.sql.execution.arrow.enable" which defaults to "false"
    
    >Handle failure gracefully if arrow is not installed (or somehow package it with Spark?)
    
    It would be difficult to package with Spark, I think, because pyarrow also depends on the native Arrow cpp library.  I changed it to fail gracefully if pyarrow is not available.  The error message is:
    ```
    ImportError: No module named pyarrow
    note: pyarrow must be installed and available on calling Python processif using spark.sql.execution.arrow.enable=true
    ```
    
    >How are the memory managed? Who allocates the memory for the arrow records, and who's responsible for releasing them?
    
    The Java side of Arrow requires using a BufferAllocator class that manages the allocated memory.  An instance of this must be used each time a ArrowRecordBatch is created and then the batch and allocator must be released/closed after they have been processed.  This is all handled in the `ArrowConverter` functions.  On the Python side, buffers are allocated from the Arrow cpp library and cleaned up when reference counts to the objects are zero.  The end user does not have to worry about managing any memory.



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Pre-release builds of Arrow 0.3 are now on conda-forge, which should help with testing https://anaconda.org/conda-forge/pyarrow/files


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks you for the review and good questions @cloud-fan!  Let me know if your still opposed to keeping the `ArrowPayload` class as is, otherwise I'll push an update for the `VarCharVector` string writer.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    yea I think it's fine to keep `ArrowPayload`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    ## Dependency Info
    
    This change does add Apache Arrow as a dependency, specifically the Java arrow-vector artifact.  For Python, usage is optional and test are conditional on ability to import pyarrow.  The Java Arrow dependency tree is minimal and can be found [here](https://github.com/apache/spark/files/798133/arrow-vector_deptree.txt).  It is relatively small, but does include Netty 4.0.41 (Spark currently uses netty-all 4.0.42 and doesn't conflict).
    
    Changes to Spark APIs have been kept at a minimal, and all Arrow classes have been encapsulated within `o.a.s.sql.ArrowConverters`.  On the Scala side, a package private method `toArrowPayloadBytes` has been added to perform the conversion to an Arrow 'payload' on the executor JVM.  This would also allow uses for the conversion, like with R for instance.  On the Python side, additions are a method `collectAsArrow` to collect and serve the Arrow payload to Python and a flag on `toPandas` that when enabled, will make use of `collectToArrow`.
    
    I know Spark has been burned on other dependencies before, like file formats, so I'll just point out how this is different.  Unlike a file on disk, Arrow is an in-memory format and is not meant to persist on disk.  So many issues that might arise when choosing a file format are not applicable here.  A great deal of care has gone in upfront to define the Arrow [format](https://github.com/apache/arrow/tree/master/format) so that it can remain as stable as possible.  I have also heard from the Arrow community that they are fully committed to ensure success in projects like Spark, and meet compatibility needs.  I can also attest from first-hand experience that they have been incredibly responsive to issues related to the this PR.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Hey @holdenk, I just had this in to do my own testing and hadn't thought
    about keeping the option, but if we do keep it then yeah you're right, it
    would be better to default to the original way.
    
    On Nov 22, 2016 12:02 PM, "Holden Karau" <no...@github.com> wrote:
    
    > *@holdenk* commented on this pull request.
    > ------------------------------
    >
    > In python/pyspark/sql/dataframe.py
    > <https://github.com/apache/spark/pull/15821#pullrequestreview-9746576>:
    >
    > > @@ -1508,7 +1518,7 @@ def toDF(self, *cols):
    >          return DataFrame(jdf, self.sql_ctx)
    >
    >      @since(1.3)
    > -    def toPandas(self):
    > +    def toPandas(self, useArrow=True):
    >
    > Would it maybe make more sense to default this to false or have more
    > thorough checking that the dataframe being written with arrow is supported?
    > At least initially the set of supported dataframes might be rather small.
    >
    > \u2014
    > You are receiving this because you authored the thread.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15821#pullrequestreview-9746576>,
    > or mute the thread
    > <https://github.com/notifications/unsubscribe-auth/AEUwdd_Y8jogGipNikWJG3JAPy8DoLV8ks5rA0pygaJpZM4KtGBc>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler Are you going to update this for arrow 0.3?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r115552398
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,396 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark
    + */
    +private[sql] class ArrowPayload(val batchBytes: Array[Byte]) extends Serializable {
    +
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(batchBytes, allocator)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    --- End diff --
    
    As far as I can tell, Parquet and other output writers can optionally limit the rows by setting `maxRecordsPerFile` [here](https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/FileFormatWriter.scala#L307).  I would think that is mostly to keep file size down, but we could something like that - maybe adding a SQLConf `spark.sql.execution.arrow.maxRecordsPerBatch`?
    
    @rxin do you have a preference on this?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Note: we are shooting for an Arrow RC in Monday time frame, so with luck we'll have a release cut next week


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    I'm against #18439 , I'd rather revert this and fix it later than installing packages without SSL.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler I'm working with @icexelloss on my end to get involved in this, we were going to start working on unit tests to validate converting each of the Spark SQL data types to Arrow format while the Arrow Java-C++ compatibility work progresses, but we don't want to duplicate any efforts if you're started on this. Perhaps we can create an integration branch someplace to make pull requests into since it will probably take a while until this patch will get accepted into Spark? 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122284356
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    --- End diff --
    
    True it's currently only used for test and will be needed in followup work.  It could be moved to test, but since these are package private, is that really necessary?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112373805
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    --- End diff --
    
    move init to the previous line


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #71950 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/71950/testReport)** for PR 15821 at commit [`9bb75de`](https://github.com/apache/spark/commit/9bb75de474f5e97f5dbc67481f7339b01c25380a).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121831202
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    --- End diff --
    
    Actually the read path is unnecessary, we only send data from JVM to python with Arrow format, but we never read it back. Can we remove it and add it back when we really need it?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks all! Apache Arrow has advanced a great deal since November, so I expect we can make a number of follow up PRs to support more data types and optimize use of the streaming record batch machinery (if you haven't already!) for lower memory utilization and better overall throughput to Python users. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    i agree w/@MaheshIBM that we're looking at a bad CA cert.  i think we're looking at a problem on continuum.io's side, not our side.  
    
    however, i do no like the thought of ignoring certs (on principle).  :)
    
    and finally, if i'm reading the run-pip-tests code correctly (and please correct me if i'm wrong @holdenk ), we're just creating a temp python environment in /tmp, installing some packages, running the tests, and then moving on.
    
    some thoughts/suggestions:
    * our conda environment is pretty stagnant and hasn't been explicitly upgraded since we deployed anaconda python over a year ago.
    * the py3k environment that exists in the workers' conda installation is solely used by spark builds, so updating said environment w/the packages in the run-pip-tests will remove the need to download them, but at the same time, make the tests a NOOP.
    * we can hope that continuum fixes their cert issue asap.  :\


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    okie dokie.  how about this i install pyarrow in the py3k conda environment right now...
    
    once that's done, we can remove the pyarrow test from run-pip-tests and add it to the regular tests (who wants to do this?).



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @shaneknapp your understanding about what run-pip-tests code is pretty correct. It's important to note that part of the test is installing the pyspark package its self to makesure we didn't break the packaging, and pyarrow is only installed because we want to be able to run some pyarrow tests with it -- we don't need that to be part of the packaging tests infact it would be simpler to have it be part of the normal tests.
    
    So one possible approach to fix this I think would be updating conda on the machines because its old, installing pyarrow into the py3k worker env, and then taking the pyarrow tests out of the packaging test and instead have them run in the normal flow.
    
    I'm not super sure this is a cert issue per-se, it seems that newer versions of conda are working fine (it's possible the SSL lib is slightly out of date and not understanding wildcards or something else in the cert)?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Seems it already asks to search in the conda-forge channel?
    
    https://github.com/apache/spark/blob/e44697606f429b01808c1a22cb44cb5b89585c5c/dev/run-pip-tests#L86


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r123128861
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -2473,6 +2482,76 @@ def range_frame_match():
     
             importlib.reload(window)
     
    +
    +@unittest.skipIf(not _have_arrow, "Arrow not installed")
    +class ArrowTests(ReusedPySparkTestCase):
    +
    +    @classmethod
    +    def setUpClass(cls):
    +        ReusedPySparkTestCase.setUpClass()
    +        cls.spark = SparkSession(cls.sc)
    +        cls.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        cls.schema = StructType([
    +            StructField("1_str_t", StringType(), True),
    +            StructField("2_int_t", IntegerType(), True),
    +            StructField("3_long_t", LongType(), True),
    +            StructField("4_float_t", FloatType(), True),
    +            StructField("5_double_t", DoubleType(), True)])
    +        cls.data = [("a", 1, 10, 0.2, 2.0),
    +                    ("b", 2, 20, 0.4, 4.0),
    +                    ("c", 3, 30, 0.8, 6.0)]
    +
    +    def assertFramesEqual(self, df_with_arrow, df_without):
    +        msg = ("DataFrame from Arrow is not equal" +
    +               ("\n\nWith Arrow:\n%s\n%s" % (df_with_arrow, df_with_arrow.dtypes)) +
    +               ("\n\nWithout:\n%s\n%s" % (df_without, df_without.dtypes)))
    +        self.assertTrue(df_without.equals(df_with_arrow), msg=msg)
    +
    +    def test_unsupported_datatype(self):
    +        schema = StructType([StructField("array", ArrayType(IntegerType(), False), True)])
    +        df = self.spark.createDataFrame([([1, 2, 3],)], schema=schema)
    +        with QuietTest(self.sc):
    +            self.assertRaises(Exception, lambda: df.toPandas())
    +
    +    def test_null_conversion(self):
    +        df_null = self.spark.createDataFrame([tuple([None for _ in range(len(self.data[0]))])] +
    +                                             self.data)
    +        pdf = df_null.toPandas()
    +        null_counts = pdf.isnull().sum().tolist()
    +        self.assertTrue(all([c == 1 for c in null_counts]))
    +
    +    def test_toPandas_arrow_toggle(self):
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        # NOTE - toPandas() without pyarrow will infer standard python data types
    --- End diff --
    
    makes sense, it's kind of a bug, maybe we should fix it for the non-arrow code path.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by leifwalsh <gi...@git.apache.org>.
Github user leifwalsh commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121922567
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1648,8 +1650,30 @@ def toPandas(self):
             0    2  Alice
             1    5    Bob
             """
    -        import pandas as pd
    -        return pd.DataFrame.from_records(self.collect(), columns=self.columns)
    +        if self.sql_ctx.getConf("spark.sql.execution.arrow.enable", "false").lower() == "true":
    +            try:
    +                import pyarrow
    +                tables = self._collectAsArrow()
    +                table = pyarrow.concat_tables(tables)
    +                return table.to_pandas()
    --- End diff --
    
    The JVM may have a heap size limit lower than the memory available on the driver, so a batch size can help the driver stay under that limit even if the collected data are larger in memory on the python size than the JVM's max heap. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121920656
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as an Array[Byte].
    +   */
    +  def toByteArray: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload. Limit ArrowRecordBatch size in ArrowPayload
    +   * by setting maxRecordsPerBatch or use 0 to fully consume rowIter.
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      maxRecordsPerBatch: Int): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator, maxRecordsPerBatch)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch, stopping when rowIter is consumed
    +   * or the number of records in the batch equals maxRecordsInBatch.  If maxRecordsPerBatch is 0,
    +   * then rowIter will be fully consumed.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator,
    +      maxRecordsPerBatch: Int = 0): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(field.dataType, ordinal, allocator).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    var recordsInBatch = 0
    +    while (rowIter.hasNext && (maxRecordsPerBatch <= 0 || recordsInBatch < maxRecordsPerBatch)) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +      recordsInBatch += 1
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert an ArrowRecordBatch to a byte array and close batch to release resources. Once closed,
    +   * the batch can no longer be used.
    +   */
    +  private[arrow] def batchToByteArray(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val root = VectorSchemaRoot.create(arrowSchema, allocator)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowFileWriter(root, null, Channels.newChannel(out))
    +
    +    // Write a batch to byte stream, ensure the batch, allocator and writer are closed
    +    Utils.tryWithSafeFinally {
    +      val loader = new VectorLoader(root)
    +      loader.load(batch)
    +      writer.writeBatch()  // writeBatch can throw IOException
    +    } {
    +      batch.close()
    +      root.close()
    +      writer.close()
    +    }
    +    out.toByteArray
    +  }
    +
    +  /**
    +   * Convert a byte array to an ArrowRecordBatch.
    +   */
    +  private[arrow] def byteArrayToBatch(
    +      batchBytes: Array[Byte],
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +    val in = new ByteArrayReadableSeekableByteChannel(batchBytes)
    +    val reader = new ArrowFileReader(in, allocator)
    +
    +    // Read a batch from a byte stream, ensure the reader is closed
    +    Utils.tryWithSafeFinally {
    +      val root = reader.getVectorSchemaRoot  // throws IOException
    +      val unloader = new VectorUnloader(root)
    +      reader.loadNextBatch()  // throws IOException
    +      unloader.getRecordBatch
    +    } {
    +      reader.close()
    +    }
    +  }
    +}
    +
    +/**
    + * Interface for writing InternalRows to Arrow Buffers.
    + */
    +private[arrow] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[arrow] abstract class PrimitiveColumnWriter(val ordinal: Int)
    +  extends ColumnWriter {
    +
    +  def getFieldType(dtype: ArrowType): FieldType = FieldType.nullable(dtype)
    +
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[arrow] class BooleanColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, if (row.getBoolean(ordinal)) 1 else 0 )
    +}
    +
    +private[arrow] class ShortColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", getFieldType(dtype: ArrowType), allocator)
    +  override val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[arrow] class IntegerColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[arrow] class LongColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[arrow] class FloatColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[arrow] class DoubleColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[arrow] class ByteColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[arrow] class UTF8StringColumnWriter(
    +    dtype: ArrowType,
    +    ordinal: Int,
    +    allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableVarBinaryVector
    --- End diff --
    
    why we choose this instead of `VarCharVector`?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122765858
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/arrow/ArrowConvertersSuite.scala ---
    @@ -0,0 +1,1218 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.File
    +import java.nio.charset.StandardCharsets
    +import java.sql.{Date, Timestamp}
    +import java.text.SimpleDateFormat
    +import java.util.Locale
    +
    +import com.google.common.io.Files
    +import org.apache.arrow.memory.RootAllocator
    +import org.apache.arrow.vector.{VectorLoader, VectorSchemaRoot}
    +import org.apache.arrow.vector.file.json.JsonFileReader
    +import org.apache.arrow.vector.util.Validator
    +import org.scalatest.BeforeAndAfterAll
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.{DataFrame, Row}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{BinaryType, StructField, StructType}
    +import org.apache.spark.util.Utils
    +
    +
    +class ArrowConvertersSuite extends SharedSQLContext with BeforeAndAfterAll {
    +  import testImplicits._
    +
    +  private var tempDataPath: String = _
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    tempDataPath = Utils.createTempDir(namePrefix = "arrow").getAbsolutePath
    +  }
    +
    +  test("collect to arrow record batch") {
    +    val indexData = (1 to 6).toDF("i")
    +    val arrowPayloads = indexData.toArrowPayload.collect()
    +    assert(arrowPayloads.nonEmpty)
    +    assert(arrowPayloads.length == indexData.rdd.getNumPartitions)
    +    val allocator = new RootAllocator(Long.MaxValue)
    +    val arrowRecordBatches = arrowPayloads.map(_.loadBatch(allocator))
    +    val rowCount = arrowRecordBatches.map(_.getLength).sum
    +    assert(rowCount === indexData.count())
    +    arrowRecordBatches.foreach(batch => assert(batch.getNodes.size() > 0))
    +    arrowRecordBatches.foreach(_.close())
    +    allocator.close()
    +  }
    +
    +  test("short conversion") {
    +    val json =
    +      s"""
    +         |{
    +         |  "schema" : {
    +         |    "fields" : [ {
    +         |      "name" : "a_s",
    +         |      "type" : {
    +         |        "name" : "int",
    +         |        "isSigned" : true,
    +         |        "bitWidth" : 16
    +         |      },
    +         |      "nullable" : false,
    +         |      "children" : [ ],
    +         |      "typeLayout" : {
    +         |        "vectors" : [ {
    +         |          "type" : "VALIDITY",
    +         |          "typeBitWidth" : 1
    +         |        }, {
    +         |          "type" : "DATA",
    +         |          "typeBitWidth" : 16
    +         |        } ]
    +         |      }
    +         |    }, {
    +         |      "name" : "b_s",
    +         |      "type" : {
    +         |        "name" : "int",
    +         |        "isSigned" : true,
    +         |        "bitWidth" : 16
    +         |      },
    +         |      "nullable" : true,
    +         |      "children" : [ ],
    +         |      "typeLayout" : {
    +         |        "vectors" : [ {
    +         |          "type" : "VALIDITY",
    +         |          "typeBitWidth" : 1
    +         |        }, {
    +         |          "type" : "DATA",
    +         |          "typeBitWidth" : 16
    +         |        } ]
    +         |      }
    +         |    } ]
    +         |  },
    +         |  "batches" : [ {
    +         |    "count" : 6,
    +         |    "columns" : [ {
    +         |      "name" : "a_s",
    +         |      "count" : 6,
    +         |      "VALIDITY" : [ 1, 1, 1, 1, 1, 1 ],
    +         |      "DATA" : [ 1, -1, 2, -2, 32767, -32768 ]
    +         |    }, {
    +         |      "name" : "b_s",
    +         |      "count" : 6,
    +         |      "VALIDITY" : [ 1, 0, 0, 1, 0, 1 ],
    +         |      "DATA" : [ 1, 0, 0, -2, 0, -32768 ]
    +         |    } ]
    +         |  } ]
    +         |}
    +       """.stripMargin
    +
    +    val a_s = List[Short](1, -1, 2, -2, 32767, -32768)
    +    val b_s = List[Option[Short]](Some(1), None, None, Some(-2), None, Some(-32768))
    +    val df = a_s.zip(b_s).toDF("a_s", "b_s")
    --- End diff --
    
    Yes, it is a little more compact but it's more difficult to control the specific types for each column, not as easy to visually compare with the inlined JSON, and can't add more than 2 columns this way.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    I recommend using the latest. The data format is forward/backward compatible so the JAR doesn't necessarily need to be 0.4.1 if you're using pyarrow 0.4.1 (0.4.1 fixed a Decimal regression in the Java library, but that isn't relevant here quite yet)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by julienledem <gi...@git.apache.org>.
Github user julienledem commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105466801
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    --- End diff --
    
    Yes. Feel free to send a PR to Arrow for this.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121614002
  
    --- Diff: pom.xml ---
    @@ -1871,6 +1872,25 @@
             <artifactId>paranamer</artifactId>
             <version>${paranamer.version}</version>
           </dependency>
    +      <dependency>
    +        <groupId>org.apache.arrow</groupId>
    --- End diff --
    
    why we add arrow dependency at root instead of only spark sql?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    FWIW, I am not against reverting. Just want to provide some contexts just in case missed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121831805
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    --- End diff --
    
    it's weird to do this heavy work in the constructor. If we remove `loadBatch`, I think we don't need this class and can just return byte array to the caller


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r101345064
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2729,6 +2749,18 @@ class Dataset[T] private[sql](
         }
       }
     
    +  /**
    +   * Collect a Dataset as an ArrowRecordBatch, and serve the ArrowRecordBatch to PySpark.
    +   */
    +  private[sql] def collectAsArrowToPython(): Int = {
    +    val payload = collectAsArrow()
    +    val payloadBytes = ArrowConverters.payloadToByteArray(payload, this.schema)
    +
    +    withNewExecutionId {
    +      PythonRDD.serveIterator(Iterator(payloadBytes), "serve-Arrow")
    --- End diff --
    
    Thanks @viirya for the review, I'm working on another update that will do conversion on the executors


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r106233588
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,419 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.arrow.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    --- End diff --
    
    yes, there is a test for unsupported types here https://github.com/BryanCutler/spark/blob/wip-toPandas_with_arrow-SPARK-13534/sql/core/src/test/scala/org/apache/spark/sql/ArrowConvertersSuite.scala#L155


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by srowen <gi...@git.apache.org>.
Github user srowen commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    CC @cloud-fan @BryanCutler is there an easy fix or do we need to revert this temporarily? it's failing the builds


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r104261004
  
    --- Diff: pom.xml ---
    @@ -1871,6 +1872,25 @@
             <artifactId>paranamer</artifactId>
             <version>${paranamer.version}</version>
           </dependency>
    +      <dependency>
    +        <groupId>org.apache.arrow</groupId>
    +        <artifactId>arrow-vector</artifactId>
    +        <version>${arrow.version}</version>
    +        <exclusions>
    --- End diff --
    
    I added netty to exclusions and does not seem to cause any issues


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r103583967
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -390,6 +391,18 @@ def collect(self):
                 port = self._jdf.collectToPython()
             return list(_load_from_socket(port, BatchedSerializer(PickleSerializer())))
     
    +    @since(2.2)
    +    def collectAsArrow(self):
    --- End diff --
    
    As we chatted it might make sense to make this an internal method for now (`_collectAsArrow`).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Jenkins retest this please


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/68425/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    This has been updated after integrating changes made with @icexelloss and @wesm.  There has been good progress made and it would be great if others could take a look and review/test this out.  
    
    The current state of `toPandas()` with Arrow has support for Datasets with primitive, string, and timestamp data types.  Complex types such as Structs, Array, and Mapped are not yet supported but are a wip.  There is a suite of tests in Scala to test Dataset -> ArrowRecordBatch conversion and a collection on JSON files that serve to validate the converted data is correct.  Also, added PySpark tests to verify Pandas frame is correct.  It is compiled with the current arrow master 0.1.1-SNAPSHOT at commit https://github.com/apache/arrow/commit/7d3e2a3ab90324625b738e464a020758379f457a
    
    The performance so far shows a significant increase and I will follow up with a script to run and details of the results seen.  Please ping me with any questions on setting up the build of Arrow or running the benchmarks.  It would be great if this could be considered for Spark 2.2 as Arrow 0.2 will be released soon and be able to support the functionality used here.
    
    @holdenk @davies @rxin, I would love to hear your thoughts on this so far.  Thanks!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r108833416
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -56,6 +56,15 @@
     from pyspark.sql.utils import AnalysisException, ParseException, IllegalArgumentException
     
     
    +_have_arrow = False
    +try:
    +    import pyarrow
    +    _have_arrow = True
    --- End diff --
    
    I mean we should throw an exception when `useArrow` is used but no pyspark is installed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    hmm.  currently thinking about this.  thanks for the ping, shiv.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #78331 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/78331/testReport)** for PR 15821 at commit [`f96f555`](https://github.com/apache/spark/commit/f96f555e1a3b8aabc7949d4b355f3af3b0e78b5a).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r103052418
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1610,8 +1623,14 @@ def toPandas(self):
             0    2  Alice
             1    5    Bob
             """
    -        import pandas as pd
    -        return pd.DataFrame.from_records(self.collect(), columns=self.columns)
    +        if useArrow:
    +            from pyarrow.table import concat_tables
    --- End diff --
    
    Since a user might specify useArrow without having the required dependcies installed despite the docstring warning, it would be good to make sure the exception thrown gives the user clear steps to resolve the issue.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #68806 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/68806/consoleFull)** for PR 15821 at commit [`053e3a6`](https://github.com/apache/spark/commit/053e3a631fc802c8063b55482c701be9ee96afe3).
     * This patch **fails Python style tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/74118/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #73321 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/73321/testReport)** for PR 15821 at commit [`9c8ea63`](https://github.com/apache/spark/commit/9c8ea63ccec4ceb9dd40834bca530a6265385579).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r101214398
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,360 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.ArrowWriter
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  private class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +    private val iter = batches.iterator
    +
    +    override def next(): ArrowRecordBatch = iter.next()
    +    override def hasNext: Boolean = iter.hasNext
    +  }
    +
    +  def internalRowsToPayload(rows: Array[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowsToArrowRecordBatch(rows, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Transfer an array of InternalRow to an ArrowRecordBatch.
    +   */
    +  private[sql] def internalRowsToArrowRecordBatch(
    +      rows: Array[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +    val fieldAndBuf = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      internalRowToArrowBuf(rows, ordinal, field, allocator)
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1.flatten
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val recordBatch = new ArrowRecordBatch(rows.length,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Write a Field from array of InternalRow to an ArrowBuf.
    +   */
    +  private def internalRowToArrowBuf(
    +      rows: Array[InternalRow],
    +      ordinal: Int,
    +      field: StructField,
    +      allocator: RootAllocator): (Array[ArrowFieldNode], Array[ArrowBuf]) = {
    +    val numOfRows = rows.length
    +    val columnWriter = ColumnWriter(allocator, field.dataType)
    +    columnWriter.init(numOfRows)
    +    var index = 0
    +
    +    while(index < numOfRows) {
    +      val row = rows(index)
    +      if (row.isNullAt(ordinal)) {
    +        columnWriter.writeNull()
    +      } else {
    +        columnWriter.write(row, ordinal)
    +      }
    +      index += 1
    +    }
    +
    +    val (arrowFieldNodes, arrowBufs) = columnWriter.finish()
    +    (arrowFieldNodes.toArray, arrowBufs.toArray)
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +    try {
    +      payload.foreach(writer.writeRecordBatch)
    +    } catch {
    +      case e: Exception =>
    +        throw e
    +    } finally {
    +      writer.close()
    +      payload.foreach(_.close())
    +    }
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(initialSize: Int): Unit
    +  def writeNull(): Unit
    +  def write(row: InternalRow, ordinal: Int): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(protected val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  protected def valueVector: BaseDataValueVector
    +  protected def valueMutator: BaseMutator
    +
    +  protected def setNull(): Unit
    +  protected def setValue(row: InternalRow, ordinal: Int): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(initialSize: Int): Unit = {
    +    valueVector.allocateNew()
    +  }
    +
    +  override def writeNull(): Unit = {
    +    setNull()
    +    nullCount += 1
    +    count += 1
    +  }
    +
    +  override def write(row: InternalRow, ordinal: Int): Unit = {
    +    setValue(row, ordinal)
    +    count += 1
    +  }
    +
    +  override def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf]) = {
    --- End diff --
    
    Do we need to prevent a `ColumnWriter` has been written after `finish` is called?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r98077909
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/ArrowSuite.scala ---
    @@ -0,0 +1,243 @@
    +/*
    + * 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
    +
    +import java.io.File
    +import java.sql.{Date, Timestamp}
    +import java.text.SimpleDateFormat
    +import java.util.{Locale, TimeZone}
    +
    +import org.apache.arrow.memory.RootAllocator
    +import org.apache.arrow.vector.{VectorLoader, VectorSchemaRoot}
    +import org.apache.arrow.vector.file.json.JsonFileReader
    +import org.apache.arrow.vector.util.Validator
    +
    +import org.apache.spark.sql.test.SharedSQLContext
    +
    +
    +// NOTE - nullable type can be declared as Option[*] or java.lang.*
    +private[sql] case class ShortData(i: Int, a_s: Short, b_s: Option[Short])
    +private[sql] case class IntData(i: Int, a_i: Int, b_i: Option[Int])
    +private[sql] case class LongData(i: Int, a_l: Long, b_l: java.lang.Long)
    +private[sql] case class FloatData(i: Int, a_f: Float, b_f: Option[Float])
    +private[sql] case class DoubleData(i: Int, a_d: Double, b_d: Option[Double])
    +
    +
    +class ArrowSuite extends SharedSQLContext {
    --- End diff --
    
    Rename to match the new name (if any) for `Arrow.scala`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by zero323 <gi...@git.apache.org>.
Github user zero323 commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    This looks amazing and I can't help but wonder - if the next step is _generating the arrow batches on executors_ is it possible to reuse this to pass data between JVM and Python UDFs? Right now, with ongoing shift towards SQL API, this is the prominent bottleneck for Python users. An improvement there could be a huge win.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121830561
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1648,8 +1650,30 @@ def toPandas(self):
             0    2  Alice
             1    5    Bob
             """
    -        import pandas as pd
    -        return pd.DataFrame.from_records(self.collect(), columns=self.columns)
    +        if self.sql_ctx.getConf("spark.sql.execution.arrow.enable", "false").lower() == "true":
    +            try:
    +                import pyarrow
    +                tables = self._collectAsArrow()
    +                table = pyarrow.concat_tables(tables)
    +                return table.to_pandas()
    --- End diff --
    
    so we have to load all the data to memory before creating pandas dataframe? Then it's useless to set a batch size limitation at JVM side...


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r123121124
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -2473,6 +2482,76 @@ def range_frame_match():
     
             importlib.reload(window)
     
    +
    +@unittest.skipIf(not _have_arrow, "Arrow not installed")
    +class ArrowTests(ReusedPySparkTestCase):
    +
    +    @classmethod
    +    def setUpClass(cls):
    +        ReusedPySparkTestCase.setUpClass()
    +        cls.spark = SparkSession(cls.sc)
    +        cls.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        cls.schema = StructType([
    +            StructField("1_str_t", StringType(), True),
    +            StructField("2_int_t", IntegerType(), True),
    +            StructField("3_long_t", LongType(), True),
    +            StructField("4_float_t", FloatType(), True),
    +            StructField("5_double_t", DoubleType(), True)])
    +        cls.data = [("a", 1, 10, 0.2, 2.0),
    +                    ("b", 2, 20, 0.4, 4.0),
    +                    ("c", 3, 30, 0.8, 6.0)]
    +
    +    def assertFramesEqual(self, df_with_arrow, df_without):
    +        msg = ("DataFrame from Arrow is not equal" +
    +               ("\n\nWith Arrow:\n%s\n%s" % (df_with_arrow, df_with_arrow.dtypes)) +
    +               ("\n\nWithout:\n%s\n%s" % (df_without, df_without.dtypes)))
    +        self.assertTrue(df_without.equals(df_with_arrow), msg=msg)
    +
    +    def test_unsupported_datatype(self):
    +        schema = StructType([StructField("array", ArrayType(IntegerType(), False), True)])
    +        df = self.spark.createDataFrame([([1, 2, 3],)], schema=schema)
    +        with QuietTest(self.sc):
    +            self.assertRaises(Exception, lambda: df.toPandas())
    +
    +    def test_null_conversion(self):
    +        df_null = self.spark.createDataFrame([tuple([None for _ in range(len(self.data[0]))])] +
    +                                             self.data)
    +        pdf = df_null.toPandas()
    +        null_counts = pdf.isnull().sum().tolist()
    +        self.assertTrue(all([c == 1 for c in null_counts]))
    +
    +    def test_toPandas_arrow_toggle(self):
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        # NOTE - toPandas() without pyarrow will infer standard python data types
    --- End diff --
    
    What I meant by this is if your Spark DataFrame has a column of `IntegerType` and `toPandas` is called without using Arrow, then Spark will pickle the data to standard python (python only has a single int type).  Then a pandas DataFrame is created using `from_records` with the python ints.  Calling this constructor forces pandas to infer the data type and it will choose `int64`.  With Arrow, the Spark schema is carried over, so pandas will know the correct data type is `int32`.  So if this test were to compare columns of `IntegerType` or `FloatType` with/without Arrow then the schema's would not match because of this.  The data is still the same, but I would say the schema is now correct with arrow.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #78265 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/78265/testReport)** for PR 15821 at commit [`8bff966`](https://github.com/apache/spark/commit/8bff966b637ee35a8c1cb051c7eb700f017e4d71).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122929031
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,396 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark
    + */
    +private[sql] class ArrowPayload(val batchBytes: Array[Byte]) extends Serializable {
    +
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(batchBytes, allocator)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    --- End diff --
    
    Spark doesn't always consume up the iterator, e.g. in a `LIMIT n` query. Usually we should register the clean up stuff in `TaskContext.addTaskCompletionListener`.
    
    Let's address it in follow-up


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    yeah, i think you're right.  however, upgrading to a new version of conda on a live environment does indeed scare me a little bit.  :)
    
    w/the new jenkins, i'll have a staging server dedicated to testing crap like this.  ah, the future:  so shiny and bright!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121729635
  
    --- Diff: pom.xml ---
    @@ -1871,6 +1872,25 @@
             <artifactId>paranamer</artifactId>
             <version>${paranamer.version}</version>
           </dependency>
    +      <dependency>
    +        <groupId>org.apache.arrow</groupId>
    --- End diff --
    
    i think this is just standard pom ..


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @mariusvniekerk I think just getting this working for local connection is going to be hard so breaking up using arrow on the driver side into a separate follow up piece of work would make sense.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r102614586
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -392,6 +392,15 @@ def collect(self):
     
         @ignore_unicode_prefix
         @since(2.0)
    --- End diff --
    
    should be 2.2


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r115635722
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,396 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark
    + */
    +private[sql] class ArrowPayload(val batchBytes: Array[Byte]) extends Serializable {
    +
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(batchBytes, allocator)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert an ArrowRecordBatch to a byte array and close batch
    +   */
    +  private[arrow] def batchToByteArray(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val root = VectorSchemaRoot.create(arrowSchema, allocator)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowFileWriter(root, null, Channels.newChannel(out))
    --- End diff --
    
    we will send multiple batches to Python for one RDD partitions, and the metadata/schema will be duplicated in these batches. Shall we consider using the stream writer?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r115802562
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,396 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark
    + */
    +private[sql] class ArrowPayload(val batchBytes: Array[Byte]) extends Serializable {
    +
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(batchBytes, allocator)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert an ArrowRecordBatch to a byte array and close batch
    +   */
    +  private[arrow] def batchToByteArray(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val root = VectorSchemaRoot.create(arrowSchema, allocator)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowFileWriter(root, null, Channels.newChannel(out))
    --- End diff --
    
    I think regardless of the arrow writer, trying to share metadata over partitions would require more involved changes to Spark internals.  That would definitely be a good issue to follow up with.  The main benefit of using the Arrow stream writer is that it can write directly to the socket and not have to buffer batches in a byte array.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121830995
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -2473,6 +2482,69 @@ def range_frame_match():
     
             importlib.reload(window)
     
    +
    +@unittest.skipIf(not _have_arrow, "Arrow not installed")
    +class ArrowTests(ReusedPySparkTestCase):
    +
    +    @classmethod
    +    def setUpClass(cls):
    +        ReusedPySparkTestCase.setUpClass()
    +        cls.spark = SparkSession(cls.sc)
    +        cls.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        cls.schema = StructType([
    +            StructField("1_str_t", StringType(), True),
    +            StructField("2_int_t", IntegerType(), True),
    +            StructField("3_long_t", LongType(), True),
    +            StructField("4_float_t", FloatType(), True),
    +            StructField("5_double_t", DoubleType(), True)])
    +        cls.data = [("a", 1, 10, 0.2, 2.0),
    +                    ("b", 2, 20, 0.4, 4.0),
    +                    ("c", 3, 30, 0.8, 6.0)]
    +
    +    def assertFramesEqual(self, df_with_arrow, df_without):
    +        msg = ("DataFrame from Arrow is not equal" +
    +               ("\n\nWith Arrow:\n%s\n%s" % (df_with_arrow, df_with_arrow.dtypes)) +
    +               ("\n\nWithout:\n%s\n%s" % (df_without, df_without.dtypes)))
    +        self.assertTrue(df_without.equals(df_with_arrow), msg=msg)
    +
    +    def test_unsupported_datatype(self):
    +        schema = StructType([StructField("array", ArrayType(IntegerType(), False), True)])
    +        df = self.spark.createDataFrame([([1, 2, 3],)], schema=schema)
    +        with QuietTest(self.sc):
    +            self.assertRaises(Exception, lambda: df.toPandas())
    +
    +    def test_null_conversion(self):
    +        df_null = self.spark.createDataFrame([tuple([None for _ in range(len(self.data[0]))])] +
    +                                             self.data)
    +        pdf = df_null.toPandas()
    +        null_counts = pdf.isnull().sum().tolist()
    +        self.assertTrue(all([c == 1 for c in null_counts]))
    +
    +    def test_toPandas_arrow_toggle(self):
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        # NOTE - toPandas() without pyarrow will infer standard python data types
    +        df_sel = df.select("1_str_t", "3_long_t", "5_double_t")
    +        self.spark.conf.set("spark.sql.execution.arrow.enable", "false")
    +        pdf = df_sel.toPandas()
    +        self.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        pdf_arrow = df_sel.toPandas()
    +        self.assertFramesEqual(pdf_arrow, pdf)
    +
    +    def test_pandas_round_trip(self):
    +        import pandas as pd
    +        import numpy as np
    +        data_dict = {}
    +        for j, name in enumerate(self.schema.names):
    +            data_dict[name] = [self.data[i][j] for i in range(len(self.data))]
    +        # need to convert these to numpy types first
    +        data_dict["2_int_t"] = np.int32(data_dict["2_int_t"])
    +        data_dict["4_float_t"] = np.float32(data_dict["4_float_t"])
    +        pdf = pd.DataFrame(data=data_dict)
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        pdf_arrow = df.toPandas()
    --- End diff --
    
    call `self.spark.conf.set("spark.sql.execution.arrow.enable", "true")` before this


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r103589341
  
    --- Diff: pom.xml ---
    @@ -1871,6 +1872,25 @@
             <artifactId>paranamer</artifactId>
             <version>${paranamer.version}</version>
           </dependency>
    +      <dependency>
    +        <groupId>org.apache.arrow</groupId>
    +        <artifactId>arrow-vector</artifactId>
    +        <version>${arrow.version}</version>
    +        <exclusions>
    --- End diff --
    
    Should we consider explore excluding netty here, since we exclude it in most of the other related projects (like parquet), since it seems to have added some unnecessary jars to the deps list.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by julienledem <gi...@git.apache.org>.
Github user julienledem commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105322707
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val fieldAndBuf = columnWriters.map { writer =>
    +      writer.finish()
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +    payload.foreach { batch =>
    +      try {
    +        writer.writeRecordBatch(batch)
    +      } finally {
    +        batch.close()
    +      }
    +    }
    +    writer.close()
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow, ordinal: Int): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row, ordinal)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    --- End diff --
    
    possibly define a case class for this so that we name the two members.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #76710 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/76710/testReport)** for PR 15821 at commit [`934c147`](https://github.com/apache/spark/commit/934c147cf41752d382ee6ae304ed18ca5bed73e4).
     * This patch **fails PySpark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #77390 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/77390/testReport)** for PR 15821 at commit [`d49a14d`](https://github.com/apache/spark/commit/d49a14daea3a5e92c2cfdf579373ca13b96c20e5).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105462127
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val fieldAndBuf = columnWriters.map { writer =>
    +      writer.finish()
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +    payload.foreach { batch =>
    +      try {
    +        writer.writeRecordBatch(batch)
    +      } finally {
    +        batch.close()
    +      }
    +    }
    +    writer.close()
    --- End diff --
    
    I think this part needs to be reworked a little.  If an exception is thrown, it should make sure all buffers are closed too.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Some PRs are blocked because of this failures, for days. I'm reverting it, @BryanCutler please reopen this PR after fixing the pip stuff, thanks!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler even though the json is long, it is still so much clearer than reading a pile of code that generates json ...



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    >Shall we update this PR to the latest and solicit from involvement from Spark committers?
    
    Yeah, I think it's about ready for that.  After we integrate the latest changes, I'll go over once more for some minor cleanup and update this.  Probably in the next day or so.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/76754/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r113730387
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,396 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark
    + */
    +private[sql] class ArrowPayload(val batchBytes: Array[Byte]) extends Serializable {
    +
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(batchBytes, allocator)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert an ArrowRecordBatch to a byte array and close batch
    +   */
    +  private[arrow] def batchToByteArray(
    --- End diff --
    
    Maybe useful to document that the `batch` becomes invalid after calling this function and should not be used further.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r106043402
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,419 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.arrow.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    --- End diff --
    
    Please add scaladoc for this even though its internal.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121815649
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as an Array[Byte].
    +   */
    +  def toByteArray: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload. Limit ArrowRecordBatch size in ArrowPayload
    +   * by setting maxRecordsPerBatch or use 0 to fully consume rowIter.
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      maxRecordsPerBatch: Int): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator, maxRecordsPerBatch)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch, stopping when rowIter is consumed
    +   * or the number of records in the batch equals maxRecordsInBatch.  If maxRecordsPerBatch is 0,
    +   * then rowIter will be fully consumed.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator,
    +      maxRecordsPerBatch: Int = 0): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(field.dataType, ordinal, allocator).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    var recordsInBatch = 0
    +    while (rowIter.hasNext && (maxRecordsPerBatch <= 0 || recordsInBatch < maxRecordsPerBatch)) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +      recordsInBatch += 1
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert an ArrowRecordBatch to a byte array and close batch to release resources. Once closed,
    +   * the batch can no longer be used.
    +   */
    +  private[arrow] def batchToByteArray(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val root = VectorSchemaRoot.create(arrowSchema, allocator)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowFileWriter(root, null, Channels.newChannel(out))
    +
    +    // Write a batch to byte stream, ensure the batch, allocator and writer are closed
    +    Utils.tryWithSafeFinally {
    +      val loader = new VectorLoader(root)
    +      loader.load(batch)
    +      writer.writeBatch()  // writeBatch can throw IOException
    +    } {
    +      batch.close()
    +      root.close()
    +      writer.close()
    +    }
    +    out.toByteArray
    +  }
    +
    +  /**
    +   * Convert a byte array to an ArrowRecordBatch.
    +   */
    +  private[arrow] def byteArrayToBatch(
    +      batchBytes: Array[Byte],
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +    val in = new ByteArrayReadableSeekableByteChannel(batchBytes)
    +    val reader = new ArrowFileReader(in, allocator)
    +
    +    // Read a batch from a byte stream, ensure the reader is closed
    +    Utils.tryWithSafeFinally {
    +      val root = reader.getVectorSchemaRoot  // throws IOException
    +      val unloader = new VectorUnloader(root)
    +      reader.loadNextBatch()  // throws IOException
    +      unloader.getRecordBatch
    +    } {
    +      reader.close()
    +    }
    +  }
    +}
    +
    +/**
    + * Interface for writing InternalRows to Arrow Buffers.
    + */
    +private[arrow] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[arrow] abstract class PrimitiveColumnWriter(val ordinal: Int)
    +  extends ColumnWriter {
    +
    +  def getFieldType(dtype: ArrowType): FieldType = FieldType.nullable(dtype)
    +
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[arrow] class BooleanColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, if (row.getBoolean(ordinal)) 1 else 0 )
    +}
    +
    +private[arrow] class ShortColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", getFieldType(dtype: ArrowType), allocator)
    +  override val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[arrow] class IntegerColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[arrow] class LongColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[arrow] class FloatColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[arrow] class DoubleColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[arrow] class ByteColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableUInt1Vector
    --- End diff --
    
    why `UInt1`? shouldn't this be tiny int?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Wait @cloud-fan! just want to ask a quesiton.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r106043718
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,419 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.arrow.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    --- End diff --
    
    Calling the input "byteArray" is maybe a bit confusing given how many byte arrays are floating around - can we give it a better name?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #74340 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/74340/testReport)** for PR 15821 at commit [`33b75b9`](https://github.com/apache/spark/commit/33b75b99b375292e1f4691983e37919d0a620725).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/73305/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/spark/pull/15821


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r106234199
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,419 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.arrow.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    --- End diff --
    
    Sure, just fyi this class is now part of the arrow-vector jar so it can be removed next release.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #77429 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/77429/testReport)** for PR 15821 at commit [`a630bf0`](https://github.com/apache/spark/commit/a630bf0d867c31be10660f25ae0d9b185dfa00e2).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Shall we update this PR to the latest and solicit from involvement from Spark committers? 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122305403
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/arrow/ArrowConvertersSuite.scala ---
    @@ -0,0 +1,1218 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.File
    +import java.nio.charset.StandardCharsets
    +import java.sql.{Date, Timestamp}
    +import java.text.SimpleDateFormat
    +import java.util.Locale
    +
    +import com.google.common.io.Files
    +import org.apache.arrow.memory.RootAllocator
    +import org.apache.arrow.vector.{VectorLoader, VectorSchemaRoot}
    +import org.apache.arrow.vector.file.json.JsonFileReader
    +import org.apache.arrow.vector.util.Validator
    +import org.scalatest.BeforeAndAfterAll
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.{DataFrame, Row}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{BinaryType, StructField, StructType}
    +import org.apache.spark.util.Utils
    +
    +
    +class ArrowConvertersSuite extends SharedSQLContext with BeforeAndAfterAll {
    +  import testImplicits._
    +
    +  private var tempDataPath: String = _
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    tempDataPath = Utils.createTempDir(namePrefix = "arrow").getAbsolutePath
    +  }
    +
    +  test("collect to arrow record batch") {
    +    val indexData = (1 to 6).toDF("i")
    +    val arrowPayloads = indexData.toArrowPayload.collect()
    +    assert(arrowPayloads.nonEmpty)
    +    assert(arrowPayloads.length == indexData.rdd.getNumPartitions)
    +    val allocator = new RootAllocator(Long.MaxValue)
    +    val arrowRecordBatches = arrowPayloads.map(_.loadBatch(allocator))
    +    val rowCount = arrowRecordBatches.map(_.getLength).sum
    +    assert(rowCount === indexData.count())
    +    arrowRecordBatches.foreach(batch => assert(batch.getNodes.size() > 0))
    +    arrowRecordBatches.foreach(_.close())
    +    allocator.close()
    +  }
    +
    +  test("short conversion") {
    +    val json =
    +      s"""
    +         |{
    +         |  "schema" : {
    +         |    "fields" : [ {
    +         |      "name" : "a_s",
    +         |      "type" : {
    +         |        "name" : "int",
    +         |        "isSigned" : true,
    +         |        "bitWidth" : 16
    +         |      },
    +         |      "nullable" : false,
    +         |      "children" : [ ],
    +         |      "typeLayout" : {
    +         |        "vectors" : [ {
    +         |          "type" : "VALIDITY",
    +         |          "typeBitWidth" : 1
    +         |        }, {
    +         |          "type" : "DATA",
    +         |          "typeBitWidth" : 16
    +         |        } ]
    +         |      }
    +         |    }, {
    +         |      "name" : "b_s",
    +         |      "type" : {
    +         |        "name" : "int",
    +         |        "isSigned" : true,
    +         |        "bitWidth" : 16
    +         |      },
    +         |      "nullable" : true,
    +         |      "children" : [ ],
    +         |      "typeLayout" : {
    +         |        "vectors" : [ {
    +         |          "type" : "VALIDITY",
    +         |          "typeBitWidth" : 1
    +         |        }, {
    +         |          "type" : "DATA",
    +         |          "typeBitWidth" : 16
    +         |        } ]
    +         |      }
    +         |    } ]
    +         |  },
    +         |  "batches" : [ {
    +         |    "count" : 6,
    +         |    "columns" : [ {
    +         |      "name" : "a_s",
    +         |      "count" : 6,
    +         |      "VALIDITY" : [ 1, 1, 1, 1, 1, 1 ],
    +         |      "DATA" : [ 1, -1, 2, -2, 32767, -32768 ]
    +         |    }, {
    +         |      "name" : "b_s",
    +         |      "count" : 6,
    +         |      "VALIDITY" : [ 1, 0, 0, 1, 0, 1 ],
    +         |      "DATA" : [ 1, 0, 0, -2, 0, -32768 ]
    +         |    } ]
    +         |  } ]
    +         |}
    +       """.stripMargin
    +
    +    val a_s = List[Short](1, -1, 2, -2, 32767, -32768)
    +    val b_s = List[Option[Short]](Some(1), None, None, Some(-2), None, Some(-32768))
    +    val df = a_s.zip(b_s).toDF("a_s", "b_s")
    +
    +    collectAndValidate(df, json, "integer-16bit.json")
    --- End diff --
    
    Arrow does integration testing between APIs using JSON, so there is already a validator that can compare an Arrow record batch (collected through Spark here) with a JSON file.  I inlined the JSON data per @rxin request, as opposed to generating files from data.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler , I have been working based on your branch here:
    https://github.com/BryanCutler/spark/tree/wip-toPandas_with_arrow-SPARK-13534
    
    Is this the right one?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/73871/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #68812 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/68812/consoleFull)** for PR 15821 at commit [`9191b96`](https://github.com/apache/spark/commit/9191b96cbcd307f9738d933033fd726027583475).
     * This patch **fails Python style tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #73310 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/73310/testReport)** for PR 15821 at commit [`9c8ea63`](https://github.com/apache/spark/commit/9c8ea63ccec4ceb9dd40834bca530a6265385579).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thank you for the review @rxin!  I will work on an update for the issues you brought up, and updating for for Arrow 0.3 should clean up some things and offer more type support.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/73308/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105459805
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    --- End diff --
    
    I was trying to encapsulate the usage of the Allocator to this class for now.  I'll add a method to close it here.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Should we maybe wait for https://github.com/apache/spark/pull/18443? Actually, I think there is an alternative for this - https://github.com/apache/spark/pull/18439 rather than reverting whole PR.
    
    Reverting is also an option. I hope these were considered (or I assume already considered).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105979896
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,419 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.arrow.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    --- End diff --
    
    It would be good to have a test that make sure this is the exception thrown when trying to convert an unsupported Spark type.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler 
    
    Thanks! The issue is fixed with your new update.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #68806 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/68806/consoleFull)** for PR 15821 at commit [`053e3a6`](https://github.com/apache/spark/commit/053e3a631fc802c8063b55482c701be9ee96afe3).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122931371
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,429 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark and served to a Python process.
    + */
    +private[sql] class ArrowPayload private[arrow] (payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as a type that can be served to Python.
    +   */
    +  def asPythonSerializable: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowPayload {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def apply(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowPayload = {
    +    new ArrowPayload(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    --- End diff --
    
    we do have timestamp writer, why we not support it here?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    A quick update - I'm not sure why the pip tests failed, hopefully just a fluke with the worker.  I'm waiting to retest until I can also update to Arrow 0.4, which includes a relevant bug fix and should be released any day.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #73612 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/73612/testReport)** for PR 15821 at commit [`2851cd6`](https://github.com/apache/spark/commit/2851cd6ea9e37a9fa439bc1a7510ba62ea90b110).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    retest this please


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks @cloud-fan.  I commented above on the reason for the type differences, but basically without arrow `IntegerType` and `FloatType` were getting up-converted to `int64` and `float64`.  Even though this shouldn't change any data maybe it would be good to document this change somewhere?
    
    @leifwalsh I also added a check for `concat_tables()` in case all records are filtered out and tables are None.  It will then produce the same pandas.DataFrame as without using Arrow, which has columns defined but is empty.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    jenkins retest this please


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by leifwalsh <gi...@git.apache.org>.
Github user leifwalsh commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122359928
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1648,8 +1650,30 @@ def toPandas(self):
             0    2  Alice
             1    5    Bob
             """
    -        import pandas as pd
    -        return pd.DataFrame.from_records(self.collect(), columns=self.columns)
    +        if self.sql_ctx.getConf("spark.sql.execution.arrow.enable", "false").lower() == "true":
    +            try:
    +                import pyarrow
    +                tables = self._collectAsArrow()
    +                table = pyarrow.concat_tables(tables)
    --- End diff --
    
    If tables is an empty list (e.g. if you load a dataset, filter the whole thing, and produce zero rows), `pyarrow.concat_tables` raises an exception rather than producing an empty table.  This should probably be fixed in arrow (cc @wesm) but we should be defensive here.  Probably should try to produce a `DataFrame` with the right schema but no rows if possible.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r98075624
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Arrow.scala ---
    @@ -0,0 +1,310 @@
    +/*
    +* 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
    +
    +import scala.collection.JavaConverters._
    +import scala.language.implicitConversions
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +object Arrow {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: ${dataType}")
    +    }
    +  }
    +
    +  /**
    +   * Transfer an array of InternalRow to an ArrowRecordBatch.
    +   */
    +  private[sql] def internalRowsToArrowRecordBatch(
    +      rows: Array[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +    val fieldAndBuf = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      internalRowToArrowBuf(rows, ordinal, field, allocator)
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1.flatten
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val recordBatch = new ArrowRecordBatch(rows.length,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Write a Field from array of InternalRow to an ArrowBuf.
    +   */
    +  private def internalRowToArrowBuf(
    +      rows: Array[InternalRow],
    +      ordinal: Int,
    +      field: StructField,
    +      allocator: RootAllocator): (Array[ArrowFieldNode], Array[ArrowBuf]) = {
    +    val numOfRows = rows.length
    +    val columnWriter = ColumnWriter(allocator, field.dataType)
    +    columnWriter.init(numOfRows)
    +    var index = 0
    +
    +    while(index < numOfRows) {
    +      val row = rows(index)
    +      if (row.isNullAt(ordinal)) {
    +        columnWriter.writeNull()
    +      } else {
    +        columnWriter.write(row, ordinal)
    +      }
    +      index += 1
    +    }
    +
    +    val (arrowFieldNodes, arrowBufs) = columnWriter.finish()
    +    (arrowFieldNodes.toArray, arrowBufs.toArray)
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(initialSize: Int): Unit
    +  def writeNull(): Unit
    +  def write(row: InternalRow, ordinal: Int): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(protected val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  protected def valueVector: BaseDataValueVector
    +  protected def valueMutator: BaseMutator
    +
    +  protected def setNull(): Unit
    +  protected def setValue(row: InternalRow, ordinal: Int): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(initialSize: Int): Unit = {
    +    valueVector.allocateNew()
    +  }
    +
    +  override def writeNull(): Unit = {
    +    setNull()
    +    nullCount += 1
    +    count += 1
    +  }
    +
    +  override def write(row: InternalRow, ordinal: Int): Unit = {
    +    setValue(row, ordinal)
    +    count += 1
    +  }
    +
    +  override def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers: Seq[ArrowBuf] = valueVector.getBuffers(true)
    +    (List(fieldNode), valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    +
    +  override protected val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", allocator)
    +  override protected val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, bool2int(row.getBoolean(ordinal)))
    +}
    +
    +private[sql] class ShortColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", allocator)
    +  override protected val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[sql] class IntegerColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", allocator)
    +  override protected val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[sql] class LongColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", allocator)
    +  override protected val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[sql] class FloatColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", allocator)
    +  override protected val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[sql] class DoubleColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", allocator)
    +  override protected val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[sql] class ByteColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", allocator)
    +  override protected val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[sql] class UTF8StringColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    +  override protected val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    val bytes = row.getUTF8String(ordinal).getBytes
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class BinaryColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    --- End diff --
    
    `"BinaryValue"`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r103052508
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1597,11 +1607,14 @@ def toDF(self, *cols):
             return DataFrame(jdf, self.sql_ctx)
     
         @since(1.3)
    -    def toPandas(self):
    +    def toPandas(self, useArrow=False):
             """Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.
     
             This is only available if Pandas is installed and available.
     
    +        :param useArrow: Make use of Apache Arrow for conversion, pyarrow must be installed
    --- End diff --
    
    For now we should probably have this as experimental, and also make clear what subset of data types are supported here (or do we expect to support all of the data types)?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #73366 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/73366/testReport)** for PR 15821 at commit [`9c8ea63`](https://github.com/apache/spark/commit/9c8ea63ccec4ceb9dd40834bca530a6265385579).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r123124184
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,429 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark and served to a Python process.
    + */
    +private[sql] class ArrowPayload private[arrow] (payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as a type that can be served to Python.
    +   */
    +  def asPythonSerializable: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowPayload {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def apply(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowPayload = {
    +    new ArrowPayload(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload. Limit ArrowRecordBatch size in ArrowPayload
    +   * by setting maxRecordsPerBatch or use 0 to fully consume rowIter.
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      maxRecordsPerBatch: Int): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator, maxRecordsPerBatch)
    +        ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch, stopping when rowIter is consumed
    +   * or the number of records in the batch equals maxRecordsInBatch.  If maxRecordsPerBatch is 0,
    +   * then rowIter will be fully consumed.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator,
    +      maxRecordsPerBatch: Int = 0): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(field.dataType, ordinal, allocator).init()
    --- End diff --
    
    There are a couple ways to write an `ArrowRecordBatch` in Java.  I think you are referring using the class `VectorSchemaRoot`.  That way requires an additional step of using a `VectorUnloader`, where the method used here creates the batch directly from the data buffers, so I believe it's the most optimal but I would need to check a little more to be sure.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/77032/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105459342
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    --- End diff --
    
    Yes, you're right.  What are your thoughts on making the Arrow version of this class public in a util package?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by MaheshIBM <gi...@git.apache.org>.
Github user MaheshIBM commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    This does not seem like a timeout issue, the certificate CN and the what is used as the hostname are not matching. So clearly the client downloads the certificate but is not able to verify (no timeout). If anything it may be possible to configure the code/command to ignore ssl cert errors. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler , there appears to be some stability issue in the current code. I am tried to repeated collect a DataFrame as Arrow BatchRecord in spark-shell and discovered that executors start to fail after a while.
    
    ![image](https://cloud.githubusercontent.com/assets/793516/24308213/7cd46daa-109d-11e7-8824-3255b9690cf2.png)
    
    I looked at one failed executor, it appeared to have been killed by mesos because of exceeding memory limit. I suspect there are some kind of memory leak.



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks for the review @viirya, I'm working on an update but want to be sure the python tests for arrow get run before I push.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r115527041
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,396 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark
    + */
    +private[sql] class ArrowPayload(val batchBytes: Array[Byte]) extends Serializable {
    +
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(batchBytes, allocator)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    --- End diff --
    
    The data size of an RDD partition can be large, and it's dangerous to exhaust the `rowIter` and load the whole RDD partition into memory. Shall we have something like a batch size threshold? IIRC parquet writer has something similar.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112365773
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1635,21 +1636,49 @@ def toDF(self, *cols):
             return DataFrame(jdf, self.sql_ctx)
     
         @since(1.3)
    -    def toPandas(self):
    -        """Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.
    +    def toPandas(self, useArrow=False):
    --- End diff --
    
    rather than having a flag here, I'd add a SQLConf to control this.



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r109547685
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2747,6 +2747,17 @@ class Dataset[T] private[sql](
         }
       }
     
    +  /**
    +   * Collect a Dataset as ArrowPayload byte arrays and serve to PySpark.
    +   */
    +  private[sql] def collectAsArrowToPython(): Int = {
    +    val payloadRdd = toArrowPayloadBytes()
    +    val payloadByteArrays = payloadRdd.collect()
    --- End diff --
    
    The conversion going on in `table.to_pandas()` is working on an already loaded table, but the Arrow Readers can read multiple batches of data and output a single table.  The issue is that pyspark serializers expects the data to be "framed" with the length so I can not send that directly to the Arrow Reader.  Even with `toLocalIteratorAndServer` I would have to read each batch of data on the driver, then combine.  It would be possible to write the "framed" stream another stream without the lengths, where it can then be then be read into a single table - but I'm not sure if that added complexity is worth it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/73355/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    That sounds great @icexelloss , there are no outstanding issues that I know of except for data type support.  Yes, we are working on date and timestamp support that should be in the upcoming Arrow 0.3 release.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    On a personal note, those benchmarks certainly look very exciting (<3 max of with arrow less than min of without arrow) :)
    
    It certainly seems it would probably be worth the review bandwidth to start looking this over but since this is pretty big and adds a new dependency this could take awhile to move forwards.
    
    It would be great to hear what the other Python focused committers (maybe @davies ?) think of this approach :)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @rxin I have updated this to use Arrow 0.3 and addressed your other comments, could you please give it another look when possible?  Following up on a couple issues:
    
    >Use SQLConf rather than a parameter for toPandas.
    
    I removed this flag and used the conf "spark.sql.execution.arrow.enable" which defaults to "false", and also added "spark.sql.execution.arrow.maxRecordsPerBatch" to limit memory usage, still under discussion.
    
    >rather than defining the json using objects and serialize them, can we just put the json as a string inline? that'd be much easier to inspect ...
    
    Here is a sample of a simple JSON file the tests use.  It contains metadata and validity array in addition to the raw data, and ends up being a fairly large string which is why I opt for generating the file instead.
    
    ```
    {
        "schema": {
            "fields": [
                {
                    "name": "nullable_int",
                    "type": {"name": "int", "isSigned": true, "bitWidth": 32},
                    "nullable": true,
                    "children": [],
                    "typeLayout": {
                        "vectors": [
                            {"type": "VALIDITY", "typeBitWidth": 1},
                            {"type": "DATA", "typeBitWidth": 32}
                        ]
                    }
                }
            ]
        },
    
        "batches": [
            {
                "count": 6,
                "columns": [
                    {
                        "name": "nullable_int",
                        "count": 6,
                        "VALIDITY": [1, 0, 0, 1, 0, 1],
                        "DATA": [1, -1, 2, -2, 2147483647, -2147483648]
                    }
                ]
            }
        ]
    }
    ```
    
    >Handle failure gracefully if arrow is not installed (or somehow package it with Spark?)
    
    I just want to make sure I took this the right way.. It should stop execution and print out an error with a clear message. Not log a message then continue execution without using pyarrow, correct?



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r106237765
  
    --- Diff: python/pyspark/sql/dataframe.py ---
    @@ -1597,21 +1598,46 @@ def toDF(self, *cols):
             return DataFrame(jdf, self.sql_ctx)
     
         @since(1.3)
    -    def toPandas(self):
    -        """Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.
    +    def toPandas(self, useArrow=False):
    +        """
    +        Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.
     
             This is only available if Pandas is installed and available.
     
    +        :param useArrow: Make use of Apache Arrow for conversion, pyarrow must be installed
    +            and available on the calling Python process (Experimental).
    +
             .. note:: This method should only be used if the resulting Pandas's DataFrame is expected
                 to be small, as all the data is loaded into the driver's memory.
     
    +        .. note:: Using pyarrow is experimental and currently supports the following data types:
    +            StringType, BinaryType, BooleanType, DoubleType, FloatType, ByteType, IntegerType,
    +            LongType, ShortType
    +
             >>> df.toPandas()  # doctest: +SKIP
                age   name
             0    2  Alice
             1    5    Bob
             """
    -        import pandas as pd
    -        return pd.DataFrame.from_records(self.collect(), columns=self.columns)
    +        if useArrow:
    +            from pyarrow.table import concat_tables
    +            tables = self._collectAsArrow()
    +            table = concat_tables(tables)
    +            return table.to_pandas()
    +        else:
    +            import pandas as pd
    +            return pd.DataFrame.from_records(self.collect(), columns=self.columns)
    +
    +    def _collectAsArrow(self):
    --- End diff --
    
    This is done on the Scala tests, the error that is thrown is:
    ```
    java.lang.UnsupportedOperationException: Unsupported data type: ArrayType(IntegerType,false)
    	at org.apache.spark.sql.ColumnWriter$.apply(ArrowConverters.scala:416)
    	at org.apache.spark.sql.ArrowConverters$$anonfun$1.apply(ArrowConverters.scala:162)
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Updating the setup seems like a good follow up PR yes. The test hack I think might make sense to keep until the Jenkins refactoring.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r98076128
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Arrow.scala ---
    @@ -0,0 +1,310 @@
    +/*
    +* 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
    +
    +import scala.collection.JavaConverters._
    +import scala.language.implicitConversions
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +object Arrow {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: ${dataType}")
    +    }
    +  }
    +
    +  /**
    +   * Transfer an array of InternalRow to an ArrowRecordBatch.
    +   */
    +  private[sql] def internalRowsToArrowRecordBatch(
    +      rows: Array[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +    val fieldAndBuf = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      internalRowToArrowBuf(rows, ordinal, field, allocator)
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1.flatten
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val recordBatch = new ArrowRecordBatch(rows.length,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Write a Field from array of InternalRow to an ArrowBuf.
    +   */
    +  private def internalRowToArrowBuf(
    +      rows: Array[InternalRow],
    +      ordinal: Int,
    +      field: StructField,
    +      allocator: RootAllocator): (Array[ArrowFieldNode], Array[ArrowBuf]) = {
    +    val numOfRows = rows.length
    +    val columnWriter = ColumnWriter(allocator, field.dataType)
    +    columnWriter.init(numOfRows)
    +    var index = 0
    +
    +    while(index < numOfRows) {
    +      val row = rows(index)
    +      if (row.isNullAt(ordinal)) {
    +        columnWriter.writeNull()
    +      } else {
    +        columnWriter.write(row, ordinal)
    +      }
    +      index += 1
    +    }
    +
    +    val (arrowFieldNodes, arrowBufs) = columnWriter.finish()
    +    (arrowFieldNodes.toArray, arrowBufs.toArray)
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(initialSize: Int): Unit
    +  def writeNull(): Unit
    +  def write(row: InternalRow, ordinal: Int): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(protected val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  protected def valueVector: BaseDataValueVector
    +  protected def valueMutator: BaseMutator
    +
    +  protected def setNull(): Unit
    +  protected def setValue(row: InternalRow, ordinal: Int): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(initialSize: Int): Unit = {
    +    valueVector.allocateNew()
    +  }
    +
    +  override def writeNull(): Unit = {
    +    setNull()
    +    nullCount += 1
    +    count += 1
    +  }
    +
    +  override def write(row: InternalRow, ordinal: Int): Unit = {
    +    setValue(row, ordinal)
    +    count += 1
    +  }
    +
    +  override def finish(): (Seq[ArrowFieldNode], Seq[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers: Seq[ArrowBuf] = valueVector.getBuffers(true)
    +    (List(fieldNode), valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    +
    +  override protected val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", allocator)
    +  override protected val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, bool2int(row.getBoolean(ordinal)))
    +}
    +
    +private[sql] class ShortColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", allocator)
    +  override protected val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[sql] class IntegerColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", allocator)
    +  override protected val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[sql] class LongColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", allocator)
    +  override protected val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[sql] class FloatColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", allocator)
    +  override protected val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[sql] class DoubleColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", allocator)
    +  override protected val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[sql] class ByteColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", allocator)
    +  override protected val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[sql] class UTF8StringColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    +  override protected val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    val bytes = row.getUTF8String(ordinal).getBytes
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class BinaryColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableVarBinaryVector
    +    = new NullableVarBinaryVector("UTF8StringValue", allocator)
    +  override protected val valueMutator: NullableVarBinaryVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    val bytes = row.getBinary(ordinal)
    +    valueMutator.setSafe(count, bytes, 0, bytes.length)
    +  }
    +}
    +
    +private[sql] class DateColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableDateVector
    +    = new NullableDateVector("DateValue", allocator)
    +  override protected val valueMutator: NullableDateVector#Mutator = valueVector.getMutator
    +
    +  override protected def setNull(): Unit = valueMutator.setNull(count)
    +  override protected def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    valueMutator.setSafe(count, row.getInt(ordinal).toLong * 24 * 3600 * 1000)
    +  }
    +}
    +
    +private[sql] class TimeStampColumnWriter(allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(allocator) {
    +  override protected val valueVector: NullableTimeStampVector
    +    = new NullableTimeStampVector("TimeStampValue", allocator)
    +  override protected val valueMutator: NullableTimeStampVector#Mutator = valueVector.getMutator
    +
    +  override protected def setNull(): Unit = valueMutator.setNull(count)
    +
    +  override protected def setValue(row: InternalRow, ordinal: Int): Unit = {
    +    valueMutator.setSafe(count, row.getLong(ordinal) / 1000)
    --- End diff --
    
    Can you add a `TODO` that we should migrate to microsecond timestamps once ARROW-477 is in? 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r113600062
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    --- End diff --
    
    No, I think this should be changed a little.  `ArrowPayload` is meant to encapsulate Arrow classes from the rest of Spark and wrap Arrow data to extend `serializable` to allow an `RDD[ArrowPayload]`.  I'll push an update that will clean this up.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r103047178
  
    --- Diff: python/pyspark/serializers.py ---
    @@ -182,6 +182,23 @@ def loads(self, obj):
             raise NotImplementedError
     
     
    +class ArrowSerializer(FramedSerializer):
    +    """
    +    Serializes an Arrow stream.
    +    """
    +
    +    def dumps(self, obj):
    +        raise NotImplementedError
    +
    +    def loads(self, obj):
    +        from pyarrow import FileReader, BufferReader
    --- End diff --
    
    We should probably fail semi-gracefully if pyarrow isn't installed (e.g. give an error message which tells people how to install it).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112370321
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    --- End diff --
    
    why even have this function? just change the signature of ArrowConverters.internalRowIterToArrowBatch and call that directly. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #68954 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/68954/consoleFull)** for PR 15821 at commit [`9191b96`](https://github.com/apache/spark/commit/9191b96cbcd307f9738d933033fd726027583475).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r115556273
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,396 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark
    + */
    +private[sql] class ArrowPayload(val batchBytes: Array[Byte]) extends Serializable {
    --- End diff --
    
    The definition of the payload internal storage is a little vague on purpose because it could change and store more than one batch, or in a different format.  I'll add some more comments so that it is a little more clear what the input/output to an `ArrowPayload` is.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #76710 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/76710/testReport)** for PR 15821 at commit [`934c147`](https://github.com/apache/spark/commit/934c147cf41752d382ee6ae304ed18ca5bed73e4).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112376037
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +
    +    // Iterate over payload batches to write each one, ensure all batches get closed
    +    var batch: ArrowRecordBatch = null
    +    Utils.tryWithSafeFinallyAndFailureCallbacks {
    +      while (payload.hasNext) {
    +        batch = payload.next()
    +        writer.writeRecordBatch(batch)
    +        batch.close()
    +      }
    +    }(catchBlock = {
    +      Option(batch).foreach(_.close())
    +      payload.foreach(_.close())
    +    }, finallyBlock = writer.close())
    +
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    --- End diff --
    
    just inline this


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Hi @rxin, this has been upgraded to Arrow 0.4 and all tests have passed.  Scala unit tests have been changed to inline JSON data from your request.  Please take another look when possible, thanks!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #75779 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/75779/testReport)** for PR 15821 at commit [`a0483b8`](https://github.com/apache/spark/commit/a0483b8990a8113305a63c3f486df6e835a8ed32).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r108834618
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala ---
    @@ -2828,4 +2839,16 @@ class Dataset[T] private[sql](
           Dataset(sparkSession, logicalPlan)
         }
       }
    +
    +  /** Convert to an RDD of ArrowPayload byte arrays */
    +  private[sql] def toArrowPayloadBytes(): RDD[Array[Byte]] = {
    +    val schema_captured = this.schema
    +    queryExecution.toRdd.mapPartitionsInternal { iter =>
    +      val converter = new ArrowConverters
    +      val payload = converter.interalRowIterToPayload(iter, schema_captured)
    +      val payloadBytes = ArrowConverters.payloadToByteArray(payload, schema_captured)
    --- End diff --
    
    Do you think we need a dedicated config for it? Or maybe a constant like 1000 (rows)?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122925584
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -2473,6 +2482,76 @@ def range_frame_match():
     
             importlib.reload(window)
     
    +
    +@unittest.skipIf(not _have_arrow, "Arrow not installed")
    +class ArrowTests(ReusedPySparkTestCase):
    +
    +    @classmethod
    +    def setUpClass(cls):
    +        ReusedPySparkTestCase.setUpClass()
    +        cls.spark = SparkSession(cls.sc)
    +        cls.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        cls.schema = StructType([
    +            StructField("1_str_t", StringType(), True),
    +            StructField("2_int_t", IntegerType(), True),
    +            StructField("3_long_t", LongType(), True),
    +            StructField("4_float_t", FloatType(), True),
    +            StructField("5_double_t", DoubleType(), True)])
    +        cls.data = [("a", 1, 10, 0.2, 2.0),
    +                    ("b", 2, 20, 0.4, 4.0),
    +                    ("c", 3, 30, 0.8, 6.0)]
    +
    +    def assertFramesEqual(self, df_with_arrow, df_without):
    +        msg = ("DataFrame from Arrow is not equal" +
    +               ("\n\nWith Arrow:\n%s\n%s" % (df_with_arrow, df_with_arrow.dtypes)) +
    +               ("\n\nWithout:\n%s\n%s" % (df_without, df_without.dtypes)))
    +        self.assertTrue(df_without.equals(df_with_arrow), msg=msg)
    +
    +    def test_unsupported_datatype(self):
    +        schema = StructType([StructField("array", ArrayType(IntegerType(), False), True)])
    +        df = self.spark.createDataFrame([([1, 2, 3],)], schema=schema)
    +        with QuietTest(self.sc):
    +            self.assertRaises(Exception, lambda: df.toPandas())
    +
    +    def test_null_conversion(self):
    +        df_null = self.spark.createDataFrame([tuple([None for _ in range(len(self.data[0]))])] +
    +                                             self.data)
    +        pdf = df_null.toPandas()
    +        null_counts = pdf.isnull().sum().tolist()
    +        self.assertTrue(all([c == 1 for c in null_counts]))
    +
    +    def test_toPandas_arrow_toggle(self):
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        # NOTE - toPandas() without pyarrow will infer standard python data types
    --- End diff --
    
    oh, do you mean with the arrow optimization, we will have a different result for int and float?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/73310/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks for the review @wesm!  Those are good ideas, I'll work on an update to this.  As for the packaging conflicts, I had to add exclusions for `com.fasterxml.jackson.core:jackson-annotations`, ` jackson-databind` and `org.slf4j:log4j-over-slf4j`.  These don't seem too critical to me and it was a while ago so I'll double check if they are still a problem.



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    You must add the conda-forge channel; I also recommend increasing the timeout for conda which helps make builds more stable, see:
    
    https://github.com/apache/arrow/blob/master/ci/travis_install_conda.sh#L37
    
    Also, I recommend updating to pyarrow 0.4.1 as soon as practical (only bug fixes)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r98074725
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/Arrow.scala ---
    @@ -0,0 +1,310 @@
    +/*
    +* 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
    +
    +import scala.collection.JavaConverters._
    +import scala.language.implicitConversions
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +object Arrow {
    --- End diff --
    
    Perhaps a more descriptive name, like `ArrowConverters`? 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by wesm <gi...@git.apache.org>.
Github user wesm commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @srowen @cloud-fan adding the steps from https://github.com/apache/arrow/blob/master/ci/travis_install_conda.sh that update conda to the latest version and increasing the SSL timeout should fix the problem. If it does not I can take a closer look


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #68954 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/68954/consoleFull)** for PR 15821 at commit [`9191b96`](https://github.com/apache/spark/commit/9191b96cbcd307f9738d933033fd726027583475).
     * This patch **fails Python style tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Hi @wesm and @icexelloss , that sounds good on our end.  @yinxusen has been working on validating some basic conversion so far, but everything is still very preliminary so it would be great to work with you guys.  I'll setup a new integration branch and ping you all when ready.
    
    > Related to this we'll also want to be able to precisely instrument and benchmark the Dataset <-> Arrow conversion -- @icexelloss suggested might be able to push down the conversion into the executors instead of doing all the work in the driver, but I'm not sure how feasible that is
    
    We were thinking about that too, as it would be more ideal.  For simplicity we decided to first do the conversion on the driver side, which should hopefully still show a performance increase, then follow up with some work to better optimize it. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105461100
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    --- End diff --
    
    trying to avoid any wrapping of the code that might cause overhead.  I believe a for loop is translated to a foreach and wraps the code. It might not make a difference but just being extra cautious!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    > Parallelizing the record batch conversion and streaming it to Python would be another significant perf win. 
    
    Right, I should have also mentioned that this PR takes a simplistic approach and collects rows to the driver, where all the conversion is done.  Offloading this to the executors should boost the performance more.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @icexelloss did you checkout this PR or is this from the arrow-integration branch?  I recently fixed a memory leak and it has been working on long repeated runs since, but I only had the fix here.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by felixcheung <gi...@git.apache.org>.
Github user felixcheung commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    it's because of this
    ```
    .SSL verification error: hostname 'conda.binstar.org' doesn't match either of 'anaconda.com', 'anacondacloud.com', 'anacondacloud.org', 'binstar.org', 'wakari.io'
    .SSL verification error: hostname 'conda.binstar.org' doesn't match either of 'anaconda.com', 'anacondacloud.com', 'anacondacloud.org', 'binstar.org', 'wakari.io'
    ...
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @cloudfan could you wait until the latest test from #18443 finishes?  It
    should be done soon, but it's failed twice so far due to unrelated errors.
    If it fails a third time, then I agree on reverting for now to not delay
    other PRs any further.
    
    On Jun 27, 2017 11:31 PM, "Wenchen Fan" <no...@github.com> wrote:
    
    > I'm against #18439 <https://github.com/apache/spark/pull/18439> , I'd
    > rather revert this and fix it later than installing packages without SSL.
    >
    > —
    > You are receiving this because you were mentioned.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15821#issuecomment-311573180>, or mute
    > the thread
    > <https://github.com/notifications/unsubscribe-auth/AEUwdUr5y-dP7ZyPQobMHPwpwPZjn1RIks5sIfi0gaJpZM4KtGBc>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks @cloud-fan and all others who helped out with this PR or reviewed!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by holdenk <gi...@git.apache.org>.
Github user holdenk commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Great, thanks @shaneknapp . @BryanCutler I've got a webinar and if you don't have a chance to change the tests around until after I'm done teaching I'll do it, but if your flight lands first then go for it :)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121750946
  
    --- Diff: pom.xml ---
    @@ -1871,6 +1872,25 @@
             <artifactId>paranamer</artifactId>
             <version>${paranamer.version}</version>
           </dependency>
    +      <dependency>
    +        <groupId>org.apache.arrow</groupId>
    --- End diff --
    
    This is just the dependency management section in the main pom.  The only actual dependency is in spark-sql.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r108579124
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -56,6 +56,15 @@
     from pyspark.sql.utils import AnalysisException, ParseException, IllegalArgumentException
     
     
    +_have_arrow = False
    +try:
    +    import pyarrow
    +    _have_arrow = True
    --- End diff --
    
    We should do similar thing above when using Arrow required feature.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r123654149
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -2620,6 +2629,74 @@ def range_frame_match():
     
             importlib.reload(window)
     
    +
    +@unittest.skipIf(not _have_arrow, "Arrow not installed")
    +class ArrowTests(ReusedPySparkTestCase):
    +
    +    @classmethod
    +    def setUpClass(cls):
    +        ReusedPySparkTestCase.setUpClass()
    +        cls.spark = SparkSession(cls.sc)
    +        cls.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        cls.schema = StructType([
    +            StructField("1_str_t", StringType(), True),
    +            StructField("2_int_t", IntegerType(), True),
    +            StructField("3_long_t", LongType(), True),
    +            StructField("4_float_t", FloatType(), True),
    +            StructField("5_double_t", DoubleType(), True)])
    +        cls.data = [("a", 1, 10, 0.2, 2.0),
    +                    ("b", 2, 20, 0.4, 4.0),
    +                    ("c", 3, 30, 0.8, 6.0)]
    +
    +    def assertFramesEqual(self, df_with_arrow, df_without):
    +        msg = ("DataFrame from Arrow is not equal" +
    +               ("\n\nWith Arrow:\n%s\n%s" % (df_with_arrow, df_with_arrow.dtypes)) +
    +               ("\n\nWithout:\n%s\n%s" % (df_without, df_without.dtypes)))
    +        self.assertTrue(df_without.equals(df_with_arrow), msg=msg)
    +
    +    def test_unsupported_datatype(self):
    +        schema = StructType([StructField("array", ArrayType(IntegerType(), False), True)])
    +        df = self.spark.createDataFrame([([1, 2, 3],)], schema=schema)
    +        with QuietTest(self.sc):
    +            self.assertRaises(Exception, lambda: df.toPandas())
    +
    +    def test_null_conversion(self):
    +        df_null = self.spark.createDataFrame([tuple([None for _ in range(len(self.data[0]))])] +
    +                                             self.data)
    +        pdf = df_null.toPandas()
    +        null_counts = pdf.isnull().sum().tolist()
    +        self.assertTrue(all([c == 1 for c in null_counts]))
    +
    +    def test_toPandas_arrow_toggle(self):
    +        df = self.spark.createDataFrame(self.data, schema=self.schema)
    +        self.spark.conf.set("spark.sql.execution.arrow.enable", "false")
    +        pdf = df.toPandas()
    +        self.spark.conf.set("spark.sql.execution.arrow.enable", "true")
    +        pdf_arrow = df.toPandas()
    +        self.assertFramesEqual(pdf_arrow, pdf)
    +
    +    def test_pandas_round_trip(self):
    +        import pandas as pd
    +        import numpy as np
    +        data_dict = {}
    +        for j, name in enumerate(self.schema.names):
    +            data_dict[name] = [self.data[i][j] for i in range(len(self.data))]
    +        # need to convert these to numpy types first
    --- End diff --
    
    is this still needed?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r112370906
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    --- End diff --
    
    this is only used once? use private.



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r122326108
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowConverters.scala ---
    @@ -0,0 +1,423 @@
    +/*
    +* Licensed to the Apache Software Foundation (ASF) under one or more
    +* contributor license agreements.  See the NOTICE file distributed with
    +* this work for additional information regarding copyright ownership.
    +* The ASF licenses this file to You under the Apache License, Version 2.0
    +* (the "License"); you may not use this file except in compliance with
    +* the License.  You may obtain a copy of the License at
    +*
    +*    http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*/
    +
    +package org.apache.spark.sql.execution.arrow
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.channels.Channels
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file._
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.FloatingPointPrecision
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
    +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * Store Arrow data in a form that can be serialized by Spark.
    + */
    +private[sql] class ArrowPayload(payload: Array[Byte]) extends Serializable {
    +
    +  /**
    +   * Create an ArrowPayload from an ArrowRecordBatch and Spark schema.
    +   */
    +  def this(batch: ArrowRecordBatch, schema: StructType, allocator: BufferAllocator) = {
    +    this(ArrowConverters.batchToByteArray(batch, schema, allocator))
    +  }
    +
    +  /**
    +   * Convert the ArrowPayload to an ArrowRecordBatch.
    +   */
    +  def loadBatch(allocator: BufferAllocator): ArrowRecordBatch = {
    +    ArrowConverters.byteArrayToBatch(payload, allocator)
    +  }
    +
    +  /**
    +   * Get the ArrowPayload as an Array[Byte].
    +   */
    +  def toByteArray: Array[Byte] = payload
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark DataType to ArrowType.
    +   */
    +  private[arrow] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[arrow] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Maps Iterator from InternalRow to ArrowPayload. Limit ArrowRecordBatch size in ArrowPayload
    +   * by setting maxRecordsPerBatch or use 0 to fully consume rowIter.
    +   */
    +  private[sql] def toPayloadIterator(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      maxRecordsPerBatch: Int): Iterator[ArrowPayload] = {
    +    new Iterator[ArrowPayload] {
    +      private val _allocator = new RootAllocator(Long.MaxValue)
    +      private var _nextPayload = if (rowIter.nonEmpty) convert() else null
    +
    +      override def hasNext: Boolean = _nextPayload != null
    +
    +      override def next(): ArrowPayload = {
    +        val obj = _nextPayload
    +        if (hasNext) {
    +          if (rowIter.hasNext) {
    +            _nextPayload = convert()
    +          } else {
    +            _allocator.close()
    +            _nextPayload = null
    +          }
    +        }
    +        obj
    +      }
    +
    +      private def convert(): ArrowPayload = {
    +        val batch = internalRowIterToArrowBatch(rowIter, schema, _allocator, maxRecordsPerBatch)
    +        new ArrowPayload(batch, schema, _allocator)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch, stopping when rowIter is consumed
    +   * or the number of records in the batch equals maxRecordsInBatch.  If maxRecordsPerBatch is 0,
    +   * then rowIter will be fully consumed.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: BufferAllocator,
    +      maxRecordsPerBatch: Int = 0): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(field.dataType, ordinal, allocator).init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    var recordsInBatch = 0
    +    while (rowIter.hasNext && (maxRecordsPerBatch <= 0 || recordsInBatch < maxRecordsPerBatch)) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +      recordsInBatch += 1
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert an ArrowRecordBatch to a byte array and close batch to release resources. Once closed,
    +   * the batch can no longer be used.
    +   */
    +  private[arrow] def batchToByteArray(
    +      batch: ArrowRecordBatch,
    +      schema: StructType,
    +      allocator: BufferAllocator): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val root = VectorSchemaRoot.create(arrowSchema, allocator)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowFileWriter(root, null, Channels.newChannel(out))
    +
    +    // Write a batch to byte stream, ensure the batch, allocator and writer are closed
    +    Utils.tryWithSafeFinally {
    +      val loader = new VectorLoader(root)
    +      loader.load(batch)
    +      writer.writeBatch()  // writeBatch can throw IOException
    +    } {
    +      batch.close()
    +      root.close()
    +      writer.close()
    +    }
    +    out.toByteArray
    +  }
    +
    +  /**
    +   * Convert a byte array to an ArrowRecordBatch.
    +   */
    +  private[arrow] def byteArrayToBatch(
    +      batchBytes: Array[Byte],
    +      allocator: BufferAllocator): ArrowRecordBatch = {
    +    val in = new ByteArrayReadableSeekableByteChannel(batchBytes)
    +    val reader = new ArrowFileReader(in, allocator)
    +
    +    // Read a batch from a byte stream, ensure the reader is closed
    +    Utils.tryWithSafeFinally {
    +      val root = reader.getVectorSchemaRoot  // throws IOException
    +      val unloader = new VectorUnloader(root)
    +      reader.loadNextBatch()  // throws IOException
    +      unloader.getRecordBatch
    +    } {
    +      reader.close()
    +    }
    +  }
    +}
    +
    +/**
    + * Interface for writing InternalRows to Arrow Buffers.
    + */
    +private[arrow] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[arrow] abstract class PrimitiveColumnWriter(val ordinal: Int)
    +  extends ColumnWriter {
    +
    +  def getFieldType(dtype: ArrowType): FieldType = FieldType.nullable(dtype)
    +
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[arrow] class BooleanColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, if (row.getBoolean(ordinal)) 1 else 0 )
    +}
    +
    +private[arrow] class ShortColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableSmallIntVector
    +    = new NullableSmallIntVector("ShortValue", getFieldType(dtype: ArrowType), allocator)
    +  override val valueMutator: NullableSmallIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getShort(ordinal))
    +}
    +
    +private[arrow] class IntegerColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableIntVector
    +    = new NullableIntVector("IntValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getInt(ordinal))
    +}
    +
    +private[arrow] class LongColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableBigIntVector
    +    = new NullableBigIntVector("LongValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableBigIntVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getLong(ordinal))
    +}
    +
    +private[arrow] class FloatColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat4Vector
    +    = new NullableFloat4Vector("FloatValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat4Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getFloat(ordinal))
    +}
    +
    +private[arrow] class DoubleColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableFloat8Vector
    +    = new NullableFloat8Vector("DoubleValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableFloat8Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getDouble(ordinal))
    +}
    +
    +private[arrow] class ByteColumnWriter(dtype: ArrowType, ordinal: Int, allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableUInt1Vector
    +    = new NullableUInt1Vector("ByteValue", getFieldType(dtype), allocator)
    +  override val valueMutator: NullableUInt1Vector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    +  override def setValue(row: InternalRow): Unit
    +    = valueMutator.setSafe(count, row.getByte(ordinal))
    +}
    +
    +private[arrow] class UTF8StringColumnWriter(
    +    dtype: ArrowType,
    +    ordinal: Int,
    +    allocator: BufferAllocator)
    +  extends PrimitiveColumnWriter(ordinal) {
    +  override val valueVector: NullableVarBinaryVector
    --- End diff --
    
    There might have been a reason when I started but I can't recall.  The data type of the Arrow field is UTF8 and VarBinaryVector is pretty much equivalent to VarCharVector storage, so it has been working fine.  It is better to use NullableVarCharVector though, and it seems to work fine.  I'll update this.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #78469 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/78469/testReport)** for PR 15821 at commit [`44d7a2a`](https://github.com/apache/spark/commit/44d7a2a3fedb4f4bec167d763d0df3d6448bbe49).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by icexelloss <gi...@git.apache.org>.
Github user icexelloss commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    @BryanCutler
    
    I think this patch is in a good shape that I want to release this code internally in Two Sigma for beta users.
    
    My understanding is support for timestamp and date is not available until arrow 0.3, is that right? 
    
    Also, are there any unresolved issues that you know of?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r113600390
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,432 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.Utils
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * TODO: This is available in arrow-vector now with ARROW-615, to be included in 0.2.1 release
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  /**
    +   * Iterate over the rows and convert to an ArrowPayload, using RootAllocator from this class
    +   */
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, _allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  /**
    +   * Read an Array of Arrow Record batches as byte Arrays into an ArrowPayload, using
    +   * RootAllocator from this class
    +   */
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +
    +  /**
    +   * Call when done using this converter, will close RootAllocator so any ArrowBuffers should be
    +   * closed first
    +   */
    +  def close(): Unit = {
    +    _allocator.close()
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      // TODO: Enable Date and Timestamp type with Arrow 0.3
    +      // case DateType => ArrowType.Date.INSTANCE
    +      // case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and convert to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val (fieldNodes, bufferArrays) = columnWriters.map(_.finish()).unzip
    +    val buffers = bufferArrays.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +
    +    // Iterate over payload batches to write each one, ensure all batches get closed
    +    var batch: ArrowRecordBatch = null
    +    Utils.tryWithSafeFinallyAndFailureCallbacks {
    +      while (payload.hasNext) {
    +        batch = payload.next()
    +        writer.writeRecordBatch(batch)
    +        batch.close()
    +      }
    +    }(catchBlock = {
    +      Option(batch).foreach(_.close())
    +      payload.foreach(_.close())
    +    }, finallyBlock = writer.close())
    +
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    --- End diff --
    
    Yes, but unfortunately it needs to call `valueMutator.setNull()` that is only a member of the concrete Mutator class, so I can't abstract that out. I think on the arrow side it could be defined as an interface and then I could clean it up here.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by shaneknapp <gi...@git.apache.org>.
Github user shaneknapp commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    btw, do we want pyarrow-0.4.0 or -0.4.1?  i'm assuming the latter based on https://github.com/apache/spark/pull/15821#issuecomment-310905209


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    I believe the pointer is the right place up to my knowledge, via ... 
    
    https://github.com/apache/spark/blob/e44697606f429b01808c1a22cb44cb5b89585c5c/dev/run-tests#L23 ->
    https://github.com/apache/spark/blob/e44697606f429b01808c1a22cb44cb5b89585c5c/dev/run-tests.py#L609 ->
    https://github.com/apache/spark/blob/e44697606f429b01808c1a22cb44cb5b89585c5c/dev/run-tests.py#L458 ->
    https://github.com/apache/spark/blob/e44697606f429b01808c1a22cb44cb5b89585c5c/dev/run-pip-tests#L78-L87
    
    and assuming from the logs provided above.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by BryanCutler <gi...@git.apache.org>.
Github user BryanCutler commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Thanks @mariusvniekerk, as @holdenk said we are going to try to get something basic working first and after we show some performance improvement, we can follow up with more things


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/78469/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r108833855
  
    --- Diff: python/pyspark/sql/tests.py ---
    @@ -56,6 +56,15 @@
     from pyspark.sql.utils import AnalysisException, ParseException, IllegalArgumentException
     
     
    +_have_arrow = False
    +try:
    +    import pyarrow
    +    _have_arrow = True
    --- End diff --
    
    Maybe give the param doc string as exception message?
    
    I.e., `To make use of Apache Arrow for conversion, pyarrow must be installed and available on the calling Python process (Experimental)`.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r121830120
  
    --- Diff: dev/run-pip-tests ---
    @@ -120,6 +122,10 @@ for python in "${PYTHON_EXECS[@]}"; do
         python "$FWDIR"/dev/pip-sanity-check.py
         echo "Run the tests for context.py"
         python "$FWDIR"/python/pyspark/context.py
    +    if [ -n "$TEST_PYARROW" ]; then
    +      echo "Run tests for pyarrow"
    +      SPARK_TESTING=1 "$FWDIR"/bin/pyspark pyspark.sql.tests ArrowTests
    --- End diff --
    
    will we remove this at some time?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #75779 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/75779/testReport)** for PR 15821 at commit [`a0483b8`](https://github.com/apache/spark/commit/a0483b8990a8113305a63c3f486df6e835a8ed32).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by julienledem <gi...@git.apache.org>.
Github user julienledem commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105321652
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    --- End diff --
    
    for instead of while?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][WIP][PySpark] Using Apache Arrow to increa...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    Build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark pull request #15821: [SPARK-13534][PySpark] Using Apache Arrow to incr...

Posted by julienledem <gi...@git.apache.org>.
Github user julienledem commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15821#discussion_r105322928
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/ArrowConverters.scala ---
    @@ -0,0 +1,411 @@
    +/*
    +* 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
    +
    +import java.io.ByteArrayOutputStream
    +import java.nio.ByteBuffer
    +import java.nio.channels.{Channels, SeekableByteChannel}
    +
    +import scala.collection.JavaConverters._
    +
    +import io.netty.buffer.ArrowBuf
    +import org.apache.arrow.memory.{BaseAllocator, RootAllocator}
    +import org.apache.arrow.vector._
    +import org.apache.arrow.vector.BaseValueVector.BaseMutator
    +import org.apache.arrow.vector.file.{ArrowReader, ArrowWriter}
    +import org.apache.arrow.vector.schema.{ArrowFieldNode, ArrowRecordBatch}
    +import org.apache.arrow.vector.types.{FloatingPointPrecision, TimeUnit}
    +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema}
    +
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * ArrowReader requires a seekable byte channel.
    + * NOTE - this is taken from test org.apache.vector.file, see about moving to public util pkg
    + */
    +private[sql] class ByteArrayReadableSeekableByteChannel(var byteArray: Array[Byte])
    +  extends SeekableByteChannel {
    +  var _position: Long = 0L
    +
    +  override def isOpen: Boolean = {
    +    byteArray != null
    +  }
    +
    +  override def close(): Unit = {
    +    byteArray = null
    +  }
    +
    +  override def read(dst: ByteBuffer): Int = {
    +    val remainingBuf = byteArray.length - _position
    +    val length = Math.min(dst.remaining(), remainingBuf).toInt
    +    dst.put(byteArray, _position.toInt, length)
    +    _position += length
    +    length.toInt
    +  }
    +
    +  override def position(): Long = _position
    +
    +  override def position(newPosition: Long): SeekableByteChannel = {
    +    _position = newPosition.toLong
    +    this
    +  }
    +
    +  override def size: Long = {
    +    byteArray.length.toLong
    +  }
    +
    +  override def write(src: ByteBuffer): Int = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +
    +  override def truncate(size: Long): SeekableByteChannel = {
    +    throw new UnsupportedOperationException("Read Only")
    +  }
    +}
    +
    +/**
    + * Intermediate data structure returned from Arrow conversions
    + */
    +private[sql] abstract class ArrowPayload extends Iterator[ArrowRecordBatch]
    +
    +/**
    + * Build a payload from existing ArrowRecordBatches
    + */
    +private[sql] class ArrowStaticPayload(batches: ArrowRecordBatch*) extends ArrowPayload {
    +  private val iter = batches.iterator
    +  override def next(): ArrowRecordBatch = iter.next()
    +  override def hasNext: Boolean = iter.hasNext
    +}
    +
    +/**
    + * Class that wraps an Arrow RootAllocator used in conversion
    + */
    +private[sql] class ArrowConverters {
    +  private val _allocator = new RootAllocator(Long.MaxValue)
    +
    +  private[sql] def allocator: RootAllocator = _allocator
    +
    +  def interalRowIterToPayload(rowIter: Iterator[InternalRow], schema: StructType): ArrowPayload = {
    +    val batch = ArrowConverters.internalRowIterToArrowBatch(rowIter, schema, allocator)
    +    new ArrowStaticPayload(batch)
    +  }
    +
    +  def readPayloadByteArrays(payloadByteArrays: Array[Array[Byte]]): ArrowPayload = {
    +    val batches = scala.collection.mutable.ArrayBuffer.empty[ArrowRecordBatch]
    +    var i = 0
    +    while (i < payloadByteArrays.length) {
    +      val payloadBytes = payloadByteArrays(i)
    +      val in = new ByteArrayReadableSeekableByteChannel(payloadBytes)
    +      val reader = new ArrowReader(in, _allocator)
    +      val footer = reader.readFooter()
    +      val batchBlocks = footer.getRecordBatches.asScala.toArray
    +      batchBlocks.foreach(block => batches += reader.readRecordBatch(block))
    +      i += 1
    +    }
    +    new ArrowStaticPayload(batches: _*)
    +  }
    +}
    +
    +private[sql] object ArrowConverters {
    +
    +  /**
    +   * Map a Spark Dataset type to ArrowType.
    +   */
    +  private[sql] def sparkTypeToArrowType(dataType: DataType): ArrowType = {
    +    dataType match {
    +      case BooleanType => ArrowType.Bool.INSTANCE
    +      case ShortType => new ArrowType.Int(8 * ShortType.defaultSize, true)
    +      case IntegerType => new ArrowType.Int(8 * IntegerType.defaultSize, true)
    +      case LongType => new ArrowType.Int(8 * LongType.defaultSize, true)
    +      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
    +      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
    +      case ByteType => new ArrowType.Int(8, true)
    +      case StringType => ArrowType.Utf8.INSTANCE
    +      case BinaryType => ArrowType.Binary.INSTANCE
    +      case DateType => ArrowType.Date.INSTANCE
    +      case TimestampType => new ArrowType.Timestamp(TimeUnit.MILLISECOND)
    +      case _ => throw new UnsupportedOperationException(s"Unsupported data type: $dataType")
    +    }
    +  }
    +
    +  /**
    +   * Iterate over InternalRows and write to an ArrowRecordBatch.
    +   */
    +  private def internalRowIterToArrowBatch(
    +      rowIter: Iterator[InternalRow],
    +      schema: StructType,
    +      allocator: RootAllocator): ArrowRecordBatch = {
    +
    +    val columnWriters = schema.fields.zipWithIndex.map { case (field, ordinal) =>
    +      ColumnWriter(ordinal, allocator, field.dataType)
    +        .init()
    +    }
    +
    +    val writerLength = columnWriters.length
    +    while (rowIter.hasNext) {
    +      val row = rowIter.next()
    +      var i = 0
    +      while (i < writerLength) {
    +        columnWriters(i).write(row)
    +        i += 1
    +      }
    +    }
    +
    +    val fieldAndBuf = columnWriters.map { writer =>
    +      writer.finish()
    +    }.unzip
    +    val fieldNodes = fieldAndBuf._1
    +    val buffers = fieldAndBuf._2.flatten
    +
    +    val rowLength = if (fieldNodes.nonEmpty) fieldNodes.head.getLength else 0
    +    val recordBatch = new ArrowRecordBatch(rowLength,
    +      fieldNodes.toList.asJava, buffers.toList.asJava)
    +
    +    buffers.foreach(_.release())
    +    recordBatch
    +  }
    +
    +  /**
    +   * Convert a Spark Dataset schema to Arrow schema.
    +   */
    +  private[sql] def schemaToArrowSchema(schema: StructType): Schema = {
    +    val arrowFields = schema.fields.map { f =>
    +      new Field(f.name, f.nullable, sparkTypeToArrowType(f.dataType), List.empty[Field].asJava)
    +    }
    +    new Schema(arrowFields.toList.asJava)
    +  }
    +
    +  /**
    +   * Write an ArrowPayload to a byte array
    +   */
    +  private[sql] def payloadToByteArray(payload: ArrowPayload, schema: StructType): Array[Byte] = {
    +    val arrowSchema = ArrowConverters.schemaToArrowSchema(schema)
    +    val out = new ByteArrayOutputStream()
    +    val writer = new ArrowWriter(Channels.newChannel(out), arrowSchema)
    +    payload.foreach { batch =>
    +      try {
    +        writer.writeRecordBatch(batch)
    +      } finally {
    +        batch.close()
    +      }
    +    }
    +    writer.close()
    +    out.toByteArray
    +  }
    +}
    +
    +private[sql] trait ColumnWriter {
    +  def init(): this.type
    +  def write(row: InternalRow): Unit
    +
    +  /**
    +   * Clear the column writer and return the ArrowFieldNode and ArrowBuf.
    +   * This should be called only once after all the data is written.
    +   */
    +  def finish(): (ArrowFieldNode, Array[ArrowBuf])
    +}
    +
    +/**
    + * Base class for flat arrow column writer, i.e., column without children.
    + */
    +private[sql] abstract class PrimitiveColumnWriter(
    +  val ordinal: Int,
    +  val allocator: BaseAllocator)
    +    extends ColumnWriter {
    +  def valueVector: BaseDataValueVector
    +  def valueMutator: BaseMutator
    +
    +  def setNull(): Unit
    +  def setValue(row: InternalRow, ordinal: Int): Unit
    +
    +  protected var count = 0
    +  protected var nullCount = 0
    +
    +  override def init(): this.type = {
    +    valueVector.allocateNew()
    +    this
    +  }
    +
    +  override def write(row: InternalRow): Unit = {
    +    if (row.isNullAt(ordinal)) {
    +      setNull()
    +      nullCount += 1
    +    } else {
    +      setValue(row, ordinal)
    +    }
    +    count += 1
    +  }
    +
    +  override def finish(): (ArrowFieldNode, Array[ArrowBuf]) = {
    +    valueMutator.setValueCount(count)
    +    val fieldNode = new ArrowFieldNode(count, nullCount)
    +    val valueBuffers = valueVector.getBuffers(true)
    +    (fieldNode, valueBuffers)
    +  }
    +}
    +
    +private[sql] class BooleanColumnWriter(ordinal: Int, allocator: BaseAllocator)
    +    extends PrimitiveColumnWriter(ordinal, allocator) {
    +  private def bool2int(b: Boolean): Int = if (b) 1 else 0
    +
    +  override val valueVector: NullableBitVector
    +    = new NullableBitVector("BooleanValue", allocator)
    +  override val valueMutator: NullableBitVector#Mutator = valueVector.getMutator
    +
    +  override def setNull(): Unit = valueMutator.setNull(count)
    --- End diff --
    
    when do we use ordinal and when do we use count?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


[GitHub] spark issue #15821: [SPARK-13534][PySpark] Using Apache Arrow to increase pe...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15821
  
    **[Test build #76210 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/76210/testReport)** for PR 15821 at commit [`b6fe733`](https://github.com/apache/spark/commit/b6fe733955d6e153722b1945c09ed663d8ed9be2).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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