[ 
https://issues.apache.org/jira/browse/SPARK-62320?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
 ]

Shivadarshan updated SPARK-62320:
---------------------------------
    Description: 
 When a pandas function returns a DataFrame with 0 columns for some input and a 
DataFrame with rows for other input, under a schema with NOT NULL fields, the 
query fails with:
  
  ```
  pyarrow.lib.ArrowInvalid: Tried to write record batch with different schema
  ```
  
  `PandasToArrowConversion.from_pandas` converts a DataFrame with 0 columns 
through a shortcut that builds the batch from `to_arrow_type(schema)`, which 
keeps the NOT NULL fields. A DataFrame with columns goes through 
  `pa.RecordBatch.from_arrays`, which makes every field nullable. The Arrow 
stream writer then rejects the second kind of batch, because its schema differs 
from the first.
  
  This is a regression from SPARK-55159 (4.2.0). Before it, both kinds of 
DataFrames got the fields of `to_arrow_type(return_type)`. Both repros below 
work on 4.1.1 and fail on 4.3.0 and master.
  
  An Arrow UDTF under the legacy pandas conversion whose eval yields no rows 
for some input rows:
  
  ```python
  from pyspark.sql.functions import udtf
  
  @udtf(returnType="a: int NOT NULL", useArrow=True)
  class NotNullUDTF:
      def eval(self, i: int):
          for n in range(i):
              yield (n,)
      
  spark.udtf.register("notNullUDTF", NotNullUDTF)
  
spark.conf.set("spark.sql.legacy.execution.pythonUDTF.pandas.conversion.enabled",
 "true")
  spark.sql("SELECT * FROM range(0, 3, 1, 1) JOIN LATERAL 
notNullUDTF(id)").collect()
  # expected: (1, 0), (2, 0), (2, 1)
  ```
  
  applyInPandas with a group that returns pd.DataFrame():
  
  ```python
  import pandas as pd
  
  def f(pdf):
      return pd.DataFrame() if pdf["k"].iloc[0] == 0 else pd.DataFrame({"a": 
[1]})
  
  spark.range(0, 2).withColumnRenamed("id", "k").repartition(1) \
      .groupBy("k").applyInPandas(f, "a int not null").collect()
  # expected: [Row(a=1)]
  ```
      
  This was found while working on SPARK-60564 
(https://github.com/apache/spark/pull/60450), which skips one test in the 
legacy pandas conversion because of it.

  was:
With `useArrow=True` and the legacy pandas conversion, a Python UDTF that 
declares a `NOT NULL` output column fails when its `eval` yields no rows for 
some input rows and yields rows for others. It works when `eval` yields a row 
for every input row, and without the legacy conversion.

```python
from pyspark.sql.functions import udtf

@udtf(returnType="a: int NOT NULL", useArrow=True)
class NotNullUDTF:
    def eval(self, i: int):
        for n in range(i):
            yield (n,)

spark.udtf.register("notNullUDTF", NotNullUDTF)
spark.conf.set("spark.sql.legacy.execution.pythonUDTF.pandas.conversion.enabled",
 "true")
spark.sql("SELECT * FROM range(0, 3, 1, 1) JOIN LATERAL 
notNullUDTF(id)").collect()
```

This fails with:

```
Tried to write record batch with different schema
```

It should return `(1, 0), (2, 0), (2, 1)`. The same query works with the conf 
set to `false`, and in the pickled (non-Arrow) mode. It also works in Spark 
4.1.1 with the conf set to `true`, so this is a regression after 4.1.1. It 
fails on 4.3.0 and on master.

This was found while working on SPARK-60564 
(https://github.com/apache/spark/pull/60450), whose 
`test_udtf_with_left_lateral_join_not_null_column` is skipped in the legacy 
pandas conversion because of it. It is not related to that change: the inner 
lateral join above fails on 4.3.0 too, without it.


> pd.DataFrame() with 0 columns and a NOT NULL schema fails with "different 
> schema" in pandas UDFs and Arrow UDTFs (regression from SPARK-55159)
> ----------------------------------------------------------------------------------------------------------------------------------------------
>
>                 Key: SPARK-62320
>                 URL: https://issues.apache.org/jira/browse/SPARK-62320
>             Project: Spark
>          Issue Type: Bug
>          Components: PySpark
>    Affects Versions: 4.2.0, 4.3.0, 5.0.0
>            Reporter: Shivadarshan
>            Priority: Minor
>
>  When a pandas function returns a DataFrame with 0 columns for some input and 
> a DataFrame with rows for other input, under a schema with NOT NULL fields, 
> the query fails with:
>   
>   ```
>   pyarrow.lib.ArrowInvalid: Tried to write record batch with different schema
>   ```
>   
>   `PandasToArrowConversion.from_pandas` converts a DataFrame with 0 columns 
> through a shortcut that builds the batch from `to_arrow_type(schema)`, which 
> keeps the NOT NULL fields. A DataFrame with columns goes through 
>   `pa.RecordBatch.from_arrays`, which makes every field nullable. The Arrow 
> stream writer then rejects the second kind of batch, because its schema 
> differs from the first.
>   
>   This is a regression from SPARK-55159 (4.2.0). Before it, both kinds of 
> DataFrames got the fields of `to_arrow_type(return_type)`. Both repros below 
> work on 4.1.1 and fail on 4.3.0 and master.
>   
>   An Arrow UDTF under the legacy pandas conversion whose eval yields no rows 
> for some input rows:
>   
>   ```python
>   from pyspark.sql.functions import udtf
>   
>   @udtf(returnType="a: int NOT NULL", useArrow=True)
>   class NotNullUDTF:
>       def eval(self, i: int):
>           for n in range(i):
>               yield (n,)
>       
>   spark.udtf.register("notNullUDTF", NotNullUDTF)
>   
> spark.conf.set("spark.sql.legacy.execution.pythonUDTF.pandas.conversion.enabled",
>  "true")
>   spark.sql("SELECT * FROM range(0, 3, 1, 1) JOIN LATERAL 
> notNullUDTF(id)").collect()
>   # expected: (1, 0), (2, 0), (2, 1)
>   ```
>   
>   applyInPandas with a group that returns pd.DataFrame():
>   
>   ```python
>   import pandas as pd
>   
>   def f(pdf):
>       return pd.DataFrame() if pdf["k"].iloc[0] == 0 else pd.DataFrame({"a": 
> [1]})
>   
>   spark.range(0, 2).withColumnRenamed("id", "k").repartition(1) \
>       .groupBy("k").applyInPandas(f, "a int not null").collect()
>   # expected: [Row(a=1)]
>   ```
>       
>   This was found while working on SPARK-60564 
> (https://github.com/apache/spark/pull/60450), which skips one test in the 
> legacy pandas conversion because of it.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to