dongjoon-hyun commented on code in PR #60101:
URL: https://github.com/apache/spark/pull/60101#discussion_r4500023911


##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/CaseInsensitiveMap.scala:
##########
@@ -43,10 +43,14 @@ class CaseInsensitiveMap[T] private (val originalMap: 
Map[String, T])
 
   override def +[B1 >: T](kv: (String, B1)): CaseInsensitiveMap[B1] = 
this.updated(kv._1, kv._2)
 
-  def ++(xs: IterableOnce[(String, T)]): CaseInsensitiveMap[T] = {
-    xs.iterator.foldLeft(this) { (m, kv) => m.updated(kv._1, kv._2) }
+  override def concat[B1 >: T](xs: IterableOnce[(String, B1)]): 
CaseInsensitiveMap[B1] = {
+    xs.iterator.foldLeft(new CaseInsensitiveMap[B1](originalMap)) { (m, kv) =>

Review Comment:
   **3. [Low] `concat` lowercases the keys of a `CaseInsensitiveMap` operand**
   
   When `xs` is itself a `CaseInsensitiveMap`, `xs.iterator` yields its 
lowercased keys, because `iterator` returns `keyLowerCasedMap.iterator`. So 
`ci1 ++ ci2` stores the keys of `ci2` lowercased in `originalMap`:
   
   ```scala
   val m = CaseInsensitiveMap(Map("a" -> "1")) ++
     
CaseInsensitiveMap(Map("fs.azure.skipUserGroupMetadataDuringInitialization" -> 
"true"))
   // m.originalMap has "fs.azure.skipusergroupmetadataduringinitialization"
   ```
   
   `mergeOptionsIntoHadoopConf` then sets the lowercased key, and Hadoop 
ignores it. The old `++` had the same problem, but now that this PR relies on 
`++` to keep the original keys, could `concat` iterate `originalMap` when `xs` 
is a `CaseInsensitiveMap`?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/ArchiveReadSuiteBase.scala:
##########
@@ -430,10 +430,18 @@ trait ArchiveReadSuiteBase extends QueryTest with 
SharedSparkSession {
           s"keep/data.$fileExtension" -> encodeFile(sampleDf((1, "keep"))),
           s"skip/data.$fileExtension" ->
             encodeFile(Seq((2, "skip", "x")).toDF("id", "name", "extra"))))
-        val schema = inferredSchema(
-          Seq(archive.getCanonicalPath), Map("archivePathFilter" -> "keep/*"))
-        assert(!schema.fieldNames.contains("extra"),
-          s"inference read a filtered-out entry; got $schema")
+        val optionSets = if (inferenceSamplesOneFile) {
+          Seq(
+            Map("archivePathFilter" -> "keep/*"),
+            Map("archivePathFilter" -> "keep/*", "mergeSchema" -> "true"))

Review Comment:
   **1. [Medium] ORC `mergeSchema` still needs the exact camelCase 
`archivePathFilter`**
   
   This covers only the spelling `archivePathFilter`. With `mergeSchema`, 
`OrcUtils.readOrcSchemasInParallel` looks the glob up in the conf by that exact 
key ([OrcUtils.scala 
L228-L229](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/orc/OrcUtils.scala#L228-L229)).
 Before this PR the key arrived lowercased, and now it arrives as the user 
wrote it. So a spelling such as `archivepathfilter`, which the scan and the 
non-merge inference accept because they read the option case-insensitively 
([L198-L199](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/orc/OrcUtils.scala#L198-L199)),
 still leaves the filter unset during the merge, in both V1 and V2. The 
inferred schema then picks up columns from filtered-out entries, like `extra` 
here, and they read back all-null.
   
   `ParquetFileFormat.mergeSchemasInParallel` avoids this by resolving the 
option case-insensitively and setting the canonical key in the conf 
([L776-L779](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetFileFormat.scala#L776-L779)).
 Could `OrcUtils.inferSchema` do the same, and could this test also cover a 
lowercase spelling?



##########
sql/core/src/main/scala/org/apache/spark/sql/internal/SessionState.scala:
##########
@@ -120,11 +120,7 @@ private[sql] class SessionState(
 
   def newHadoopConfWithOptions(options: Map[String, String]): Configuration = {
     val hadoopConf = newHadoopConf()
-    options.foreach { case (k, v) =>
-      if ((v ne null) && k != "path" && k != "paths") {
-        hadoopConf.set(k, v)
-      }
-    }
+    DataSourceUtils.mergeOptionsIntoHadoopConf(options, hadoopConf)

Review Comment:
   **2. [Medium] No way to restore the previous behavior**
   
   Thank you for adding the migration note for item 2 of my previous review. 
This change ships in Spark 4.4.0, a feature release, and it can silently change 
what existing tables and jobs do. An option such as 
`Parquet.Enable.Dictionary`, a mixed-case spelling of a lowercase Hadoop key, 
used to reach the conf lowercased and took effect, and now it is ignored 
without an error. Spark usually offers a `spark.sql.legacy.*` config for this 
kind of change. Could we add one that restores the lowercased keys, and mention 
it in the migration note? If we keep the change without one, should it be a 
master-only change for Spark 5.0.0?



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/CaseInsensitiveMap.scala:
##########
@@ -43,10 +43,14 @@ class CaseInsensitiveMap[T] private (val originalMap: 
Map[String, T])
 
   override def +[B1 >: T](kv: (String, B1)): CaseInsensitiveMap[B1] = 
this.updated(kv._1, kv._2)
 
-  def ++(xs: IterableOnce[(String, T)]): CaseInsensitiveMap[T] = {
-    xs.iterator.foldLeft(this) { (m, kv) => m.updated(kv._1, kv._2) }
+  override def concat[B1 >: T](xs: IterableOnce[(String, B1)]): 
CaseInsensitiveMap[B1] = {

Review Comment:
   **7. [Nit] `concat` rebuilds the map once per element**
   
   Each `updated` call filters `originalMap` and builds a new 
`CaseInsensitiveMap`, which recomputes `keyLowerCasedMap`. So adding m entries 
to n keys costs O(m * (n + m)), and the seed recomputes `keyLowerCasedMap` even 
when `xs` is empty. Since every `++` through a `Map` reference now comes here 
instead of `MapOps.concat`, could this build the result in one pass, for 
example by deduplicating `xs` by lowercased key, filtering `originalMap` once, 
and creating a single `CaseInsensitiveMap`? Option maps are small, so this is 
not a blocker.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSourceUtils.scala:
##########
@@ -49,28 +49,28 @@ import org.apache.spark.util.Utils
 object DataSourceUtils extends PredicateHelper {
 
   /**
-   * Merges write options into a Hadoop configuration. Keys "path" and "paths" 
are excluded.
-   * This ensures per-write options are present in the conf even if they were 
added to the
-   * options map after the Hadoop conf was originally created.
+   * Merges data source options into a Hadoop configuration. Keys "path" and 
"paths" are excluded.
+   * Callers are expected to pass a map that preserves the original key 
casing; an unmodified
+   * [[CaseInsensitiveMap]] is also unwrapped to its `originalMap` as a 
safeguard.
    */
-  def mergeWriteOptionsIntoHadoopConf(
+  def mergeOptionsIntoHadoopConf(
       options: Map[String, String], conf: Configuration): Unit = {
-    // CaseInsensitiveMap.iterator yields lowercased keys, but Hadoop 
Configuration is
-    // case-sensitive. Use the original map to preserve the user's key casing.
+    // Hadoop Configuration is case-sensitive. Callers should pass a map with 
the original keys,
+    // and we also unwrap CaseInsensitiveMap here since its iterator yields 
lowercased keys.
     val rawOptions = options match {
       case ci: CaseInsensitiveMap[String @unchecked] => ci.originalMap
       case other => other
     }
     rawOptions.foreach { case (k, v) =>

Review Comment:
   **6. [Low] Spellings that differ only in case now all reach the conf**
   
   `originalMap` can hold several spellings of one key, for example from a data 
source table:
   
   ```sql
   CREATE TABLE t (id INT) USING parquet
   OPTIONS ('parquet.filter.columnindex.enabled' 'true', 
'PARQUET.FILTER.COLUMNINDEX.ENABLED' 'false');
   ```
   
   Before this PR, `newHadoopConfWithOptions` iterated the lowercased view, so 
a DSv1 read got one value per key in the conf, the same value that the 
case-insensitive option lookup returns. Now every spelling is set, and Parquet 
looks up only `parquet.filter.columnindex.enabled`, so the value that applies 
can differ from what the case-insensitive view returns. 
`CaseInsensitiveStringMap` warns about such duplicates 
([L64-L66](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/catalyst/src/main/java/org/apache/spark/sql/util/CaseInsensitiveStringMap.java#L64-L66)).
 Could this keep one spelling per key, consistent with the lowercased view, or 
at least log a warning?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/FileTable.scala:
##########
@@ -66,7 +66,7 @@ abstract class FileTable(
       // We are reading from the results of a streaming query. We will load 
files from
       // the metadata log instead of listing them using HDFS APIs.
       new MetadataLogFileIndex(sparkSession, new Path(paths.head),
-        options.asScala.toMap, userSpecifiedSchema)
+        caseSensitiveMap, userSpecifiedSchema)

Review Comment:
   **5. [Low] The metadata log of a streaming sink is still read without the 
options**
   
   This map now keeps its casing, but `MetadataLogFileIndex` opens 
`_spark_metadata` with `newHadoopConf()` ([MetadataLogFileIndex.scala 
L47](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MetadataLogFileIndex.scala#L47)),
 and `FileStreamSinkLog` reads the log through `HDFSMetadataLog`, whose 
`CheckpointFileManager` also uses `newHadoopConf()` ([HDFSMetadataLog.scala 
L70](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/checkpointing/HDFSMetadataLog.scala#L70)).
 So a file system option given only as a data source option, such as a 
credential or the `ds_Option` that `FakeFileSystemRequiringDSOption` requires, 
reaches `FileStreamSink.hasMetadata` above but not the metadata log read. DSv1 
has the same gap ([DataSource.scala 
L413](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7
 
eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSource.scala#L413)),
 and `CommonFileDataSourceSuite` does not read the output of a streaming sink, 
so no test covers it. This PR did not cause it, so like `FileStreamSource` in 
my previous review, it can be a separate JIRA issue.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/parquet/ParquetTable.scala:
##########
@@ -41,7 +41,7 @@ case class ParquetTable(
     ParquetScanBuilder(sparkSession, fileIndex, schema, dataSchema, 
mergedOptions(options))
 
   override def inferSchema(files: Seq[FileStatus]): Option[StructType] =
-    ParquetUtils.inferSchema(sparkSession, options.asScala.toMap, files)
+    ParquetUtils.inferSchema(sparkSession, 
options.asCaseSensitiveMap.asScala.toMap, files)

Review Comment:
   **9. [Nit] The same conversion is spelled out in eight places**
   
   `options.asCaseSensitiveMap.asScala.toMap` now appears in `FileTable` 
(`fileIndex` and `hasStrictFileReads`), `AvroTable`, `CSVTable`, `JsonTable`, 
`OrcTable`, this file and `TextBasedFileScan`. A new table that writes 
`options.asScala.toMap` out of habit would bring the bug back. Could 
`FileTable` define it once, for example as `protected lazy val 
caseSensitiveOptions`, for `fileIndex`, `hasStrictFileReads` and the 
`inferSchema` methods to share?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSourceUtils.scala:
##########
@@ -49,28 +49,28 @@ import org.apache.spark.util.Utils
 object DataSourceUtils extends PredicateHelper {
 
   /**
-   * Merges write options into a Hadoop configuration. Keys "path" and "paths" 
are excluded.
-   * This ensures per-write options are present in the conf even if they were 
added to the
-   * options map after the Hadoop conf was originally created.
+   * Merges data source options into a Hadoop configuration. Keys "path" and 
"paths" are excluded.
+   * Callers are expected to pass a map that preserves the original key 
casing; an unmodified
+   * [[CaseInsensitiveMap]] is also unwrapped to its `originalMap` as a 
safeguard.
    */
-  def mergeWriteOptionsIntoHadoopConf(
+  def mergeOptionsIntoHadoopConf(
       options: Map[String, String], conf: Configuration): Unit = {
-    // CaseInsensitiveMap.iterator yields lowercased keys, but Hadoop 
Configuration is
-    // case-sensitive. Use the original map to preserve the user's key casing.
+    // Hadoop Configuration is case-sensitive. Callers should pass a map with 
the original keys,
+    // and we also unwrap CaseInsensitiveMap here since its iterator yields 
lowercased keys.
     val rawOptions = options match {
       case ci: CaseInsensitiveMap[String @unchecked] => ci.originalMap

Review Comment:
   **4. [Low] DSv1 callers still depend on the `CaseInsensitiveMap` unwrap**
   
   Following up on item 5 of my previous review: the doc now says that callers 
are expected to pass a map with the original casing and that this unwrap is a 
safeguard. However, the DSv1 callers still pass a `CaseInsensitiveMap`. 
`DataSourceScanExec` passes `relation.options` 
([L797](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala#L797),
 
[L809](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala#L809)),
 `InsertIntoHadoopFsRelationCommand` passes its `options` 
([L93](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/InsertIntoHadoopFsRelationCommand.scala#L93)),
 and `CSVDataSource`, `JsonDataSource` and `XmlDataSource` pass the 
`parameters` of their parsed options ([CSV](https://g
 
ithub.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/CSVDataSource.scala#L247-L248),
 
[JSON](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JsonDataSource.scala#L148-L149),
 
[XML](https://github.com/apache/spark/blob/af2b45010b08a31498ca293fa7eea8a288b9d33d/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/xml/XmlDataSource.scala#L126-L127)).
 For them, this branch is the only thing that keeps the casing, and it only 
works for an unmodified instance: `filter`, `filterNot`, `map`, `transform` and 
`view.filterKeys(...).toMap` on a `CaseInsensitiveMap` all return a plain map 
with lowercased keys. `LibSVMFileFormat` hit the same problem with `++` before 
the `concat` override. Could those call sites pass `originalMap` explicitly? If 
not, the doc could say that the DSv1 paths rely on this
  branch.



##########
docs/sql-migration-guide.md:
##########
@@ -28,6 +28,7 @@ license: |
 
 ## Upgrading from Spark SQL 4.3 to 4.4
 
+- Since Spark 4.4, data source options merged into Hadoop `Configuration` via 
`SessionState.newHadoopConfWithOptions` and Data Source V2 file tables/scans 
preserve the original key casing instead of lowercasing keys when passed 
through `CaseInsensitiveMap` or `CaseInsensitiveStringMap` (SPARK-60887). 
Mixed-case Hadoop configuration keys (such as 
`fs.azure.skipUserGroupMetadataDuringInitialization`) and camelCase Spark SQL 
reader keys read from the Hadoop configuration on executors 
(`spark.sql.parquet.fieldId.read.enabled`, 
`spark.sql.parquet.fieldId.read.ignoreMissing`, and 
`spark.sql.parquet.ignoreVariantAnnotation`) now take effect on Data Source V1 
reads, while lowercase Hadoop configuration keys written with mixed casing 
(such as `Parquet.Enable.Dictionary` instead of `parquet.enable.dictionary`) no 
longer match.

Review Comment:
   **8. [Nit] The migration note names an internal API**
   
   `SessionState.newHadoopConfWithOptions` is `private[sql]`, so users cannot 
relate it to anything they do. Also, "now take effect on Data Source V1 reads" 
leaves out the DSv2 paths that this PR changes, such as schema inference. Could 
the note describe what users see instead, for example that Hadoop configuration 
keys given as data source options now keep their casing in DSv1 reads and in 
DSv2 schema inference?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/TextBasedFileScan.scala:
##########
@@ -31,8 +31,11 @@ import org.apache.spark.util.Utils
 abstract class TextBasedFileScan(
     sparkSession: SparkSession,
     options: CaseInsensitiveStringMap) extends FileScan {
-  @transient private lazy val codecFactory: CompressionCodecFactory = new 
CompressionCodecFactory(
-    sparkSession.sessionState.newHadoopConfWithOptions(options.asScala.toMap))
+  private def newHadoopConf(): Configuration =

Review Comment:
   **10. [Nit] `newHadoopConf()` shares its name with 
`SessionState.newHadoopConf()`**
   
   Thank you for the shared helper for item 7 of my previous review. 
`sessionState.newHadoopConf()` does not apply the options while this helper 
does, so the same name can mislead readers. How about a name like 
`newHadoopConfWithScanOptions()`?



-- 
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]

Reply via email to