spark-test commented on code in PR #60533:
URL: https://github.com/apache/spark/pull/60533#discussion_r4581707506
##########
python/pyspark/sql/tests/test_types.py:
##########
@@ -3749,6 +3770,122 @@ def test_varchar_type(self):
self.assertEqual(v1, v3)
self.assertFalse(v1 is v3)
+ def test_file_type(self):
+ external, unknown = FileType.external(), FileType()
+ self.assertEqual(FileTypeMode.UNKNOWN, unknown.mode)
+ self.assertEqual(FileTypeMode.EXTERNAL, external.mode)
+ self.assertEqual(external, FileType(FileTypeMode.EXTERNAL))
+ # The mode is part of the type identity.
+ self.assertNotEqual(external, unknown)
+ self.assertNotEqual(hash(external), hash(unknown))
+
+ self.assertEqual("file external", external.simpleString())
+ self.assertEqual("file", unknown.simpleString())
+ self.assertEqual("file", FileType.typeName())
+ self.assertEqual("FileType(FileTypeMode.EXTERNAL)", repr(external))
+ self.assertEqual("FileType()", repr(unknown))
+ self.assertEqual("file external",
DataType._get_jvm_type_name(external))
+ self.assertEqual('"file external"', external.json())
+ self.assertEqual('"file unknown"', unknown.json())
+
+ with self.assertRaises(PySparkTypeError) as pe:
+ FileType("external") # type: ignore[arg-type]
+ self.check_error(
+ exception=pe.exception,
+ errorClass="NOT_EXPECTED_TYPE",
+ messageParameters={
+ "arg_name": "mode",
+ "expected_type": "FileTypeMode",
+ "arg_type": "str",
+ },
+ )
+
+ def test_file_type_json(self):
+ from pyspark.sql.types import _parse_datatype_json_string,
_parse_datatype_json_value
+
+ # Outside a struct field, the JSON carries the mode, and a plain
"file" is unknown.
+ for json_value, expected in [
+ ("file external", FileType.external()),
+ ("file unknown", FileType()),
+ ("file", FileType()),
+ ]:
+ with self.subTest(json_value=json_value):
+ self.assertEqual(expected,
_parse_datatype_json_value(json_value))
+ for dt in [FileType(), FileType.external(),
ArrayType(FileType.external())]:
+ with self.subTest(dt=dt):
+ self.assertEqual(dt, _parse_datatype_json_string(dt.json()))
+ for json_value in ["file managed", "file external unknown", "files"]:
+ with self.subTest(json_value=json_value):
+ with self.assertRaises(PySparkValueError) as pe:
+ _parse_datatype_json_value(json_value)
+ self.check_error(
+ exception=pe.exception,
+ errorClass="CANNOT_PARSE_DATATYPE",
+ messageParameters={"msg": json_value},
+ )
+ # Outside a struct field, a plain "file" in an array or a map is
unknown too.
+ self.assertEqual(
+ ArrayType(FileType()),
+ _parse_datatype_json_value(
+ {"type": "array", "elementType": "file", "containsNull": True}
+ ),
+ )
+ self.assertEqual(
+ MapType(StringType(), FileType()),
+ _parse_datatype_json_value(
+ {
+ "type": "map",
+ "keyType": "string",
+ "valueType": "file",
+ "valueContainsNull": True,
+ }
+ ),
+ )
+
+ # In a struct field, and in an array or map of one, an external file
is the plain "file"
+ # and a plain "file" is read as external. An unknown file keeps its
mode.
+ schema = StructType(
+ [
+ StructField("a", FileType.external()),
+ StructField("b", FileType()),
+ StructField("c", ArrayType(FileType.external())),
+ StructField("d", MapType(StringType(), FileType.external())),
Review Comment:
**Nit (P3):** Every FILE map in the new tests has a string key: this one,
`test_file_type_json_with_collations`, `test_file_type_json_matches_jvm`,
`test_file_type_from_ddl`, and both proto round trips. So nothing checks the
map-key half of the struct-field rule, which the PR implements on both sides:
`MapType.fromJson` forwarding `inStructField` to the key, and `fileTypeJson`
recursing into `keyType`.
In a mutation repro, two one-line regressions, dropping the key's
`inStructField` and writing the key with `dt.keyType.jsonValue()`, each left
the JSON and parsed types for every schema in the new JSON tests unchanged, so
those tests still pass. Yet a field holding `MapType(FileType.external(),
IntegerType())`, which this PR writes with key "file" and reads back equal,
came back with a `FileType()` key under the first, losing its mode, and was
written with key "file external" under the second, where the JVM's writer,
which recurses into the key, emits "file". Such a schema is reachable through
the public types, for example with `json()` and `StructType.fromJson`.
Adding a field such as `StructField("k", MapType(FileType.external(),
IntegerType()))` to this schema, with an assertion that its `keyType` is
written as "file", and to the schema in `test_file_type_json_matches_jvm` would
pin both sides.
**Verification:**
- **Regression:** With the map reader no longer passing the struct-field
flag to the key, or with the writer emitting the key's own JSON value, the new
map-key assertions fail, and they pass with the PR's code.
- **Compatibility:** For a struct field holding a map with an external FILE
key, the JSON PySpark writes equals the JVM's, and each side reads the other's
JSON back to an equal type.
##########
python/pyspark/sql/types.py:
##########
@@ -1494,7 +1503,8 @@ def _dataTypeJsonValue(
string_metadata: Dict[str, str],
char_varchar_metadata: Dict[str, str],
) -> Union[str, Dict[str, Any]]:
- if not string_metadata and not char_varchar_metadata:
+ has_file = _has_type(self.dataType, FileType)
Review Comment:
**Nit (P3):** `_has_type` walks this field's whole type, nested struct
fields and UDT storage types included (`VectorUDT.sqlType()` builds a new
struct on each call), and every nested `StructField` repeats the walk on its
own subtree when its struct serializes. Only the field's own type and its array
and map positions can change what `fileTypeJson` writes, so for a schema
without a FILE, which is every schema existing workloads serialize, the walk is
added CPU work that grows with nesting depth while the JSON stays the same.
A timing repro of `StructType.json()` against the base branch's version of
this method measured 1.07-1.08x on a flat 1,000-field schema, 1.12-1.27x on
nested, collated, and UDT-field schemas, and 5.0-5.6x on a depth-100 struct
chain. It is planning-time work with no per-row cost, reached from classic and
Connect `createDataFrame`, `cast`, UDF return types, reader schemas, and state
schemas.
A check of only those positions, the field's own type and recursively its
array element and map key and value types, that returns what the base branch
returns (`self.dataType.jsonValue()`, or
`removeCollations(self.dataType).jsonValue()` for a collated field) when no
external FILE turns up gave byte-identical JSON in the same repro, at
1.02-1.06x in every case including the depth-100 chain. That remainder is the
per-field check any FILE gate pays. The JVM's `existsRecursively` pre-check has
the same broad shape, but the output depends only on those positions, so the
narrower check keeps parity with it.
**Verification:**
- **Compatibility:** For schemas holding an external or unknown FILE as a
field's own type, in an array, as a map key and as a map value, inside a nested
struct, and beside a collated string, the JSON PySpark writes is unchanged from
the current head and still equals the JVM's, and each side reads the other's
back to an equal type.
- **Regression:** Serializing schemas without a FILE, including a flat wide
schema, a deep chain of nested structs, and a schema with collated string
fields, gives JSON identical to the base branch's at a cost close to the base
branch's that does not grow with nesting depth.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]