Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-39168][PYTHON] Use all values in a python list when inferring ArrayType schema #36545

Closed
wants to merge 10 commits into from

Conversation

physinet
Copy link
Contributor

What changes were proposed in this pull request?

This PR modifies type inference for python lists to consider all values in the list, not just the first value.

Why are the changes needed?

This enables convenient type inference in the two following cases:

previous current
[None, 1] array<void> (raises ValueError) array<bigint>
[{"b": 1}, {"c": 2}] array<struct<b:bigint>> array<struct<b:bigint,c:bigint>>

Does this PR introduce any user-facing change?

Possible user-facing changes:

  • attempting to infer the schema of an array with mixed types (e.g. ["a", 1]) may result in a TypeError
    • previously, this was inferred as an array<string> and produced a value ["a", "1"]
  • fields of inferred struct types will differ if dictionaries in an array have different keys

How was this patch tested?

Added unit tests for various cases.

@physinet
Copy link
Contributor Author

physinet commented May 13, 2022

  • Add a unit test for ["a", 1] producing a TypeError
  • Consider making this behavior configurable

@physinet physinet changed the title [WIP][SPARK-39168] Use all values in a python list when inferring ArrayType schema [WIP][SPARK-39168][PYTHON] Use all values in a python list when inferring ArrayType schema May 13, 2022
@HyukjinKwon
Copy link
Member

Nice PR description. Yeah, we should probably add a configuration then, please also refer to 2537fe8 for adding a SQL config

@HyukjinKwon
Copy link
Member

HyukjinKwon commented May 14, 2022

We should probably add a configuration like spark.sql.pyspark.legacy.inferFirstElementInArray.enabled (feel free to pick other names if you have other ideas). Would also have to create a new page like https://github.com/apache/spark/blob/master/python/docs/source/migration_guide/pyspark_3.2_to_3.3.rst and describe this behavior change.

@AmplabJenkins
Copy link

Can one of the admins verify this patch?

@physinet
Copy link
Contributor Author

We should probably add a configuration like spark.sql.pyspark.legacy.inferFirstElementInArray.enabled (feel free to pick other names if you have other ideas). Would also have to create a new page like https://github.com/apache/spark/blob/master/python/docs/source/migration_guide/pyspark_3.2_to_3.3.rst and describe this behavior change.

Added this configuration (slightly changed the name) and created a new migration guide page.

Copy link
Member

@HyukjinKwon HyukjinKwon left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM otherwise

@HyukjinKwon
Copy link
Member

cc @BryanCutler @viirya @ueshin FYI

@physinet physinet force-pushed the infer_schema_from_full_array branch from cfc81be to 7cde786 Compare May 17, 2022 12:58
@physinet physinet changed the title [WIP][SPARK-39168][PYTHON] Use all values in a python list when inferring ArrayType schema [SPARK-39168][PYTHON] Use all values in a python list when inferring ArrayType schema May 17, 2022
@@ -570,10 +570,20 @@ def _inferSchemaFromList(
if not data:
raise ValueError("can not infer schema from empty dataset")
infer_dict_as_struct = self._jconf.inferDictAsStruct()
infer_array_from_first_element = self._jconf.legacyInferArrayTypeFromFirstElement()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need a flag? in the cases where this matters, the schema would be wrong and produce an error; would that be desirable?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously it was allowed to have mixed types in a python list, as long as the types could be cast to the type enforced by the schema inferred from the first element:

>>> df = spark.createDataFrame([{"a": ["1", 2]}])
>>> df.show()
+------+
|     a|
+------+
|[1, 2]|
+------+
>>> df.schema
StructType(List(StructField(a,ArrayType(StringType,true),true)))

With this change, creating the DataFrame causes an error:

>>> df = spark.createDataFrame([{"a": ["1", 2]}])
...
TypeError: Unable to infer the type of the field a.

Because of this change, I think it makes sense to have the behavior configurable.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait, this seems like the wrong behavior. StringType should be inferred for this column, as it is now. I don't see a reason to break this? don't we want to just find the widest applicable type?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can see the argument for casting to the widest applicable type, but I think that should be a separate discussion. Inferring the type of an array I think should be analogous to inferring a type over rows, which raises an error in this case:

>>> spark.createDataFrame([{"a": "1"}, {"a": 2}])
...
TypeError: field a: Can not merge type <class 'pyspark.sql.types.StringType'> and <class 'pyspark.sql.types.LongType'>

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see it fixes some cases, by somewhat 'accidentally' correctly inferring a widening type. But it does cause some common cases to start failing, when they 'accidentally' work now (your example in this thread). It feels like the half-measure isn't worth it, as it needs a whole new flag. Is it hard to just implement logic to find the closest type for everything? that code surely already exists in the code base

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be marked as a TODO (at least on the python side). https://github.com/apache/spark/blob/master/python/pyspark/sql/types.py#L1377

Again, I think this should be addressed separately from this PR, but I'm happy to hold off on this PR if you think type-widening logic should be implemented first.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not super familiar with this part of the code and I don't object to the change if someone else wants to merge; just seems like it would be relatively straightforward to 'really' fix it

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that's right that it causes a behaviour change. However, the (previous) string type coercion behaviour in an element of an array is actually a mistake I believe. For example, such type coercion is not supported in regular type inference:

>>> spark.createDataFrame([{"a": "1"}, {"a" :2}])
Traceback (most recent call last):
  ...
TypeError: field a: Can not merge type <class 'pyspark.sql.types.StringType'> and <class 'pyspark.sql.types.LongType'>

So, what this PR actually does is to match the behaviour with non-nested type inference. The switch was added for users dependent on the previous behaviour.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, that is sounding reasonable then to me. I dislike flags, but, if a follow-up made the flag irrelevant, maybe that's OK.

Copy link
Contributor Author

@physinet physinet May 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By the way, I think StringType is the only type that supports coercion currently: https://github.com/apache/spark/blob/master/python/pyspark/sql/types.py#L1596-L1599

Copy link
Member

@viirya viirya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having a quick look. The new behavior seems more reasonable, although there is a concern on breaking current behavior. Migration guide is updated and a legacy flag is added. So seems okay to go.

@HyukjinKwon
Copy link
Member

Merged to master.

@HyukjinKwon
Copy link
Member

Thanks for working on this @physinet, and congrats for being a Apache Spark contributor :-).

