spark-test commented on code in PR #59972:
URL: https://github.com/apache/spark/pull/59972#discussion_r4467067990
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/SchemaPruning.scala:
##########
@@ -127,12 +130,37 @@ object SchemaPruning extends SQLConfHelper {
val rootFieldType = StructType(Array(root.field))
val optFieldType = StructType(Array(opt.field))
val merged = optFieldType.merge(rootFieldType)
- DataTypeUtils.sameType(merged, optFieldType)
+ DataTypeUtils.sameType(merged, optFieldType) &&
+ opt.mapKeys.forall(_.retainedBy(rootFieldType))
Review Comment:
**Nit (P3):** The comments above, both the summary and the numbered
criteria, still say an optional `IsNull`/`IsNotNull` root field can be dropped
whenever the merged type equals the optional field's type. This line adds a
second requirement: the covering root must also keep every map key the null
check compares. For `m[k] IS NULL` together with a projection of
`map_keys(m)[0].a`, the merged-type check alone would drop the optional field,
but this condition keeps it so the complete stored key is read. The condition
is described only on `RootField.mapKeys` and `MapKeyRequirement`, so someone
editing this filter from the comments could drop it and bring back comparisons
of narrowed struct keys.
**Verification:**
- **Inspection:** The documented criteria for dropping an optional
null-check root field match both conditions the code checks: the merged type
equals the optional field, and the covering field keeps every map key the null
check compares.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetSchemaPruningSuite.scala:
##########
@@ -35,6 +41,216 @@ abstract class ParquetSchemaPruningSuite extends
SchemaPruningSuite with Adaptiv
override protected val vectorizedReaderNestedEnabledKey: String =
SQLConf.PARQUET_VECTORIZED_READER_NESTED_COLUMN_ENABLED.key
+ test("a pruned two-level Parquet LIST preserves its element type and field
IDs") {
+ withTempPath { file =>
+ // After clipping legacy to just wanted, both LISTs have identical
repeated groups.
+ val fileSchema = MessageTypeParser.parseMessageType(
+ """message m {
+ | optional group legacy (LIST) {
+ | repeated group entries { optional int32 sibling = 18; optional
int32 wanted = 17; }
+ | }
+ | optional group standard (LIST) {
+ | repeated group entries { optional int32 wanted = 17; }
+ | }
+ | optional int32 idx;
+ |}""".stripMargin)
+ val writer = ExampleParquetWriter.builder(new Path(file.toURI))
+
.withConf(spark.sessionState.newHadoopConf()).withType(fileSchema).build()
+ try {
+ val row = new SimpleGroupFactory(fileSchema).newGroup().append("idx",
1)
+ val legacy = row.addGroup("legacy")
+ legacy.addGroup("entries").append("sibling", 10).append("wanted", 11)
+ legacy.addGroup("entries").append("sibling", 20).append("wanted", 22)
+ val standard = row.addGroup("standard")
+ standard.addGroup("entries").append("wanted", 30)
+ standard.addGroup("entries").append("wanted", 33)
+ writer.write(row)
+ } finally {
+ writer.close()
+ }
+ val fieldId = new
MetadataBuilder().putLong(ParquetUtils.FIELD_ID_METADATA_KEY, 17).build()
+ val missingId = new
MetadataBuilder().putLong(ParquetUtils.FIELD_ID_METADATA_KEY, 19).build()
+ val element = new StructType()
+ .add("sibling", IntegerType, nullable = true, metadata = missingId)
+ .add("renamed", IntegerType, nullable = true, metadata = fieldId)
+ val readSchema = new StructType().add("legacy", ArrayType(element))
+ .add("standard", ArrayType(IntegerType)).add("idx", IntegerType)
+ Seq("true", "false").foreach { vectorized =>
+ withSQLConf(
+ vectorizedReaderEnabledKey -> vectorized,
+ SQLConf.PARQUET_FIELD_ID_READ_ENABLED.key -> "true",
+ SQLConf.NESTED_SCHEMA_PRUNING_ENABLED.key -> "true") {
+ val data =
spark.read.schema(readSchema).parquet(file.getCanonicalPath)
+ val query = data.selectExpr("legacy[1].renamed", "standard[1]")
+ checkScanSchemata(query,
+ "struct<legacy:array<struct<renamed:int>>,standard:array<int>>")
+ checkAnswer(query, Row(22, 33))
+
+ val dynamic = data.selectExpr("legacy[idx].renamed", "standard[idx]")
+ checkScanSchemata(dynamic,
+
"struct<legacy:array<struct<renamed:int>>,standard:array<int>,idx:int>")
+ checkAnswer(dynamic, Row(22, 33))
+
+ // Only the missing ID is requested. The first physical field is
read for levels
+ // and shares its name, but has a different ID.
+ checkAnswer(data.selectExpr("legacy.sibling"), Row(Seq(null, null)))
+ checkAnswer(data.selectExpr("legacy[idx].sibling"), Row(null))
+ }
+ }
+ }
+ }
+
+ test("a two-level Parquet LIST preserves enclosing struct nullness after
pruning") {
+ withTempPath { file =>
+ val fileSchema = MessageTypeParser.parseMessageType(
+ """message m {
+ | optional group record {
+ | optional group items (LIST) {
+ | repeated group entries { optional int32 x; optional int32 y; }
+ | }
+ | }
+ |}""".stripMargin)
+ val writer = ExampleParquetWriter.builder(new Path(file.toURI))
+
.withConf(spark.sessionState.newHadoopConf()).withType(fileSchema).build()
+ val factory = new SimpleGroupFactory(fileSchema)
+ try {
+ val row = factory.newGroup()
+
row.addGroup("record").addGroup("items").addGroup("entries").append("x",
1).append("y", 2)
+ writer.write(row)
+ writer.write(factory.newGroup())
+ } finally {
+ writer.close()
+ }
+ Seq("true", "false").foreach { vectorized =>
+ withSQLConf(vectorizedReaderEnabledKey -> vectorized) {
+ // The only physical child available for the record's levels is the
clipped LIST.
+ val data = spark.read.schema("record STRUCT<missing:
INT>").parquet(file.getCanonicalPath)
+ checkAnswer(data.selectExpr("record.missing", "record IS NULL"),
+ Seq(Row(null, false), Row(null, true)))
+ }
+ }
+ }
+ }
+
+ test("dynamic array selection preserves root and nested Parquet field IDs") {
+ withSQLConf(
+ SQLConf.NESTED_SCHEMA_PRUNING_ENABLED.key -> "true",
+ SQLConf.PARQUET_FIELD_ID_WRITE_ENABLED.key -> "true",
+ SQLConf.PARQUET_FIELD_ID_READ_ENABLED.key -> "true") {
+ withTempPath { dir =>
+ val rootId = new MetadataBuilder()
+ .putLong(ParquetUtils.FIELD_ID_METADATA_KEY, 1).build()
+ val leafId = new MetadataBuilder()
+ .putLong(ParquetUtils.FIELD_ID_METADATA_KEY, 17).build()
+ val leafType = new StructType()
+ .add("old_id", IntegerType, nullable = true, metadata = leafId)
+ .add("payload", StringType)
+ def schema(rootName: String, leaf: StructType): StructType = new
StructType()
+ .add(rootName, ArrayType(new StructType().add("children",
ArrayType(leaf))),
+ nullable = true, metadata = rootId)
+ .add("idx", IntegerType)
+ val writeSchema = schema("old_items", leafType)
+ val readSchema = schema("new_items", StructType(Seq(
+ leafType("old_id").copy(name = "new_id"), leafType("payload"))))
+ val rows = Seq(Row(Seq(Row(Seq(Row(42, "unused")))), 0))
+ val path = dir.getCanonicalPath
+ spark.createDataFrame(spark.sparkContext.parallelize(rows),
writeSchema)
+ .write.parquet(path)
+
+ Seq("true", "false").foreach { vectorized =>
+ withSQLConf(vectorizedReaderEnabledKey -> vectorized) {
+ val query = spark.read.schema(readSchema).parquet(path)
+ .selectExpr("new_items[idx].children.new_id")
+ checkScanSchemata(query,
+
"struct<new_items:array<struct<children:array<struct<new_id:int>>>>,idx:int>")
+ checkAnswer(query, Row(Seq(42)))
+ }
+ }
+ }
+ }
+ }
+
+ test("dynamic lookups preserve complex column defaults and constant lookups
still prune") {
+ withTempPath { dir =>
+ withTable("t") {
+ val path = dir.getCanonicalPath
+ sql(
+ s"""CREATE TABLE t (idx INT, k STRING,
+ | items ARRAY<STRUCT<a: INT, b: INT>> DEFAULT array(),
+ | byKey MAP<STRING, STRUCT<a: INT, b: INT>> DEFAULT map()
+ |) USING parquet LOCATION '$path'""".stripMargin)
+ sql("INSERT INTO t SELECT 0, 'k', array(named_struct('a', 5, 'b', 6)),
" +
+ "map('k', named_struct('a', 7, 'b', 8))")
+ sql(
+ """ALTER TABLE t ADD COLUMNS (
+ | arr ARRAY<STRUCT<a: INT, b: INT>> DEFAULT
array(named_struct('a', 11, 'b', 22)),
+ | m MAP<STRING, STRUCT<a: INT, b: INT>>
+ | DEFAULT map('k', named_struct('a', 33, 'b', 44))
+ |)""".stripMargin)
+
+ val data = spark.read.schema(spark.table("t").schema).parquet(path)
+ Seq("true", "false").foreach { vectorized =>
+ withSQLConf(vectorizedReaderEnabledKey -> vectorized) {
+ val query = data.selectExpr("arr[idx].b", "m[k].b", "items[0].b",
"byKey['k'].b",
+ "filter(items, x -> array(true, false)[idx])[0].b")
+ checkAnswer(query, Row(22, 44, 6, 8, 6))
+ checkScanSchemata(query,
"struct<idx:int,k:string,items:array<struct<b:int>>," +
+
"byKey:map<string,struct<b:int>>,arr:array<struct<a:int,b:int>>," +
+ "m:map<string,struct<a:int,b:int>>>")
+ }
+ }
+ }
+ }
+ }
+
+ test("dynamic lookups preserve defaults on nested fields") {
+ withTempPath { dir =>
+ val path = dir.getCanonicalPath
+ sql(
+ """SELECT 0 AS i,
+ | named_struct('arr', array(named_struct('a', 1, 'b', 22))) AS s,
+ | map(0, named_struct('anchor', 7, 'n', named_struct('a', 3, 'b',
44))) AS m
+ |""".stripMargin).write.parquet(path)
+
+ val pair = StructType.fromDDL("a INT, b INT")
+ val default = "named_struct('a', 5, 'b', 6)"
+ val arr = StructField("arr",
ArrayType(pair)).withExistenceDefaultValue(s"array($default)")
+ val n = StructField("n", pair).withExistenceDefaultValue(default)
+ val schema = new StructType()
+ .add("i", IntegerType)
+ .add("s", new StructType().add(arr))
+ .add("m", MapType(IntegerType, new StructType().add("anchor",
IntegerType).add(n)))
+
+ for (vectorized <- Seq("true", "false")) {
+ withSQLConf(vectorizedReaderEnabledKey -> vectorized) {
+ val data = spark.read.schema(schema).parquet(path)
+ checkAnswer(data.selectExpr("s.arr[i].b", "m[i].n.b"), Row(22, 44))
+ checkAnswer(data.selectExpr("m[i].anchor", "m[0].n.b"), Row(7, 44))
+ }
+ }
+ }
+ }
+
+ test("dynamic array selection preserves bounds in legacy missing-field
mode") {
+ withTempPath { dir =>
+ val path = dir.getCanonicalPath
+ sql("SELECT array(named_struct('present', 1)) AS items, 1 AS
idx").write.parquet(path)
+ val legacy =
SQLConf.LEGACY_PARQUET_RETURN_NULL_STRUCT_IF_ALL_FIELDS_MISSING.key
+ for (vectorized <- Seq("true", "false")) {
+ withSQLConf(legacy -> "true", SQLConf.ANSI_ENABLED.key -> "true",
Review Comment:
**Nit (P3):** `withSQLConf` puts the legacy flag in the session SQL conf,
and explicitly set SQL confs are copied over the Hadoop configuration that both
the planner and the reader read, so they always agree here. The V1 rule and
`ParquetScanBuilder` deliberately resolve the flag from the reader's effective
Hadoop configuration, so that `spark.hadoop.*` settings, and on V2 per-read
options, give the planner the same answer as the reader. If either were
switched to read `SQLConf` directly, this test would still pass, while a flag
set through those channels would prune `items` and return NULL instead of
raising `INVALID_ARRAY_INDEX`. That is the difference you reproduced with
`spark.hadoop.*` during review.
**Verification:**
- **Regression:** With the session SQL setting unset and the legacy flag
enabled only through the Hadoop configuration, an out-of-bounds row-dependent
array index under ANSI raises INVALID_ARRAY_INDEX on V1 and V2 with both
Parquet readers.
- **Regression:** On V2, enabling the legacy flag only through a per-read
option keeps the same error.
--
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]