You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by do...@apache.org on 2026/10/20 22:03:15 UTC

(spark-connect-swift) branch main updated: [SPARK-60409] Fix `createDataFrame` to keep the number of rows of local data without columns

This is an automated email from the ASF dual-hosted git repository.

dongjoon-hyun pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/spark-connect-swift.git


The following commit(s) were added to refs/heads/main by this push:
     new 2310e8f  [SPARK-60409] Fix `createDataFrame` to keep the number of rows of local data without columns
2310e8f is described below

commit 2310e8feec1e5b5068ce3d7ed0d3d29684584704
Author: Dongjoon Hyun <do...@apache.org>
AuthorDate: Tue Oct 20 15:03:09 2026 -0700

    [SPARK-60409] Fix `createDataFrame` to keep the number of rows of local data without columns
    
    ### What changes were proposed in this pull request?
    
    This PR fixes `SparkSession.createDataFrame` to keep the number of rows of local data without columns, like PySpark.
    
    - `[[Sendable?]]` rows: `ConvertToArrow.toArrowIPCStream` sets the length of the `RecordBatch` to the number of rows.
    - `Encodable` items: `createDataFrame(batch:rowCount:schema:)` sets the length to the number of items when the encoded `RecordBatch` has no columns.
    
    ### Why are the changes needed?
    
    Local data without columns crashes because `RecordBatch.init(_:columns:)` reads `columns[0]`. In addition, `RecordBatch.Builder.finish()` takes the length from the first column, so a `RecordBatch` without columns cannot have any rows.
    
    ```swift
    struct EmptyRecord: Encodable, Sendable {}
    
    try await spark.createDataFrame([EmptyRecord(), EmptyRecord()]).count()  // crash
    try await spark.createDataFrame([[], []], "").count()                    // crash
    try await spark.createDataFrame([[], []], "struct<>").count()            // crash
    try await spark.createDataFrame([[], []], StructType()).count()          // crash
    ```
    
    PySpark keeps the number of rows in this case. [LocalDataToArrowConversion.convert](https://github.com/apache/spark/blob/v4.2.0/python/pyspark/sql/conversion.py#L912) of `v4.2.0` (2026-07-11) uses `pa.Table.from_struct_array(pa.array([{}] * len(rows)))`. The server accepts a 0-column batch with N rows.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. The above examples return `2` instead of crashing. With SPARK-60405, which fixes reading results without columns, `collect()` returns `[Row(), Row()]` for them.
    
    ### How was this patch tested?
    
    Added `CreateDataFrameTests.emptySchema` and `CreateDataFrameTests.createDataFrameWithEncodableWithoutFields`. Verified against an `apache/spark:4.2.0` Connect server.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #610 from dongjoon-hyun/SPARK-60409.
    
    Authored-by: Dongjoon Hyun <do...@apache.org>
    Signed-off-by: Dongjoon Hyun <do...@apache.org>
---
 Sources/SparkConnect/ConvertToArrow.swift          |  4 ++-
 Sources/SparkConnect/SparkSession.swift            | 12 ++++++---
 Tests/SparkConnectTests/CreateDataFrameTests.swift | 29 ++++++++++++++++++++++
 3 files changed, 41 insertions(+), 4 deletions(-)

diff --git a/Sources/SparkConnect/ConvertToArrow.swift b/Sources/SparkConnect/ConvertToArrow.swift
index 79b909b..7f0ad45 100644
--- a/Sources/SparkConnect/ConvertToArrow.swift
+++ b/Sources/SparkConnect/ConvertToArrow.swift
@@ -53,8 +53,10 @@ enum ConvertToArrow {
     }
     switch batchBuilder.finish() {
     case .success(let batch):
+      // Like PySpark, keep the number of rows even if there are no columns.
+      let batches = [RecordBatch(batch.schema, columns: batch.columns, length: UInt(data.count))]
       switch ArrowWriter().writeStreaming(
-        ArrowWriter.Info(.recordbatch, schema: batch.schema, batches: [batch]))
+        ArrowWriter.Info(.recordbatch, schema: batch.schema, batches: batches))
       {
       case .success(let ipcStream):
         return ipcStream
diff --git a/Sources/SparkConnect/SparkSession.swift b/Sources/SparkConnect/SparkSession.swift
index 69e0b43..28e1803 100644
--- a/Sources/SparkConnect/SparkSession.swift
+++ b/Sources/SparkConnect/SparkSession.swift
@@ -213,7 +213,7 @@ public actor SparkSession {
       throw SparkConnectError.InvalidArrowData
     }
     let schema = try StructType(batch.schema).toDDL
-    return try await createDataFrame(batch: batch, schema: schema)
+    return try await createDataFrame(batch: batch, rowCount: data.count, schema: schema)
   }
 
   /// Creates a ``DataFrame`` from the given array of `Encodable` instances with the specified schema string.
@@ -229,7 +229,7 @@ public actor SparkSession {
     guard let batch = try ArrowEncoder.encode(data) else {
       throw SparkConnectError.InvalidArrowData
     }
-    return try await createDataFrame(batch: batch, schema: schema)
+    return try await createDataFrame(batch: batch, rowCount: data.count, schema: schema)
   }
 
   /// Creates a ``DataFrame`` from the given array of `Encodable` instances with the specified ``StructType`` schema.
@@ -244,7 +244,13 @@ public actor SparkSession {
     return try await createDataFrame(data, schema.toDDL)
   }
 
-  private func createDataFrame(batch: RecordBatch, schema: String) async throws -> DataFrame {
+  private func createDataFrame(batch: RecordBatch, rowCount: Int, schema: String) async throws
+    -> DataFrame
+  {
+    // Like PySpark, keep the number of rows even if there are no columns.
+    let batch =
+      batch.columnCount == 0
+      ? RecordBatch(batch.schema, columns: [], length: UInt(rowCount)) : batch
     switch ArrowWriter().writeStreaming(
       ArrowWriter.Info(.recordbatch, schema: batch.schema, batches: [batch]))
     {
diff --git a/Tests/SparkConnectTests/CreateDataFrameTests.swift b/Tests/SparkConnectTests/CreateDataFrameTests.swift
index 55b0a29..170584a 100644
--- a/Tests/SparkConnectTests/CreateDataFrameTests.swift
+++ b/Tests/SparkConnectTests/CreateDataFrameTests.swift
@@ -165,6 +165,22 @@ struct CreateDataFrameTests {
     await spark.stop()
   }
 
+  @Test
+  func emptySchema() async throws {
+    let spark = try await SparkSession.builder.getOrCreate()
+    // Like PySpark, the number of rows is kept even if there are no columns.
+    let dfs = [
+      try await spark.createDataFrame([[], []], ""),
+      try await spark.createDataFrame([[], []], "struct<>"),
+      try await spark.createDataFrame([[], []], StructType()),
+    ]
+    for df in dfs {
+      #expect(try await df.columns.isEmpty)
+      #expect(try await df.count() == 2)
+    }
+    await spark.stop()
+  }
+
   @Test
   func integerWidening() async throws {
     let spark = try await SparkSession.builder.getOrCreate()
@@ -365,6 +381,19 @@ struct CreateDataFrameTests {
     await spark.stop()
   }
 
+  struct EmptyRecord: Encodable, Sendable {}
+
+  @Test
+  func createDataFrameWithEncodableWithoutFields() async throws {
+    let spark = try await SparkSession.builder.getOrCreate()
+    let data = [EmptyRecord(), EmptyRecord()]
+    let df = try await spark.createDataFrame(data)
+    #expect(try await df.columns.isEmpty)
+    #expect(try await df.count() == 2)
+    #expect(try await spark.createDataFrame(data, "struct<>").count() == 2)
+    await spark.stop()
+  }
+
   @Test
   func createDataFrameWithEncodablePrimitives() async throws {
     let spark = try await SparkSession.builder.getOrCreate()


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