cloud-fan commented on code in PR #58977:
URL: https://github.com/apache/spark/pull/58977#discussion_r4528178449
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/json/JsonExpressionEvalUtils.scala:
##########
@@ -137,14 +137,22 @@ case class JsonToStructsEvaluator(
@transient
private lazy val parser = {
- val parsedOptions = new JSONOptions(options, timeZoneId.get,
nameOfCorruptRecord)
+ def jsonOptions(parameters: Map[String, String]): JSONOptions =
+ new JSONOptions(parameters, timeZoneId.get, nameOfCorruptRecord)
+ // Resolve the corrupt record column once, also checking its type, and
parse with options
+ // that carry the resolved name, so that every comparison below is exact.
+ val parsedOptions = nullableSchema match {
+ case s: StructType =>
+ jsonOptions(ExprUtils.withResolvedColumnNameOfCorruptRecord(
Review Comment:
**Blocking (P1):** The `from_json` and `from_csv` evaluators now resolve the
corrupt record column when their transient lazy parser is first built, which
happens on the executor at the first row, and `corruptRecordCandidates` reads
`SQLConf.get.caseSensitiveAnalysis` at that moment. The readers are fine
because they resolve once on the driver at setup, but these expressions decide
wherever the task runs, while the `OptimizeCsvJsonExprs` pruning guards decide
on the driver with the session's setting.
Reading the code, with `spark.sql.caseSensitive=true` and
`df = sc.parallelize(Seq("""{"Error": "timeout", "a":
1}""")).toDF("v").selectExpr("from_json(v, 'Error STRING, a INT',
map('columnNameOfCorruptRecord', 'error')) AS p")`,
`df.collect()` returns `{timeout, 1}` but `df.rdd.collect()` returns `{null,
1}`. `Dataset.rdd` runs its action as a plain job, `SQLExecutionRDD.compute`
applies its captured conf only while it creates the iterator, and the parser is
built later, where `SQLConf.get` is a `ReadOnlySQLConf` over local properties
that hold no `spark.sql.caseSensitive`, so it sees `false`. The same split
happens for a plan built before the session setting changes and collected after
it, and for a pruned extraction of the case-variant field, which the guard
pruned as data and the evaluator then treats as the corrupt record column,
returning null for well-formed records. The base branch returns the data on
every path. So `spark.sql.caseSensitive=true`, the way back the migration guide
names, does not hold for `from_csv` and `from_json` on these paths.
This extends existing discussions
[1](https://github.com/apache/spark/pull/58977#issuecomment-6770611603),
[2](https://github.com/apache/spark/pull/58977#discussion_r4524407637),
[3](https://github.com/apache/spark/pull/58977#pullrequestreview-5841219133).
**Recommended change:** Add a defaulted case-sensitivity argument to
JsonToStructs and CsvToStructs that captures spark.sql.caseSensitive when the
expression is created during analysis, the same way JsonToStructs captures
spark.sql.charVarchar.standardSemantics.enabled, and pass it to their
evaluators. Give the ExprUtils corrupt record helpers and their shared
candidate rule an explicit case-sensitivity argument: the reader setup points
pass the session's setting as they read it today, the evaluators pass the
captured value, and the OptimizeCsvJsonExprs guards pass the value captured on
the expression they inspect. Add from_csv and from_json function tests that
consume results through Dataset.rdd under spark.sql.caseSensitive=true, and
that change the setting between building a plan and collecting it.
**Why this works:** The setting that decides between exact and
case-insensitive matching becomes a field of the expression, fixed when the
query or view is analyzed and serialized with the expression. The guard on the
driver and the evaluator on any executor then read the same value, whatever the
task's local properties hold or how the results are consumed.
**Scope:** Capture the case-sensitivity setting on from_json and from_csv at
analysis and use that captured value for both the optimizer's pruning decision
and the evaluator's corrupt record resolution.
**Compatibility:** The readers' resolution, the error classes and when they
are raised, and every result under an unchanged session setting stay exactly as
in this PR.
**Risks:** CsvToStructs has no custom extractor, so adding a constructor
field changes the arity of its pattern matches; the CSV pruning arm's match has
to be updated, or a custom extractor added as JsonToStructs has. The captured
value takes part in expression equality, so two otherwise identical from_json
or from_csv calls analyzed under different settings no longer compare equal;
this matters only across sessions with different settings, for example for
cached-plan matching.
**Constraints:** The CSV and JSON readers keep resolving with the driver
session's setting at setup; only the expressions take the captured value. A
view created under spark.sql.caseSensitive=true keeps exact matching when it is
queried from a session using the default, as views keep their other captured
settings. Under an unchanged session setting, every result and every pruning
decision stays as in this PR.
**Exclusions:**
- The transient corrupt record name in CsvToStructs and JsonToStructs's
executor-side read of spark.sql.columnNameOfCorruptRecord stay as on the base
branch; this repair captures only the setting that decides between exact and
case-insensitive matching.
- Adding the legacy exact-matching flag belongs to its own repair, which
folds the flag into the value this repair captures.
**Success:** For from_csv and from_json, the same field is the corrupt
record column whether results are consumed through collect() or Dataset.rdd,
and whether or not the session setting changed after the plan was built. The
optimizer's pruning guard and the evaluator decide with the same setting, so a
pruned extraction never lands on a field the evaluator then treats as the
corrupt record column. Setting spark.sql.caseSensitive to true keeps exact
matching for from_csv and from_json on every way of consuming results.
**Verification:**
- **Regression:** In a session with spark.sql.caseSensitive=true, from_json
and from_csv over a non-local input with a schema whose only match for the
corrupt record name differs in case return the field's data through
Dataset.rdd, the same as through collect(), both for the whole struct and for
an extraction of that field with expression optimization on.
- **Regression:** A from_json or from_csv DataFrame whose executed plan is
built under one spark.sql.caseSensitive value and collected after the session
switches to the other returns the rows the setting used at analysis implies,
with the pruned extraction of a case-variant field returning its data or its
raw line as that setting dictates rather than null.
- **Compatibility:** Under the default setting, from_csv and from_json with
a case-variant corrupt record field still capture malformed records and still
prune extractions of ordinary fields, and the CSV and JSON readers still
resolve with the session's setting when they are set up.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -95,6 +97,93 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
throw QueryCompilationErrors.nonMapFunctionNotAllowedError()
}
+ /**
+ * The fields of `schema` that `columnNameOfCorruptRecord` can refer to. A
field named exactly
+ * like the option always wins, so a schema that already works keeps its
meaning. Otherwise,
+ * under case-insensitive resolution, these are the fields the session
resolver matches.
+ */
+ private def corruptRecordCandidates(
+ schema: StructType,
+ columnNameOfCorruptRecord: String): Seq[StructField] = {
+ if (columnNameOfCorruptRecord == null) {
+ // `from_csv` holds the name in a transient field, so it reads back as
null after the
+ // expression is serialized. A null never names a field.
+ Nil
+ } else {
+ val exact = schema.fields.filter(_.name == columnNameOfCorruptRecord)
+ if (exact.nonEmpty || SQLConf.get.caseSensitiveAnalysis) {
Review Comment:
**Blocking (P1):** Under the default `spark.sql.caseSensitive=false`, this
fallback makes a field such as `Error`, with `columnNameOfCorruptRecord=error`,
the corrupt record column for the CSV and JSON readers, `from_csv` and
`from_json`, and no setting lets users who rely on the old exact matching keep
it.
Reading the code: `spark.read.option("columnNameOfCorruptRecord",
"error").schema("id INT, Error STRING").json(path)` over `{"id": 1, "Error":
"timeout"}` returns `Error = "timeout"` on the base branch and `NULL` with this
PR. An inferred JSON schema over clean records with an `Error` key reads
`Error` as `NULL` on every row with no error, because inference adds an exactly
named `error` field only when it sees a malformed record. For CSV, with schema
`a INT, Error STRING, b STRING` over the line `1,timeout,2`, selecting `b`
alone reads `"timeout"`, because the parser schema drops `Error` while tokens
still map by position.
The migration note's ways back are a non-colliding option name, which means
editing every affected read, or `spark.sql.caseSensitive=true`, which is
internal, documented as highly discouraged, and changes how every identifier in
the session resolves. The note also does not mention the CSV column shift or
the inferred-schema case, so affected users cannot tell from it that their data
is involved. You offered to add a `spark.sql.legacy.*` conf if a committer
prefers one, and this is the case for it.
This extends existing discussions
[1](https://github.com/apache/spark/pull/58977#issuecomment-6770611603),
[2](https://github.com/apache/spark/pull/58977#pullrequestreview-5841219133).
**Recommended change:** Add an internal boolean spark.sql.legacy.* entry to
SQLConf, false by default, whose true setting restores exact matching of
columnNameOfCorruptRecord. Fold it into the matching input of the ExprUtils
corrupt record helpers: when it is true, the candidate rule returns only fields
named exactly like the option, as it does under spark.sql.caseSensitive=true,
so the readers' resolution, the from_csv and from_json evaluators and the
optimizer's pruning guards all match exactly. The reader setup points read it
from the session together with the case-sensitivity setting, and from_json and
from_csv capture it when they are analyzed, together with that setting. Extend
the 4.4 migration-guide entry to name the flag as the way back, and to say that
for CSV a file that physically holds such a column now shifts the values of the
columns after it, and that an inferred JSON schema with such a key is affected
whenever inference sees no malformed record. Add tests that run
the readers and the functions with the flag on and off.
**Why this works:** The flag becomes one more input to the single matching
decision: wherever spark.sql.caseSensitive is read or captured to choose
between exact and case-insensitive matching, the choice is exact when either is
true. Because every consumer compares exactly against the name the candidate
rule returns, consulting the flag there restores the base branch's field choice
for readers, functions and pruning together.
**Scope:** Add a legacy configuration that restores exact matching of
columnNameOfCorruptRecord for the CSV and JSON readers and from_csv and
from_json, read wherever the case-sensitivity setting is read or captured, and
document it in the migration guide.
**Compatibility:** With the flag at its default, every result, error and
pruning decision is the same as with this PR, and under
spark.sql.caseSensitive=true matching is exact either way.
**Risks:** Until the case-sensitivity setting is captured on from_json and
from_csv, a flag read where the task runs is lost on Dataset.rdd actions, as
spark.sql.caseSensitive is; it fully holds there only together with that
capture. A captured flag takes part in expression equality, like the captured
case-sensitivity value, so two otherwise identical from_json or from_csv calls
analyzed under different flag values no longer compare equal.
**Constraints:** The flag defaults to false, so the PR's case-insensitive
matching stays the default. With the flag set to true, every CSV and JSON
reader, from_csv, from_json and the pruning guards treat only a field named
exactly like the option as the corrupt record column, as on the base branch.
The flag joins the exact-matching input that the corrupt record helpers take
from their callers, so the guards' fast path and the captured value need no
separate branch for it.
**Exclusions:**
- XML keeps matching exactly whatever the flag says, since the PR defers
moving it to the shared resolution.
**Success:** Setting the legacy flag to true restores the base branch's
exact matching of columnNameOfCorruptRecord for the CSV and JSON readers on the
v1 and v2 paths, the Dataset[String] readers, from_csv and from_json, without
changing how other identifiers resolve. from_csv and from_json honor the flag
however their results are consumed, including through Dataset.rdd. The
migration-guide entry names the flag as the way back and describes the CSV
column shift and the inferred-schema case.
**Verification:**
- **Behavior:** With the legacy flag set to true and spark.sql.caseSensitive
at its default, CSV and JSON file reads on the v1 and v2 paths, the
Dataset[String] readers, and from_csv and from_json over a schema with a field
that matches the option only ignoring case read that field as data, as the base
branch does, while an exactly named field is still the corrupt record column.
- **Regression:** A JSON read with an inferred schema over records that all
carry a key matching the option only ignoring case and parse cleanly reads that
key as the corrupt record column with the flag at its default, and returns the
key's values with the flag set to true.
- **Regression:** In a session with the flag set to true, from_json and
from_csv over a non-local input with a case-variant field return that field's
data through Dataset.rdd, the same as through collect(), and with expression
optimization on an extraction of that field is pruned as an ordinary field.
- **Inspection:** The 4.4 migration-guide entry names the flag and its
legacy setting, and says that for CSV the columns after such a column shift and
that an inferred JSON schema is affected when inference sees no malformed
record.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/OptimizeCsvJsonExprs.scala:
##########
@@ -45,9 +45,13 @@ import org.apache.spark.unsafe.types.UTF8String
object OptimizeCsvJsonExprs extends Rule[LogicalPlan] {
private def nameOfCorruptRecord = conf.columnNameOfCorruptRecord
- /** Whether the field this extracts is the corrupt record column of its
`JsonToStructs`. */
+ /**
+ * Whether the field this extracts is the corrupt record column of its
`JsonToStructs`. This
+ * follows the rule the evaluators resolve the column with, so a field that
matches the name
+ * only ignoring case counts under case-insensitive resolution.
+ */
private def selectsCorruptRecord(g: GetStructField): Boolean =
- g.childSchema(g.ordinal).name == nameOfCorruptRecord
+ ExprUtils.isCorruptRecordField(g.childSchema, g.ordinal,
nameOfCorruptRecord)
Review Comment:
**Non-blocking (P2):** `selectsCorruptRecord` judges the extracted field
against the full `from_json` schema, but the rewrite then hands the evaluator
the pruned schema, and the evaluator resolves the corrupt record column against
whatever schema it gets. An exactly named field wins only while it is in the
schema, so when the schema holds both `_corrupt_record` and `_CORRUPT_RECORD`,
the case variant is data in the full schema but becomes the corrupt record
column once pruning drops the exact field.
Reading the code, under the default settings
`SELECT c FROM (SELECT p.* FROM (SELECT from_json(value, '_corrupt_record
STRING, _CORRUPT_RECORD STRING, a INT') AS p FROM t)) AS x(r, c, a)`
over a non-local `t` holding `{"_CORRUPT_RECORD": "v", "a": 1}` is pruned to
`struct<_CORRUPT_RECORD>` and returns null, while the unpruned expression, the
same query with `spark.sql.optimizer.enableJsonExpressionOptimization=false`,
and the base branch return `v`. A view analyzed under
`spark.sql.caseSensitive=true` that selects the field by name, and a
`named_struct` of `_CORRUPT_RECORD` and `a`, reach the same rewrite. The CSV
arm is not affected, because the CSV evaluator resolves against the full schema.
Suggested fix: in the `from_json` `GetStructField` and `named_struct` arms,
prune only when every field the pruned schema keeps has the same corrupt record
role there as in the full schema, judged with the case sensitivity the
evaluator uses, and otherwise leave the expression unpruned.
This extends existing discussions
[1](https://github.com/apache/spark/pull/58977#issuecomment-6770611603),
[2](https://github.com/apache/spark/pull/58977#discussion_r4524407693).
**Verification:**
- **Regression:** With JSON expression optimization on, a non-local input,
and the schema _corrupt_record STRING, _CORRUPT_RECORD STRING, a INT,
extracting _CORRUPT_RECORD alone by ordinal, and inside a named_struct with a,
returns the record's _CORRUPT_RECORD value for a well-formed record, matching
the result with the optimization off.
- **Compatibility:** from_json extractions of ordinary fields over schemas
with only an exact or only a case-variant corrupt record field are still
pruned, and extractions of the corrupt record field alone are still not pruned,
as the existing pruning plan checks expect.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -95,6 +97,93 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
throw QueryCompilationErrors.nonMapFunctionNotAllowedError()
}
+ /**
+ * The fields of `schema` that `columnNameOfCorruptRecord` can refer to. A
field named exactly
+ * like the option always wins, so a schema that already works keeps its
meaning. Otherwise,
+ * under case-insensitive resolution, these are the fields the session
resolver matches.
+ */
+ private def corruptRecordCandidates(
+ schema: StructType,
+ columnNameOfCorruptRecord: String): Seq[StructField] = {
+ if (columnNameOfCorruptRecord == null) {
+ // `from_csv` holds the name in a transient field, so it reads back as
null after the
+ // expression is serialized. A null never names a field.
+ Nil
+ } else {
+ val exact = schema.fields.filter(_.name == columnNameOfCorruptRecord)
+ if (exact.nonEmpty || SQLConf.get.caseSensitiveAnalysis) {
+ exact.toSeq
+ } else {
+ val resolver = SQLConf.get.resolver
+ schema.fields.filter(f => resolver(f.name,
columnNameOfCorruptRecord)).toSeq
+ }
+ }
+ }
+
+ /**
+ * Decides which field of `schema` is the corrupt record column of a CSV or
JSON reader and
+ * returns that field's exact name, honouring `spark.sql.caseSensitive`.
When no field matches,
+ * the name is returned unchanged. Several fields that match only ignoring
case are ambiguous
+ * and are rejected.
+ *
+ * A reader has to make this decision once and compare field names exactly
against the result
+ * everywhere else, including on executors: the record parser drops the
column from its schema
+ * and [[org.apache.spark.sql.catalyst.util.FailureSafeParser]] copies the
parsed row back by
+ * position, so the two must agree on the field or values land in the wrong
columns.
+ *
+ * This also checks that the resolved field is a nullable string, as
+ * [[verifyColumnNameOfCorruptRecord]] does, reporting the name as the user
spelled it.
+ *
+ * XML does not resolve the name this way yet and still matches it exactly.
+ */
+ def resolveColumnNameOfCorruptRecord(
+ schema: StructType,
+ columnNameOfCorruptRecord: String): String = {
+ val candidates = corruptRecordCandidates(schema, columnNameOfCorruptRecord)
+ val names = candidates.map(_.name).distinct
+ if (names.length > 1) {
+ throw QueryCompilationErrors.ambiguousColumnOrFieldError(
+ Seq(columnNameOfCorruptRecord), names.length, CurrentOrigin.get)
+ }
+ candidates.foreach { f =>
+ if (!f.dataType.isInstanceOf[StringType] || !f.nullable) {
+ throw QueryCompilationErrors.invalidFieldTypeForCorruptRecordError(
+ columnNameOfCorruptRecord, f.dataType)
+ }
+ }
+ names.headOption.getOrElse(columnNameOfCorruptRecord)
+ }
+
+ /**
+ * Returns the reader `options` with `columnNameOfCorruptRecord` set to the
name
+ * [[resolveColumnNameOfCorruptRecord]] picks for `schema`, so that the
options a reader hands
+ * to its parsers carry the resolved name.
+ */
+ def withResolvedColumnNameOfCorruptRecord(
+ options: Map[String, String],
+ schema: StructType,
+ columnNameOfCorruptRecord: String): Map[String, String] = {
+ val resolved = resolveColumnNameOfCorruptRecord(schema,
columnNameOfCorruptRecord)
+ if (resolved == columnNameOfCorruptRecord) {
+ options
+ } else {
+ CaseInsensitiveMap(options) +
(DataSourceOptions.COLUMN_NAME_OF_CORRUPT_RECORD -> resolved)
+ }
+ }
+
+ /**
+ * Whether the field at `ordinal` is one
[[resolveColumnNameOfCorruptRecord]] can pick as the
+ * corrupt record column of `schema`. Unlike the resolution this never
throws, so the optimizer
+ * can use it to keep such a field from being pruned.
+ */
+ def isCorruptRecordField(
+ schema: StructType,
+ ordinal: Int,
+ columnNameOfCorruptRecord: String): Boolean = {
+ val name = schema(ordinal).name
+ corruptRecordCandidates(schema, columnNameOfCorruptRecord).exists(_.name
== name)
Review Comment:
**Nit (P3):** Each call rebuilds the full candidate list, one or two filters
over `schema.fields` plus `SQLConf.get` lookups, to answer a question about one
field, and `OptimizeCsvJsonExprs` calls it for every JSON and CSV
`GetStructField` guard and for every field of a `named_struct`, on each pass of
the fixed-point batch. The base branch compared one name. Results do not
change; it is planning-time work that grows with the number of extractions
times the schema width.
A fast path gives the same answers without the scan: true when the field is
named exactly like the option; false for a null name, under case-sensitive
resolution, or when the resolver does not match the field; and only for a field
that matches the name ignoring case, true when no field is named exactly like
the option.
**Verification:**
- **Compatibility:** The candidate check gives the same answer as the full
candidate rule for a null name, an exact match, a lone case variant, an exact
field alongside a variant, several variants, and case-sensitive resolution, for
every field position in each schema.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/csv/CsvExpressionEvalUtils.scala:
##########
@@ -57,32 +57,37 @@ case class CsvToStructsEvaluator(
// scalastyle:off nonascii
val exprOptions = options ++ Map("lineSep" -> '\uFFFF'.toString)
// scalastyle:on nonascii
- val parsedOptions = new CSVOptions(
- exprOptions,
+ def csvOptions(parameters: Map[String, String]): CSVOptions = new
CSVOptions(
+ parameters,
columnPruning = true,
defaultTimeZoneId = timeZoneId.get,
defaultColumnNameOfCorruptRecord = nameOfCorruptRecord)
+ // Resolve the corrupt record column once, also checking its type, and
parse with options
+ // that carry the resolved name, so that every comparison below is exact.
+ val parsedOptions =
csvOptions(ExprUtils.withResolvedColumnNameOfCorruptRecord(
+ exprOptions, nullableSchema,
csvOptions(exprOptions).columnNameOfCorruptRecord))
Review Comment:
**Nit (P3):** `csvOptions(exprOptions)` is built only to read
`columnNameOfCorruptRecord`, and `csvOptions(...)` is then built again over the
map `withResolvedColumnNameOfCorruptRecord` returns, which is the same map
unless the resolved name differs; `JsonToStructsEvaluator` does the same with
`jsonOptions`. Since the parser is a transient lazy val, every task pays one
extra options construction per expression occurrence, for identical options.
Keeping the first object and building a second one only when the returned map
differs gives the same options.
**Verification:**
- **Inspection:** Each evaluator's parser setup constructs a second options
object only on the branch where the resolved name differs from the one in the
first options object.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/xml/XmlSuite.scala:
##########
@@ -3875,6 +3875,26 @@ class XmlSuite
}
}
+ test("SPARK-59629: a case variant of the corrupt record column stays a data
column") {
+ // XML still matches `columnNameOfCorruptRecord` exactly, so
`_CORRUPT_RECORD` is ordinary
+ // data here and the fields after it keep their values.
+ val schema = "a STRING, _CORRUPT_RECORD STRING, b STRING"
+ val record = "<row><a>1</a><b>2</b></row>"
Review Comment:
**Nit (P3):** This record is well formed and has no `_CORRUPT_RECORD`
element, so `Row("1", null, "2")` is the answer under either rule: if XML
started treating `_CORRUPT_RECORD` as the corrupt record column, it would still
read null here and `b` would still be `"2"`. The test catches a column shift,
but not the change its name describes. Giving the record a value, for example
`<_CORRUPT_RECORD>c</_CORRUPT_RECORD>`, and expecting `"c"` back on all three
paths makes it pin that the field stays data.
**Verification:**
- **Behavior:** For the file read, xml on a Dataset[String] and from_xml
with the schema a STRING, _CORRUPT_RECORD STRING, b STRING, a record that
carries a value for _CORRUPT_RECORD returns that value in the field and b's own
value.
--
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]