spark-test commented on code in PR #60101:
URL: https://github.com/apache/spark/pull/60101#discussion_r4543314566


##########
sql/core/src/main/scala/org/apache/spark/sql/internal/SessionState.scala:
##########
@@ -120,11 +120,10 @@ 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(

Review Comment:
   **Blocking (P1):** This line now lets a read option spelled 
`spark.sql.parquet.fieldId.read.enabled` reach the V1 Parquet reader's Hadoop 
conf, and `ParquetFileFormat.setupHadoopConf` does not reset it. The row-based 
reader then makes its two field-matching decisions from different sources: 
`ParquetReadSupport.getRequestedSchema` clips the requested schema with the 
option's value, while `ParquetRowConverter` matches fields by 
`SQLConf.get.parquetFieldIdReadEnabled`, which in a task is the session value.
   
   Reading the code, take files that hold `a INT` (field id 1) and `b INT` 
(field id 2), written before the table dropped `a` and renamed `b` to `a`, so 
the read schema is `a INT` with field id 2. With the session at the default 
`false` and `spark.sql.parquet.enableVectorizedReader=false`, 
`spark.read.schema(readSchema).option("spark.sql.parquet.fieldId.read.enabled", 
"true").parquet(dir)` clips to the Parquet column `b`, but the converter 
matches by name, finds no Catalyst field `b` and sends it to `NoopUpdater`, so 
`a` is null in every row and nothing fails. The opposite split (session `true`, 
option `false`) puts the file's `a` values into whichever read field carries id 
1. The vectorized reader takes both decisions from the conf, so it returns 
`b`'s values for the same read. On the base branch the key reached the conf 
lowercased, so both halves followed the session.
   
   V2 reads already had this split, because `ParquetScanBuilder` builds its 
conf from `asCaseSensitiveMap`; this change brings it to the default V1 path, 
including catalog tables whose `OPTIONS` carry the key.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60101#discussion_r4472819690).
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSourceUtils.scala:
##########
@@ -49,28 +49,40 @@ 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.
+   * Data Source V2 callers pass a map with original key casing 
(`asCaseSensitiveMap`), while
+   * Data Source V1 callers pass a [[CaseInsensitiveMap]] that is unwrapped to 
`originalMap` here
+   * unless `legacyLowercaseKeys` is enabled. When `originalMap` contains 
multiple spellings of
+   * the same key that differ only in case, only the entry matching the 
case-insensitive lookup is
+   * set so the Hadoop configuration agrees with `CaseInsensitiveMap.get`.
    */
-  def mergeWriteOptionsIntoHadoopConf(
-      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.
-    val rawOptions = options match {
-      case ci: CaseInsensitiveMap[String @unchecked] => ci.originalMap
+  def mergeOptionsIntoHadoopConf(
+      options: Map[String, String],
+      conf: Configuration,
+      legacyLowercaseKeys: Boolean = false): Unit = {
+    val rawOptions: Iterable[(String, String)] = options match {
+      case ci: CaseInsensitiveMap[String @unchecked] if !legacyLowercaseKeys =>

Review Comment:
   **Non-blocking (P2):** This unwrap is what keeps a V1 option's spelling, but 
Spark Connect batch reads arrive here already lowercased. 
`SparkConnectPlanner`'s DataSource read branch wraps the proto options in 
`CaseInsensitiveMap[String](...)` and replays them with `localMap.foreach { 
case (key, value) => reader.option(key, value) }`; iterating a 
`CaseInsensitiveMap` yields its lowercased keys, so the server-side reader, the 
`DataSource` and the `HadoopFsRelation` only ever see 
`fs.azure.skipusergroupmetadataduringinitialization`, even though the PySpark 
Connect reader sends the key as written. The Scala Connect client lowercases 
even earlier, because `DataFrameReader.load` and `DataFrameWriter` serialize 
`extraOptions` with `foreach`. So 
`spark.read.option("fs.azure.skipUserGroupMetadataDuringInitialization", 
"true").parquet(path)` now works in a classic session but is still ignored on 
Spark Connect. Connect streaming reads and the server's write handlers keep the 
casing they rece
 ive, so only these producers need to change.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60101#discussion_r4472819712), 
[2](https://github.com/apache/spark/pull/60101#discussion_r4500023917).
   
   **Recommended change:** Keep the user's option spellings on Spark Connect 
batch reads: in `SparkConnectPlanner`'s DataSource read branch, replay the 
options into `reader.option` from the original map (`localMap.originalMap` or 
the proto map) instead of iterating the `CaseInsensitiveMap`, keeping the 
current lowercased replay when 
`spark.sql.legacy.lowercaseDataSourceOptionsInHadoopConf` is on; in the Scala 
client's `DataFrameReader.load`, serialize `extraOptions.originalMap` instead 
of iterating `extraOptions`. Add a TODO at the Scala client's `DataFrameWriter` 
option serialization that names the write-side change it still needs. Mention 
Spark Connect reads in the flag's doc and in the migration note, and add Spark 
Connect read tests with a mixed-case option.
   
   **Why this works:** The proto options map already carries the spellings the 
client sent; replaying it unchanged gives the server-side `DataFrameReader` the 
keys a classic session gets, so `ResolveDataSource`, the `HadoopFsRelation` and 
the conf helper keep them. With the legacy flag on, the planner keeps 
lowercasing as it does today, so Connect reads get exactly the base-branch keys 
on every path, including file listing.
   
   **Scope:** Spark Connect batch reads keep the user's option spellings, with 
the base-branch lowercasing kept under the legacy flag.
   
   **Risks:** Mixed-case option keys from Connect clients now reach Hadoop 
confs as written on every batch read path, including file listing, the same 
behavior classic sessions get, and the legacy flag restores the base-branch 
lowercasing. Scala Connect users get the fix only with an updated client, 
because an older client still lowercases keys before sending them.
   
   **Constraints:** Server-side option lookups must keep returning the same 
values; this holds because the reader still stores options in a 
`CaseInsensitiveMap` and both clients send at most one spelling per key.
   
   **Exclusions:**
   - Writes built by the Scala Connect client still lowercase per-write options 
in `DataFrameWriter`; changing that would alter Connect writes in a way the 
legacy flag cannot roll back, so it needs its own change, which the TODO there 
names.
   - `transformParse`, which parses an in-memory dataset and builds no Hadoop 
conf from its options, keeps its current option handling.
   
   **Success:** A Spark Connect batch read with a mixed-case Hadoop option, 
from the PySpark or Scala client, sets that key as written in the conf of its 
read tasks and schema inference, as a classic session does. With the legacy 
flag on, a Spark Connect read gets the same lowercased keys as on the base 
branch. The flag's doc and the migration note mention Spark Connect reads.
   
   **Verification:**
   - **Regression:** A Spark Connect read whose target file system requires a 
mixed-case option at initialization succeeds from both the Python and Scala 
clients.
   - **Compatibility:** On Spark Connect, mixed-case spellings of reader 
options such as `header` or `mergeSchema` give the same result as before, and 
with the legacy flag on the read's conf carries only the lowercased key.



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/CaseInsensitiveMap.scala:
##########
@@ -43,10 +43,24 @@ 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:
   **Non-blocking (P2):** Through a `Map[String, String]` reference, `++` now 
dispatches here and keeps the operands' spellings, and one existing caller 
relied on the old lowercasing. The three-argument `JDBCOptions` constructor 
builds `CaseInsensitiveMap(parameters ++ Map(url, dbtable))`, and 
`DataFrameReader.jdbc(url, table, predicates, connectionProperties)` passes it 
`extraOptions ++ connectionProperties.asScala`. Since `asConnectionProperties` 
iterates `originalMap`, `spark.read.option("User", "scott").jdbc(url, "t", 
predicates, props)` used to give the driver `user` and now gives it `User`, and 
a `loginTimeout` property in `props` now arrives as `loginTimeout` instead of 
`logintimeout`. CamelCase driver properties now work here as they already did 
through `jdbc(url, table, properties)` and `format("jdbc")`, but 
`java.util.Properties` lookups are case-sensitive, so a driver that reads 
`user`, `password` or `ssl` stops seeing a mixed-case spelling it used to get. 
`spark.sql.legac
 y.lowercaseDataSourceOptionsInHadoopConf` does not reach this path, and 
neither the migration note nor the PR description mentions it. Which drivers 
match property names case-insensitively was not checked.
   
   **Recommended change:** Gate the new connection-property casing of the 
predicates `jdbc` reader behind a new internal `spark.sql.legacy.*` flag that 
defaults to false: when it is true, the three-argument `JDBCOptions` and 
`JdbcOptionsInWrite` constructors build their parameters from the map's 
lowercased view, as Scala's default concatenation did on the base branch. Add a 
migration-guide entry saying that the predicates reader now sends connection 
property names as written, with a mixed-case example such as `User`, and naming 
the flag; mention it among the PR description's user-facing changes. Add JDBC 
reader tests for both flag values.
   
   **Why this works:** The constructors are the only place where the 
concatenated options become the driver's properties on this path, so reading 
the flag there restores exactly the base-branch names, while the other `jdbc` 
entry points and the `CaseInsensitiveMap.++` change that the file-source paths 
rely on stay as they are.
   
   **Scope:** A rollback flag and a migration note for the connection-property 
names of the predicates `jdbc` reader.
   
   **Risks:** The flag adds one internal config entry; by default the 
predicates reader keeps the new behavior and sends names as written.
   
   **Constraints:** With the flag on or off, `jdbc(url, table, properties)`, 
`format("jdbc").load()` and the V2 JDBC catalog must send the same property 
names as they do now.
   
   **Exclusions:**
   - Code outside the JDBC option constructors that concatenates a 
`CaseInsensitiveMap` through a `Map` reference is not gated by this flag.
   
   **Success:** By default, a predicates `jdbc` read hands the driver 
connection property names as written. With the new flag set to true, the same 
read hands the driver the lowercased names the base branch sent. The migration 
guide describes the change and names the flag.
   
   **Verification:**
   - **Regression:** A predicates `jdbc` read whose reader options and 
connection properties include mixed-case names, such as `User` and 
`loginTimeout`, passes those names to the driver as written with the flag off 
and lowercased with the flag on.
   - **Compatibility:** `jdbc(url, table, properties)` and 
`format("jdbc").load()` pass the same connection property names to the driver 
with the flag on and off.
   - **Inspection:** The migration guide has an entry for the predicates `jdbc` 
reader's connection-property names that names the new flag.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/FileFormatWriter.scala:
##########
@@ -108,7 +108,7 @@ object FileFormatWriter extends Logging {
 
     // Merge write options into the job's configuration so that per-write 
options
     // take precedence over session-level defaults set later in prepareWrite.
-    DataSourceUtils.mergeWriteOptionsIntoHadoopConf(options, 
job.getConfiguration)
+    DataSourceUtils.mergeOptionsIntoHadoopConf(options, job.getConfiguration)

Review Comment:
   **Nit (P3):** This call does not pass 
`spark.sql.legacy.lowercaseDataSourceOptionsInHadoopConf`, so with the flag on 
the write merge still deduplicates case-colliding spellings and drops `path` 
and `paths` in any casing, where Spark 4.3's `mergeWriteOptionsIntoHadoopConf` 
set every spelling in `originalMap` and filtered only the exact `path` and 
`paths`. Reading the code, take a table created with `OPTIONS 
('parquet.enable.dictionary' 'false', 'PARQUET.ENABLE.DICTIONARY' 'true')` 
whose options iterate the lowercase spelling first: Spark 4.3's insert ended 
with `parquet.enable.dictionary=false`, because this merge also set the 
lowercase spelling, while with the flag on here the merge keeps only 
`PARQUET.ENABLE.DICTIONARY`, so the job conf ends with `true` and the files get 
dictionary encoding. The migration note says the flag restores the previous 
behavior, which does not hold for such writes.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60101#discussion_r4500023907).
   
   **Verification:**
   - **Regression:** With the legacy flag on, an insert into a data source 
table whose `OPTIONS` hold two case spellings of one Parquet key writes with 
the value Spark 4.3 applied, and an option keyed `Path` reaches the write's job 
conf.
   - **Behavior:** With the flag off, the same insert's job conf holds only the 
spelling that the case-insensitive option lookup returns.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8105,6 +8105,18 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val LEGACY_LOWERCASE_DATA_SOURCE_OPTIONS_IN_HADOOP_CONF =
+    buildConf("spark.sql.legacy.lowercaseDataSourceOptionsInHadoopConf")
+      .internal()
+      .doc("When true, data source options wrapped in a CaseInsensitiveMap or 
passed to " +
+        "Data Source V2 schema inference are merged into Hadoop Configuration 
with lowercased " +

Review Comment:
   **Nit (P3):** The doc lists options wrapped in a `CaseInsensitiveMap` and 
options passed to V2 schema inference, but the flag has two more readers: 
`FileTable.fileIndex` passes `schemaInferenceOptions` to `MetadataLogFileIndex` 
when a V2 table reads a streaming sink's output, and 
`TextBasedFileScan.codecFactory` reads the flag for the conf behind CSV, JSON 
and text split decisions. Neither is schema inference or a `CaseInsensitiveMap` 
input, so the doc tells a reader the flag does not affect them.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/FileTable.scala:
##########
@@ -58,25 +59,36 @@ abstract class FileTable(
 
   import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
 
+  protected lazy val caseSensitiveOptions: Map[String, String] =

Review Comment:
   **Non-blocking (P2):** The V2 tables now hand case-preserving options to 
inference and the file index, but one more producer still uses the lowercased 
copy: `FallBackFileSourceV2`, which rewrites an `INSERT INTO` a V2 `FileTable` 
as a V1 write, builds its `HadoopFsRelation` with `d.options.asScala.toMap`. 
`DataSourceStrategy` passes those options to 
`InsertIntoHadoopFsRelationCommand`, whose `newHadoopConfWithOptions` call and 
`FileFormatWriter` merge then get a plain map that is already lowercased. With 
`spark.sql.sources.useV1SourceList` set to an empty string, 
`spark.read.format("parquet").option("fs.azure.skipUserGroupMetadataDuringInitialization",
 "true").load(dir).createOrReplaceTempView("t")` followed by `INSERT INTO t 
SELECT ...` still writes with only the lowercased key, while reads of `t` honor 
the option.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60101#discussion_r4472819675), 
[2](https://github.com/apache/spark/pull/60101#discussion_r4472819712).
   
   **Verification:**
   - **Regression:** With V2 file sources enabled, an insert into a temporary 
view over a V2 file source read, whose file system requires a mixed-case option 
at initialization, succeeds, and its write conf carries the option as written.
   - **Compatibility:** With the legacy flag on, the same insert's write conf 
carries only the lowercased key.



##########
docs/sql-migration-guide.md:
##########
@@ -93,6 +93,7 @@ license: |
 - Since Spark 4.4, a write to a Data Source V2 table that parses the SQL text 
of a CHECK constraint binds an unqualified built-in function name to 
`system.builtin`, regardless of the SQL path and 
`spark.sql.functionResolution.sessionOrder` (SPARK-60777). Previously, an 
existing constraint could call another function with the same name.
 - Since Spark 4.4, `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE ... ADD 
CONSTRAINT` on a Data Source V2 table fail with `SUBQUERY_IN_CHECK_CONSTRAINT` 
when the condition of a CHECK constraint contains a subquery. `ALTER TABLE ... 
ADD CONSTRAINT` keeps failing with 
`UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY.HIGHER_ORDER_FUNCTION` on a subquery 
in a lambda function. Previously, most of these statements failed with 
`INTERNAL_ERROR`, but a subquery that needed no resolution, such as `id > 
(SELECT 0 AS a)`, was accepted and every write evaluated it again 
(SPARK-60781). Existing constraints that contain a subquery are not rejected.
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V2 implementation selected by 
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic` 
property do not control the V2 path. For scalar functions, determinism uses 
`BoundFunction.isDeterministic()` (default `true`) and the arguments' 
determinism. A call with constant arguments can therefore become eligible for 
constant folding during query planning instead of being evaluated per row.
+- Since Spark 4.4, Hadoop configuration keys passed as data source options 
keep their original casing in Data Source V1 reads, writes to catalog file 
source tables, and Data Source V1 and V2 schema inference instead of being 
lowercased (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 those paths, 
while lowercase Hadoop configuration keys written with mixed casing (such as 
`Parquet.Enable.Dictionary` instead of `parquet.enable.dictionary`) no longer 
match. To restore the previous behavior, set 
`spark.sql.legacy.lowercaseDataSourceOptionsInHadoopConf` to `true`.

Review Comment:
   **Nit (P3):** This list covers V1 reads, catalog file-source writes and V1 
and V2 schema inference, but two more V2 paths changed the same way and are 
switched back by the same flag: the options `FileTable.fileIndex` now passes to 
`MetadataLogFileIndex` when a V2 table reads a streaming sink's output, and the 
case-preserving conf `TextBasedFileScan.codecFactory` uses to decide whether 
CSV, JSON and text files can be split. A user who spells 
`io.compression.codecs` with other casing, or reads a sink's output with Hadoop 
options, cannot tell from this note that those reads changed.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60101#discussion_r4500023934).
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/FileTable.scala:
##########
@@ -58,25 +59,36 @@ abstract class FileTable(
 
   import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
 
+  protected lazy val caseSensitiveOptions: Map[String, String] =
+    options.asCaseSensitiveMap.asScala.toMap
+
+  protected def schemaInferenceOptions: Map[String, String] =
+    if (sparkSession.sessionState.conf.getConf(
+        SQLConf.LEGACY_LOWERCASE_DATA_SOURCE_OPTIONS_IN_HADOOP_CONF)) {
+      options.asScala.toMap

Review Comment:
   **Nit (P3):** This branch, and the flag read in 
`TextBasedFileScan.codecFactory`, are the only things that lowercase V2 options 
under the flag: V2 inference hands `newHadoopConfWithOptions` a plain map, 
which its legacy branch leaves as is. No test sets the flag on a V2 read; the 
SPARK-60887 case in `DataSourceSuite` calls the helper directly. Changing this 
to always return `caseSensitiveOptions`, or dropping the flag read from 
`codecFactory`, keeps every test green. `codecFactory` is not covered in either 
mode, since `CompressionCodecFactory` opens no file system for 
`FakeFileSystemRequiringDSOption` to reject.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60101#discussion_r4472819739).
   
   **Verification:**
   - **Regression:** With the legacy flag on and V2 file sources enabled, 
Parquet, ORC, Avro, JSON and CSV schema inference and a read of a streaming 
sink's output build their conf from lowercased option keys, and a check that 
requires the lowercased spelling fails if they do not.
   - **Regression:** A V2 CSV, JSON or text scan builds its codec-factory conf 
from lowercased option keys with the flag on and from the keys as written with 
it off.



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