spark-test commented on code in PR #58977:
URL: https://github.com/apache/spark/pull/58977#discussion_r4524407648
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/FailureSafeParser.scala:
##########
@@ -29,8 +29,12 @@ class FailureSafeParser[IN](
schema: StructType,
columnNameOfCorruptRecord: String) {
- private val corruptFieldIndex =
schema.getFieldIndex(columnNameOfCorruptRecord)
- private val actualSchema = StructType(schema.filterNot(_.name ==
columnNameOfCorruptRecord))
+ private val corruptFieldIndex =
+ ExprUtils.corruptRecordFieldIndex(schema, columnNameOfCorruptRecord)
Review Comment:
**Blocking (P1):** `FailureSafeParser` and `verifyColumnNameOfCorruptRecord`
are shared with the XML readers, which this PR says it leaves alone, but the
XML parser schemas still drop only a field named exactly like the option
(`XmlFileFormat.buildReader`, `DataFrameReader.xml`), and `from_xml` hands the
parser the whole schema. Now that this index is resolved case-insensitively,
the two sides disagree for XML.
Reading the code, `spark.read.schema("a STRING, _CORRUPT_RECORD STRING, b
STRING").option("rowTag", "row").xml(path)` over `<row><a>1</a><b>2</b></row>`
returns `b = null`: the parser emits `["1", null, "2"]`, this index drops
position 1 from `FailureSafeParser`'s schema, and positions 0 and 1 are copied
into `a` and `b`, so `"2"` is lost. On the base branch the row passes through
and `b` is `"2"`. Every field after such a field is shifted, a value that lands
in a field of another type fails later with a `ClassCastException`, and
`_CORRUPT_RECORD INT` now fails with `INVALID_CORRUPT_RECORD_TYPE`. This covers
XML file reads (any `multiLine` setting, archives, either parser),
`DataFrameReader.xml` on a `Dataset[String]`, and `from_xml`, which already
misplaced values this way for an exactly named field in the middle of the
schema.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -95,14 +95,59 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
throw QueryCompilationErrors.nonMapFunctionNotAllowedError()
}
+ /**
+ * Returns whether `fieldName` names the column a datasource writes corrupt
records to.
+ *
+ * The comparison goes through `SQLConf.resolver`, so it honours
`spark.sql.caseSensitive` like
+ * every other identifier comparison in the analyzer. Matching on `==`
instead leaves the field
+ * unrecognised whenever the schema and the `columnNameOfCorruptRecord`
option differ only in
+ * case: the column is then treated as ordinary data, and the record that
should have been
+ * captured in it is lost.
+ */
+ def isCorruptRecordColumn(fieldName: String, columnNameOfCorruptRecord:
String): Boolean = {
+ SQLConf.get.resolver(fieldName, columnNameOfCorruptRecord)
+ }
+
+ /**
+ * Returns `schema` without the column a datasource writes corrupt records
to, which is the
+ * schema the underlying record parser is given. The corrupt record column
holds the raw text
+ * of a record that failed to parse, so it is never read from the record
itself.
+ */
+ def schemaWithoutCorruptRecordColumn(
+ schema: StructType,
+ columnNameOfCorruptRecord: String): StructType = {
+ StructType(schema.filterNot(f => isCorruptRecordColumn(f.name,
columnNameOfCorruptRecord)))
Review Comment:
**Blocking (P1):** This filter drops every field that matches the option
ignoring case, but `FailureSafeParser` keeps only the one index that
`corruptRecordFieldIndex` takes from a `Locale.ROOT`-lowercased map, and each
side reads `spark.sql.caseSensitive` where it runs. Whenever they disagree,
`FailureSafeParser` copies the parser's row by position into the wrong fields
or reads past its end.
Reading the code, `spark.read.option("columnNameOfCorruptRecord",
"error").json(ds)` over a `Dataset[String]` holding `{"Error": "x"}` and the
malformed line `{"Error": ` fails: inference adds `error` for the malformed
line and merges fields by exact name into `[Error STRING, error STRING]`, this
reader runs no duplicate-name check, this filter leaves the JSON parser an
empty schema, and `FailureSafeParser` then reads position 0 of an empty row and
throws `ArrayIndexOutOfBoundsException` on the well-formed line. The base
branch returns `Error = "x"` and captures the malformed line in `error`.
The same split affects user schemas with two such fields in `from_json`,
`from_csv` and the `Dataset[String]` readers (exact duplicates included), names
that `equalsIgnoreCase` and lowercasing fold differently, a `Dataset[String]`
DataFrame built under one `spark.sql.caseSensitive` value and run under
another, and `df.rdd` actions, whose tasks resolve with the default setting
after `SQLExecutionRDD`'s conf scope has ended.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/json/JsonExpressionEvalUtils.scala:
##########
@@ -145,7 +145,8 @@ case class JsonToStructsEvaluator(
val (parserSchema, actualSchema) = nullableSchema match {
case s: StructType =>
ExprUtils.verifyColumnNameOfCorruptRecord(s,
parsedOptions.columnNameOfCorruptRecord)
- (s, StructType(s.filterNot(_.name ==
parsedOptions.columnNameOfCorruptRecord)))
+ (s, ExprUtils.schemaWithoutCorruptRecordColumn(
Review Comment:
**Non-blocking (P2):** `selectsCorruptRecord` in `OptimizeCsvJsonExprs`,
which keeps the exactly named field from being pruned away, still compares
names exactly, so `from_json` is pruned to a case-variant corrupt record field
alone, or to a subset of fields that includes it. Once this line removes that
field, the JSON parser has nothing left to convert, so a record that fails on a
value rather than on JSON syntax is never flagged.
Reading the code, `from_json(v, 'a INT, _CORRUPT_RECORD
STRING')._CORRUPT_RECORD` over `{"a": "x"}` on a non-local input returns null,
while selecting the whole struct returns the raw text, so the data loss this PR
fixes for `from_json` remains on the default optimized path for extractions of
that field.
See **Shared repair plan 2** in the review body.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/json/JsonSuite.scala:
##########
@@ -2698,6 +2698,62 @@ abstract class JsonSuite
}
}
+ test("SPARK-59629: columnNameOfCorruptRecord honors
spark.sql.caseSensitive") {
+ val columnNameOfCorruptRecord = "_unparsed"
+ // The schema declares the corrupt record field in a different case to the
option value.
+ val schema = new StructType()
+ .add("a", IntegerType)
+ .add(columnNameOfCorruptRecord.toUpperCase(Locale.ROOT), StringType)
Review Comment:
**Nit (P3):** Because `_UNPARSED` is declared last, this test passes even if
`JsonFileFormat.buildReader` or `JsonPartitionReaderFactory.buildReader` goes
back to the exact-name filter: the parser would keep `_UNPARSED` as its last
column, `FailureSafeParser` would still copy position 0 into `a`, and both
expected rows would still match. Declaring the field ahead of a data column, as
in `_UNPARSED STRING, a INT`, makes that revert copy the empty slot into `a`
and fail the test. The CSV case does not have this gap, since a revert there
changes the token count.
**Verification:**
- **Regression:** With the case-variant field declared before a data column,
the JSON capture case returns the data column's value for the well-formed
record and the raw text for the malformed one under
spark.sql.caseSensitive=false, and treats the field as absent data under true,
on both the v1 and v2 paths.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -95,14 +95,59 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
throw QueryCompilationErrors.nonMapFunctionNotAllowedError()
}
+ /**
+ * Returns whether `fieldName` names the column a datasource writes corrupt
records to.
+ *
+ * The comparison goes through `SQLConf.resolver`, so it honours
`spark.sql.caseSensitive` like
+ * every other identifier comparison in the analyzer. Matching on `==`
instead leaves the field
+ * unrecognised whenever the schema and the `columnNameOfCorruptRecord`
option differ only in
+ * case: the column is then treated as ordinary data, and the record that
should have been
+ * captured in it is lost.
+ */
+ def isCorruptRecordColumn(fieldName: String, columnNameOfCorruptRecord:
String): Boolean = {
+ SQLConf.get.resolver(fieldName, columnNameOfCorruptRecord)
+ }
+
+ /**
+ * Returns `schema` without the column a datasource writes corrupt records
to, which is the
+ * schema the underlying record parser is given. The corrupt record column
holds the raw text
+ * of a record that failed to parse, so it is never read from the record
itself.
+ */
+ def schemaWithoutCorruptRecordColumn(
+ schema: StructType,
+ columnNameOfCorruptRecord: String): StructType = {
+ StructType(schema.filterNot(f => isCorruptRecordColumn(f.name,
columnNameOfCorruptRecord)))
+ }
+
+ /**
+ * Resolves the field a datasource writes corrupt records to, honouring
+ * `spark.sql.caseSensitive` the same way the rest of schema resolution
does. Returns None when
+ * the schema declares no such field, which is the normal case for a reader
that does not ask
+ * for the corrupt record.
+ */
+ def corruptRecordFieldIndex(
+ schema: StructType,
+ columnNameOfCorruptRecord: String): Option[Int] = {
+ // The name can be null: `from_csv` and `from_json` hold it in a transient
field, so it reads
Review Comment:
**Nit (P3):** Only `from_csv` reads the name back as null: `CsvToStructs`
keeps it in a `@transient private val`, while `JsonToStructs` keeps it in a
`@transient private lazy val` that is recomputed from `SQLConf` after
deserialization, so `from_json` never passes null here. The comment should name
only `from_csv`, as this PR's commit message already does.
**Verification:**
- **Inspection:** The comment that explains the null guard matches how
CsvToStructs and JsonToStructs declare their corrupt record name.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -95,14 +95,59 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
throw QueryCompilationErrors.nonMapFunctionNotAllowedError()
}
+ /**
+ * Returns whether `fieldName` names the column a datasource writes corrupt
records to.
+ *
+ * The comparison goes through `SQLConf.resolver`, so it honours
`spark.sql.caseSensitive` like
+ * every other identifier comparison in the analyzer. Matching on `==`
instead leaves the field
+ * unrecognised whenever the schema and the `columnNameOfCorruptRecord`
option differ only in
+ * case: the column is then treated as ordinary data, and the record that
should have been
+ * captured in it is lost.
+ */
+ def isCorruptRecordColumn(fieldName: String, columnNameOfCorruptRecord:
String): Boolean = {
Review Comment:
**Nit (P3):** The description defers XML, but nothing in the code says so:
`XmlFileFormat.buildReader`, `DataFrameReader.xml` and
`StaxXmlParser.parseColumn` still compare field names with `==` against the
option, and this helper's doc says the comparison honours
`spark.sql.caseSensitive` like every other identifier comparison without
mentioning that XML does not. A TODO at those XML comparisons, and a note here
that these helpers cover CSV and JSON, would keep a later reader from taking
XML's exact match as the intended rule.
**Verification:**
- **Inspection:** Every XML comparison of a field name with
columnNameOfCorruptRecord has a nearby TODO describing the deferred change, and
the CSV and JSON resolution's comment names those formats as its scope.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -95,14 +95,59 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
throw QueryCompilationErrors.nonMapFunctionNotAllowedError()
}
+ /**
+ * Returns whether `fieldName` names the column a datasource writes corrupt
records to.
+ *
+ * The comparison goes through `SQLConf.resolver`, so it honours
`spark.sql.caseSensitive` like
+ * every other identifier comparison in the analyzer. Matching on `==`
instead leaves the field
+ * unrecognised whenever the schema and the `columnNameOfCorruptRecord`
option differ only in
+ * case: the column is then treated as ordinary data, and the record that
should have been
+ * captured in it is lost.
+ */
+ def isCorruptRecordColumn(fieldName: String, columnNameOfCorruptRecord:
String): Boolean = {
+ SQLConf.get.resolver(fieldName, columnNameOfCorruptRecord)
Review Comment:
**Nit (P3):** `schemaWithoutCorruptRecordColumn` calls this once per schema
field, and inside a task `SQLConf.get` builds a new `ReadOnlySQLConf` on every
call. The CSV v1 per-file closure and `CSVPartitionReaderFactory` call the
helper twice per file split, and `JsonPartitionReaderFactory` once, so every
default CSV scan and v2 JSON scan builds one configuration object and does one
`spark.sql.caseSensitive` lookup per field per split, including reads with no
corrupt record field; the base branch compared strings. The work grows with
schema width times the number of splits, though it is likely small next to
opening a file, and it buys nothing: the setting cannot change within one call,
and the Parquet and ORC v2 reader factories read `caseSensitiveAnalysis` once.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/csv/CsvExpressionEvalUtils.scala:
##########
@@ -72,10 +72,12 @@ case class CsvToStructsEvaluator(
parsedOptions.columnNameOfCorruptRecord)
val actualSchema =
- StructType(nullableSchema.filterNot(_.name ==
parsedOptions.columnNameOfCorruptRecord))
+ ExprUtils.schemaWithoutCorruptRecordColumn(
+ nullableSchema, parsedOptions.columnNameOfCorruptRecord)
val actualRequiredSchema =
- StructType(requiredSchema.map(_.asNullable).getOrElse(nullableSchema)
- .filterNot(_.name == parsedOptions.columnNameOfCorruptRecord))
+ ExprUtils.schemaWithoutCorruptRecordColumn(
Review Comment:
**Blocking (P1):** `OptimizeCsvJsonExprs` still decides with an exact
comparison against `spark.sql.columnNameOfCorruptRecord` whether an extracted
`from_csv` field is the corrupt record column, so it prunes `from_csv` to a
field like `_CORRUPT_RECORD`. This line then removes that field from the pruned
required schema, leaving it empty, so `UnivocityParser` returns
`InternalRow.empty`, and `FailureSafeParser`, which now resolves the field,
reads position 0 of the empty row.
Reading the code,
`spark.sparkContext.parallelize(Seq("x,y,z")).toDF("v").selectExpr("from_csv(v,
'a INT, b STRING, _CORRUPT_RECORD STRING')._CORRUPT_RECORD")` throws
`ArrayIndexOutOfBoundsException` (the base branch returns `z`), while selecting
the whole struct captures the raw line as intended. So the case this PR adds
for `from_csv`, reading the corrupt record through a case-variant field, fails
whenever a query extracts that field alone over a non-local input with the
default optimizer and codegen settings. A `VALUES` list or a local `Seq` hides
it, because `ConvertToLocalRelation` evaluates the projection before the
pruning rule runs.
See **Shared repair plan 2** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/FailureSafeParser.scala:
##########
@@ -29,8 +29,12 @@ class FailureSafeParser[IN](
schema: StructType,
columnNameOfCorruptRecord: String) {
- private val corruptFieldIndex =
schema.getFieldIndex(columnNameOfCorruptRecord)
- private val actualSchema = StructType(schema.filterNot(_.name ==
columnNameOfCorruptRecord))
+ private val corruptFieldIndex =
+ ExprUtils.corruptRecordFieldIndex(schema, columnNameOfCorruptRecord)
Review Comment:
**Blocking (P1):** When the optimizer prunes `from_csv` to a single
extracted field, `CsvToStructsEvaluator` still gives `FailureSafeParser` the
full schema while `UnivocityParser` returns only the pruned field. Now that
this index also resolves a field spelled like the option in another case,
`FailureSafeParser` copies every other full-schema field from the one-field row
and returns a row laid out by the full schema, while the pruned
`GetStructField` reads position 0.
Reading the code,
`spark.sparkContext.parallelize(Seq("1,x")).toDF("v").selectExpr("from_csv(v,
'a INT, b STRING, _CORRUPT_RECORD STRING').a")` throws
`ArrayIndexOutOfBoundsException`, where the base branch returns 1. With the
two-field schema `'_CORRUPT_RECORD STRING, b STRING'`, `.b` over the line
`hello` returns null although the unpruned struct holds `b = hello`, and a
malformed line returns its raw text, or a `ClassCastException` when the
extracted field is not a string. This needs `from_csv` without options over a
non-local input with whole-stage codegen, all defaults. The base branch already
behaves this way for the exact name `_corrupt_record`; the PR extends it to
every case-variant spelling.
**Verification:**
- **Regression:** With CSV expression optimization on and a non-local input,
extracting an ordinary field from from_csv over a schema of two or more fields
that holds a corrupt record field, spelled exactly or in another case and
placed before or after the extracted field, returns the value the unpruned
struct holds for that field, for well-formed and malformed lines alike.
- **Behavior:** Selecting the whole from_csv struct still fills the corrupt
record field with the raw line for malformed records.
--
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]