HyukjinKwon added a commit that referenced this pull request May 13, 2024
…rArrayTypeFromFirstElement

### What changes were proposed in this pull request?

This PR fixes a bug that does not respect `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` in nested arrays, introduced by #36545.

### Why are the changes needed?

To have a way to restore the original behaviour.

### Does this PR introduce _any_ user-facing change?

Yes, it fixes the regression when `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` is set to `True`.

### How was this patch tested?

Unittest added.

### Was this patch authored or co-authored using generative AI tooling?

No.

Closes #46548 from HyukjinKwon/SPARK-48248.

Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
HyukjinKwon added a commit that referenced this pull request May 13, 2024
…rArrayTypeFromFirstElement

This PR fixes a bug that does not respect `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` in nested arrays, introduced by #36545.

To have a way to restore the original behaviour.

Yes, it fixes the regression when `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` is set to `True`.

Unittest added.

No.

Closes #46548 from HyukjinKwon/SPARK-48248.

Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
(cherry picked from commit b2140d0)
Signed-off-by: Hyukjin Kwon <[email protected]>
HyukjinKwon added a commit that referenced this pull request May 13, 2024
…rArrayTypeFromFirstElement

This PR fixes a bug that does not respect `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` in nested arrays, introduced by #36545.

To have a way to restore the original behaviour.

Yes, it fixes the regression when `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` is set to `True`.

Unittest added.

No.

Closes #46548 from HyukjinKwon/SPARK-48248.

Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
(cherry picked from commit b2140d0)
Signed-off-by: Hyukjin Kwon <[email protected]>
HyukjinKwon added a commit that referenced this pull request May 14, 2024
… schema

### What changes were proposed in this pull request?

This is similar with #36545. This PR proposes to infer the map types from all pairs instead of the first pair.

### Why are the changes needed?

To have the consistent behaivor. e.g.,

```python
>>> spark.createDataFrame([[1], [2], ["a"], ["c"]]).collect()
[Row(_1='1'), Row(_1='2'), Row(_1='a'), Row(_1='c')]
```

### Does this PR introduce _any_ user-facing change?

Yes. See below

**Without Spark Connect:**

```python
>>> spark.createDataFrame([{"outer": {"payment": 200.5, "name": "A"}}]).collect()
[Row(outer={'name': 'A', 'payment': '200.5'})]
>>> spark.conf.set("spark.sql.pyspark.legacy.inferMapTypeFromFirstPair.enabled", True)
>>> spark.createDataFrame([{"outer": {"payment": 200.5, "name": "A"}}]).collect()
[Row(outer={'name': None, 'payment': 200.5})]
```

**With Spark Conenct:**

```python
>>> spark.createDataFrame([{"outer": {"payment": 200.5, "name": "A"}}]).collect()
[Row(outer={'payment': '200.5', 'name': 'A'})]
>>> spark.conf.set("spark.sql.pyspark.legacy.inferMapTypeFromFirstPair.enabled", True)
>>> spark.createDataFrame([{"outer": {"payment": 200.5, "name": "A"}}]).collect()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../spark/python/pyspark/sql/connect/session.py", line 635, in createDataFrame
    _table = LocalDataToArrowConversion.convert(_data, _schema)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.../spark/python/pyspark/sql/connect/conversion.py", line 378, in convert
    return pa.Table.from_arrays(pylist, schema=pa_schema)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "pyarrow/table.pxi", line 3974, in pyarrow.lib.Table.from_arrays
  File "pyarrow/table.pxi", line 1464, in pyarrow.lib._sanitize_arrays
  File "pyarrow/array.pxi", line 373, in pyarrow.lib.asarray
  File "pyarrow/array.pxi", line 343, in pyarrow.lib.array
  File "pyarrow/array.pxi", line 42, in pyarrow.lib._sequence_to_array
  File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status
  File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: Could not convert 'A' with type str: tried to convert to double
```

### How was this patch tested?

Unittests added

### Was this patch authored or co-authored using generative AI tooling?

No.

Closes #46547 from HyukjinKwon/infer-map-first.

Lead-authored-by: Hyukjin Kwon <[email protected]>
Co-authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
szehon-ho pushed a commit to szehon-ho/spark that referenced this pull request Aug 7, 2024
…rArrayTypeFromFirstElement

This PR fixes a bug that does not respect `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` in nested arrays, introduced by apache#36545.

To have a way to restore the original behaviour.

Yes, it fixes the regression when `spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabled` is set to `True`.

Unittest added.

No.

Closes apache#46548 from HyukjinKwon/SPARK-48248.

Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
(cherry picked from commit b2140d0)
Signed-off-by: Hyukjin Kwon <[email protected]>
(cherry picked from commit 1d6724ca8e9e79f666aefd4258cce1482602644f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants