spark-test commented on code in PR #60398:
URL: https://github.com/apache/spark/pull/60398#discussion_r4556302495
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/csv/UnivocityGenerator.scala:
##########
@@ -209,6 +209,18 @@ class UnivocityGenerator(
}
}
+ private lazy val skipSingleNullValueRecord =
+
SQLConf.get.getConf(SQLConf.LEGACY_CSV_SKIP_SINGLE_NULL_VALUE_RECORD_ON_WRITE)
+ // A record holding only an empty null token is an empty line, which the
writer skips; write it
+ // as a quoted empty string instead, independent of `emptyValue`, so it
reads back as null.
+ private val loneNullRecord = s"${options.quote}${options.quote}"
+ private val nullIsEmptyLine = !nullAsQuotedEmptyString && !options.quoteAll
&&
Review Comment:
**Non-blocking (P2):** This predicate decides from the option strings, not
from what the writer actually renders, whether a lone null becomes an empty
line. So some single-column writes still lose every null row, while the conf
doc, the comment above and the migration note say the row is kept.
By the review's reading of this code and of univocity 2.9.1:
- When nulls are written through `emptyValue`
(`treatNullAsEmptyString=true`, or
`spark.sql.legacy.nullValueWrittenAsQuotedEmptyStringCsv=true` with the option
unset), `convertRow` passes `nullValue`, and the writer substitutes
`emptyValue` for it. With `emptyValue` set to an empty string or to null, or
with `nullValue` set to null, the field renders as nothing. For example,
`Seq("A", null).toDF("code").write.option("treatNullAsEmptyString",
"true").option("emptyValue", "").csv(p)` writes only `A`.
- The `options.nullValue.isEmpty` check misses whitespace. Spark trims
whitespace on write by default (`ignoreLeadingWhiteSpace` and
`ignoreTrailingWhiteSpace`), so `.option("nullValue", " ")` on its own also
renders the null as nothing and drops the row. A whitespace-only `emptyValue`
does the same when nulls are written through `emptyValue`.
For these records `to_csv` goes through the fallback in `writeToString` and
returns an empty string instead of `""`.
Suggested fix: derive the predicate from how the configured writer renders a
one-field null. For example, compute it once, lazily, by passing the value
`convertRow` writes for a null to `writeRowToString` on a separate `CsvWriter`
built from `options.asWriterSettings`, and treat a `null` result as an empty
line. Keep the disabled-quote exclusion and the legacy gate. Then update the
comment here, the migration note's "the one case" wording, and the
`treatNullAsEmptyString=true` text in the CSV option reference.
**Verification:**
- **Regression:** Writing a single-column DataFrame with null rows writes
one quoted empty string line per null row, and reading the files back with
default reader options returns those rows as null, in configurations whose null
the writer would otherwise render as nothing: at least
treatNullAsEmptyString=true with an empty emptyValue,
treatNullAsEmptyString=true with a null nullValue,
spark.sql.legacy.nullValueWrittenAsQuotedEmptyStringCsv=true with an empty
emptyValue, and a whitespace-only nullValue such as ' ' with the default
whitespace trimming.
- **Behavior:** In the null-as-empty-string mode, a single-column null is
still written as the emptyValue when that value renders as visible text, such
as '-', and as the quoted empty string with the default emptyValue, exactly as
on the base branch.
- **Behavior:** to_csv of a one-field struct holding a null, with
treatNullAsEmptyString=true and an empty emptyValue, returns the quoted empty
string both when the call is constant-folded and when it is evaluated in a
generated projection.
- **Compatibility:** With
spark.sql.legacy.csv.skipSingleNullValueRecordOnWrite=true, the same
single-column writes drop the null rows exactly as on the base branch.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/csv/CSVSuite.scala:
##########
@@ -869,6 +870,83 @@ abstract class CSVSuite
}
}
+ private def checkSingleNullValueRecords(skipped: Boolean): Unit = {
+
withSQLConf(SQLConf.LEGACY_NULL_VALUE_WRITTEN_AS_QUOTED_EMPTY_STRING_CSV.key ->
"false") {
+ val df = Seq(("A", "west"), (null, "west"), ("B", "east"), (null,
"east"),
+ (null, "east")).toDF("code", "region")
+ val ab = Seq("A", "B")
+ def kept(token: String) = ab ++ Seq.fill(if (skipped) 0 else 3)(token)
+ // (write options, read options, lines written). A non-empty nullValue
or quoteAll never
+ // wrote an empty line; with quoting off a null cannot be told from an
empty line.
+ Seq[(Map[String, String], Map[String, String], Seq[String])](
+ (Map.empty, Map.empty, kept("\"\"")),
+ (Map("emptyValue" -> "-"), Map.empty, kept("\"\"")),
+ (Map("emptyValue" -> ""), Map.empty, kept("\"\"")),
+ (Map("treatNullAsEmptyString" -> "false"), Map.empty, kept("\"\"")),
+ (Map("nullValue" -> null), Map.empty, kept("\"\"")),
+ (Map("quote" -> "'"), Map("quote" -> "'"), kept("''")),
+ (Map("nullValue" -> "N"), Map("nullValue" -> "N"), ab ++
Seq.fill(3)("N")),
+ (Map("quoteAll" -> "true"), Map.empty, Seq("\"A\"", "\"B\"") ++
Seq.fill(3)("\"\"")),
+ (Map("quote" -> ""), Map.empty, ab)).foreach { case (opts, readOpts,
lines) =>
+ withTempPath { path =>
+ df.select("code").write.options(opts).csv(path.getCanonicalPath)
Review Comment:
**Nit (P3):** The helper builds a two-column `df` but only ever writes
`df.select("code")`, so nothing pins the `row.numFields == 1` term in
`isLoneNullRecord`. Suppose that term regressed. A `(null, "west")` row would
then be written as `""` and lose its `region` value, and
`to_csv(named_struct('a', CAST(NULL AS STRING), 'b', 'x'))` would return `""`
instead of `,x`. The review found no existing CSV write or `to_csv` test that
writes a multi-column record with a leading null, so nothing would catch it.
Suggest also writing the two-column `df` here and asserting its `,west` and
`,east` lines, plus a two-field `to_csv` case with a leading null.
**Verification:**
- **Regression:** A two-column CSV write whose rows include a null first
value, with default bare-token null handling and
spark.sql.legacy.csv.skipSingleNullValueRecordOnWrite at its default, writes
lines that keep every delimiter and the remaining values, such as ,west. A
two-field to_csv with a leading null returns its delimited form rather than a
quoted empty string.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/csv/UnivocityGenerator.scala:
##########
@@ -231,11 +243,21 @@ class UnivocityGenerator(
* Writes a single InternalRow to CSV using Univocity.
*/
def write(row: InternalRow): Unit = {
- gen.writeRow(convertRow(row): _*)
+ if (isLoneNullRecord(row)) {
+ gen.writeRow(loneNullRecord)
Review Comment:
**Nit (P3):** Writing the quoted token here changes what
`treatNullAsEmptyString=false` does for one-field records. A lone null is now
written as `""`, as the new test row for that option expects, and with the
default `emptyValue` that is also how an actual empty string is written. The
CSV option reference still says that with `false` "a null is written as a bare,
unquoted empty token, so it can be told apart from an empty string"
(docs/sql-data-sources-csv.md). The `CSVOptions.treatNullAsEmptyString`
scaladoc, the comment above `nullAsQuotedEmptyString` in this file and the
`spark.sql.legacy.nullValueWrittenAsQuotedEmptyStringCsv` doc describe the same
bare token. Only the migration note mentions the exception. Suggest adding the
exception to those four descriptions: with quoting enabled, a record whose only
value is a null is written as a quoted empty string, because a bare token would
be an empty line that the writer drops, and setting
`spark.sql.legacy.csv.skipSingleNullValueR
ecordOnWrite` to `true` restores the bare token along with the dropped line.
**Verification:**
- **Inspection:** No description of treatNullAsEmptyString=false, or of
spark.sql.legacy.nullValueWrittenAsQuotedEmptyStringCsv set to false, still
says a null is always written as a bare token that can be told apart from an
empty string without naming the single-field exception.
##########
docs/sql-migration-guide.md:
##########
@@ -25,6 +25,7 @@ license: |
## Upgrading from Spark SQL 4.4 to 5.0
- Since Spark 5.0, the Spark Thrift Server refuses to start when
`hive.server2.enable.doAs` is `true` and `hive.server2.authentication` verifies
user identities (any recognized type other than `NONE`/`NOSASL`). It
impersonates the connecting user for Hive metastore calls and driver-side file
system access, but executor-side data access still runs as the server's own
service identity, so storage-level permissions are checked against the service
principal rather than the connecting user (SPARK-5159). Spark 4.4 logs a
warning for the same configuration. To restore the previous behavior, set
`spark.sql.hive.thriftServer.allowIneffectiveDoAs` to `true`. Setting
`hive.server2.enable.doAs` to `false` also starts the server, but note that it
stops impersonating metastore calls as well, so it is not a no-op.
+- Since Spark 5.0, the CSV data source and `to_csv` keep a record whose only
value is a null written as an empty token (the default `nullValue`). Previously
such a record was an empty line, which the writer dropped, so a single-column
CSV write lost its null rows and `to_csv` of a one-field struct holding a null
failed or returned null. The record is now written as a quoted empty string
(`""`), which the CSV reader reads back as null unless a custom read
`emptyValue` is set; this applies even with a custom `emptyValue` and with
`treatNullAsEmptyString=false`, the one case where that option no longer writes
a null as an unquoted empty token. `to_csv` also returns an empty string
instead of failing for any other record that is an empty line, such as an empty
string with `emptyValue` set to an empty string. To restore the previous
behavior, set `spark.sql.legacy.csv.skipSingleNullValueRecordOnWrite` to `true`.
Review Comment:
**Nit (P3):** This entry announces a data-loss fix but does not state its
boundary. With quoting disabled (`quote` set to an empty string),
`nullIsEmptyLine` excludes the record (`options.quote != '\u0000'`). By the
review's reading of the code, a single-column null row is still written as an
empty line and dropped, and `to_csv` returns an empty string rather than `""`.
The PR's own test row `(Map("quote" -> ""), Map.empty, ab)` pins this, and only
the test comment explains it. This sentence ("The record is now written as a
quoted empty string"), the
`spark.sql.legacy.csv.skipSingleNullValueRecordOnWrite` doc ("whatever
`emptyValue` is") and the comment at the predicate all leave it out. A user who
disables quoting is therefore told the rows are kept. Suggest naming the
exemption in all three places: without a quote character no token can represent
the null, so the row is still dropped.
**Verification:**
- **Inspection:** The migration note, the doc of
spark.sql.legacy.csv.skipSingleNullValueRecordOnWrite and the comment at the
lone-null predicate each name the disabled-quote exemption, and none of them
still says the record is written as a quoted empty string without that
exception.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/csv/CSVSuite.scala:
##########
@@ -869,6 +870,83 @@ abstract class CSVSuite
}
}
+ private def checkSingleNullValueRecords(skipped: Boolean): Unit = {
+
withSQLConf(SQLConf.LEGACY_NULL_VALUE_WRITTEN_AS_QUOTED_EMPTY_STRING_CSV.key ->
"false") {
+ val df = Seq(("A", "west"), (null, "west"), ("B", "east"), (null,
"east"),
+ (null, "east")).toDF("code", "region")
+ val ab = Seq("A", "B")
+ def kept(token: String) = ab ++ Seq.fill(if (skipped) 0 else 3)(token)
+ // (write options, read options, lines written). A non-empty nullValue
or quoteAll never
+ // wrote an empty line; with quoting off a null cannot be told from an
empty line.
+ Seq[(Map[String, String], Map[String, String], Seq[String])](
+ (Map.empty, Map.empty, kept("\"\"")),
+ (Map("emptyValue" -> "-"), Map.empty, kept("\"\"")),
+ (Map("emptyValue" -> ""), Map.empty, kept("\"\"")),
+ (Map("treatNullAsEmptyString" -> "false"), Map.empty, kept("\"\"")),
+ (Map("nullValue" -> null), Map.empty, kept("\"\"")),
+ (Map("quote" -> "'"), Map("quote" -> "'"), kept("''")),
+ (Map("nullValue" -> "N"), Map("nullValue" -> "N"), ab ++
Seq.fill(3)("N")),
+ (Map("quoteAll" -> "true"), Map.empty, Seq("\"A\"", "\"B\"") ++
Seq.fill(3)("\"\"")),
+ (Map("quote" -> ""), Map.empty, ab)).foreach { case (opts, readOpts,
lines) =>
+ withTempPath { path =>
+ df.select("code").write.options(opts).csv(path.getCanonicalPath)
+ checkAnswer(spark.read.text(path.getCanonicalPath),
lines.map(Row(_)))
+ checkAnswer(spark.read.options(readOpts).schema("code
STRING").csv(path.getCanonicalPath),
+ (ab ++ Seq.fill(lines.size - 2)(null: String)).map(Row(_)))
+ }
+ }
+ withTempPath { path =>
+ df.write.partitionBy("region").csv(path.getCanonicalPath)
+ checkAnswer(
+ spark.read.schema("code STRING, region
STRING").csv(path.getCanonicalPath)
+ .groupBy("region").agg("*" -> "count", "code" -> "count"),
+ if (skipped) Seq(Row("east", 1L, 1L), Row("west", 1L, 1L))
+ else Seq(Row("east", 3L, 1L), Row("west", 2L, 1L)))
+ }
+ val folded = sql("SELECT to_csv(named_struct('code', CAST(NULL AS
STRING)))")
+ checkAnswer(folded, Row(if (skipped) null else "\"\""))
+ val toCsv = spark.range(2).selectExpr(
+ "to_csv(named_struct('code', CASE WHEN id = 0 THEN 'A' END))",
+ "to_csv(named_struct('code', CASE WHEN id = 0 THEN '' END),
map('emptyValue', ''))")
+ if (skipped) {
+ val e = intercept[SparkException](toCsv.collect())
+ assert(Utils.getRootCause(e).isInstanceOf[NullPointerException])
+ } else {
+ checkAnswer(toCsv, Seq(Row("A", ""), Row("\"\"", "\"\"")))
+ }
+ }
+ }
+
+ test("CSV write keeps a single-column record whose value is null") {
+ checkSingleNullValueRecords(skipped = false)
+ }
+
+ test("CSV write keeps a single-column record whose value is null " +
+ "(gate off reproduces the bug)") {
+ withSQLConf(SQLConf.LEGACY_CSV_SKIP_SINGLE_NULL_VALUE_RECORD_ON_WRITE.key
-> "true") {
+ checkSingleNullValueRecords(skipped = true)
+ }
+ }
+
+ test("CSV write keeps a single-column record whose value is null " +
+ "(reads tables written with the gate off)") {
+ val gate = SQLConf.LEGACY_CSV_SKIP_SINGLE_NULL_VALUE_RECORD_ON_WRITE.key
Review Comment:
**Nit (P3):** `gate` holds
`spark.sql.legacy.csv.skipSingleNullValueRecordOnWrite`, so `withSQLConf(gate
-> "true")` below writes the legacy, row-dropping files, which this test's
title calls "written with the gate off", and `gate -> "false"` writes the fixed
files. That reads backwards, and it makes it easy to invert the writes or the
expected rows when extending the test. Suggest naming the value after the conf
it holds (for example `legacySkip`), or wording both titles as "legacy conf
enabled".
**Verification:**
- **Inspection:** In the single-column null tests, every title that names
the legacy state matches the value assigned to
spark.sql.legacy.csv.skipSingleNullValueRecordOnWrite in the block it
describes, and no identifier named for a gate holds the inverted conf.
--
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]