dongjoon-hyun opened a new pull request, #60637:
URL: https://github.com/apache/spark/pull/60637

   ### What changes were proposed in this pull request?
   
   This PR fixes a correctness issue: a write to a Data Source V2 table could 
store rows that violate an enforced CHECK constraint, because it read the 
stored SQL text of the condition under the session settings of the writer.
   
   A write checks a CHECK constraint through its stored `predicateSql` when the 
constraint has no predicate, or when the predicate cannot be converted back to 
a Catalyst expression. This happens for conditions using functions such as 
`upper`, `substring`, and `length`, array elements, `extract`, and, since 
SPARK-60032, conditions added by `ALTER TABLE` that read the current time and 
the like. `TableConstraintResolution` parsed that text and analyzed the result 
under the session settings of the writer.
   
   This PR makes the following changes.
   
   1. A write parses and analyzes the text under 
`StoredExpressionText.fixedConf`, the fixed settings that a write also uses for 
the stored text of a generation expression: ANSI mode on, and the default 
values of the SQL configs that change how a text reads. The session time zone, 
case sensitivity, `spark.sql.timestampType`, 
`spark.sql.decimalOperations.allowPrecisionLoss`, and the settings that views 
also take from the session that reads them stay with the writer. Only the 
condition is analyzed under these settings, as `Filter(invariant, 
LocalRelation(query.output))`. The query of the write is not analyzed again, 
and the resolved `CheckInvariant` goes to the `Filter` above the query as 
before. As in `StoredExpressionText.analyzeStrict`, the analyzed condition is 
checked under the settings of the session. Parsing alone is not enough, because 
implicit casts and functions such as `abs` and `element_at` take the ANSI value 
during analysis. Built-in function names are still bound to `sys
 tem.builtin`.
   2. `CheckAnalysis` fails `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE 
... ADD CONSTRAINT` with the new `SESSION_DEPENDENT_CHECK_CONSTRAINT` error 
when the condition means something else under the fixed settings. The check 
applies whether or not the condition has a predicate, because a connector may 
store only the text or validate the constraint with it. It compares two parses 
of the text by the session parser, so that a parser extension does not cause a 
false alarm, with the ANSI value of the session, so that it is about how the 
text reads. For `ALTER TABLE`, this replaces the fallback of SPARK-60032, which 
kept the predicate with the values at the time of the `ALTER TABLE` for such a 
condition.
   3. A condition that cannot be parsed or resolved on a write fails with the 
new `UNRESOLVABLE_CHECK_CONSTRAINT` error, which names the constraint and keeps 
the original error as its cause.
   4. The internal `spark.sql.legacy.useCurrentConfigsForCheckConstraint` 
config, `false` by default, restores the previous behavior of both the write 
and the DDL, including the fallback of SPARK-60032.
   
   `StoredExpressionText.readsAsInSession` takes the parser and the fixed 
settings to compare with, and the `Check.predicateSql` Javadoc and the 
migration guide describe the new behavior.
   
   ### Why are the changes needed?
   
   This is a correctness issue. A writer's session settings could store rows 
that violate an enforced constraint, without any error.
   
   ```sql
   ALTER TABLE t ADD CONSTRAINT c CHECK (CAST(upper(s) AS INT) > 0);
   INSERT INTO t SELECT 1, 'abc';  -- CAST_INVALID_INPUT
   SET spark.sql.ansi.enabled=false;
   -- Issue 1: It should fail with CAST_INVALID_INPUT, but stores the row.
   INSERT INTO t SELECT 2, 'abc';
   ```
   
   ```sql
   ALTER TABLE t ADD CONSTRAINT c CHECK (upper(s) <> 'A\\B');
   INSERT INTO t SELECT 1, concat('A', chr(92), 'B');  -- 
CHECK_CONSTRAINT_VIOLATION
   SET spark.sql.parser.escapedStringLiterals=true;
   -- Issue 2: It should fail with CHECK_CONSTRAINT_VIOLATION, but stores the 
row.
   INSERT INTO t SELECT 2, concat('A', chr(92), 'B');
   ```
   
   An implicit cast (`upper(s) > 1`) and an overflow (`length(s) + 2147483647 < 
0`) were also stored under `spark.sql.ansi.enabled=false`. Conditions that 
convert back from their predicate, such as `CAST(s AS INT) > 0` and `s <> 
'A\\B'`, were rejected regardless of the writer.
   
   Other writers failed instead. `spark.sql.ansi.enforceReservedKeywords=true` 
failed to parse `upper(order) <> 'X'`, and 
`spark.sql.ansi.doubleQuotedIdentifiers=true` read the string in `upper(s) <> 
"X"` as a column. In both cases the error did not name the constraint.
   
   A DDL in a session that reads the text differently cannot be stored safely 
either way. A write, or a connector, that reads the text reads another 
condition. For `ALTER TABLE`, a predicate with the values at the time of the 
`ALTER TABLE`, such as `ts <= <the time of the ALTER TABLE>` for `"ts" <= 
current_timestamp()`, rejects valid rows later.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes, compared to the released Spark versions.
   
   - A write that checks a constraint through its text no longer depends on the 
session settings of the writer, except for the settings listed above. A write 
with ANSI mode off now fails with an error such as `CAST_INVALID_INPUT` or 
`ARITHMETIC_OVERFLOW` on a row that the condition cannot evaluate under ANSI 
mode. Previously, such a row could be stored.
   - An existing constraint that was created under a non-default config, such 
as `spark.sql.ansi.doubleQuotedIdentifiers`, and that is checked through its 
text now reads with the default value of that config.
   - A DDL fails with `SESSION_DEPENDENT_CHECK_CONSTRAINT` on a condition that 
means something else under the fixed settings. Examples are a backslash in a 
string under `spark.sql.parser.escapedStringLiterals=true`, a double-quoted 
name under `spark.sql.ansi.doubleQuotedIdentifiers=true`, a function written 
without parentheses, such as `user`, under 
`spark.sql.ansi.enforceReservedKeywords=true`, and `${...}` under 
`spark.sql.variable.substitute=false`.
   - A condition that cannot be resolved on a write fails with 
`UNRESOLVABLE_CHECK_CONSTRAINT` instead of errors such as `UNRESOLVED_ROUTINE`, 
`UNRESOLVED_COLUMN`, or `PARSE_SYNTAX_ERROR`, which remain available as its 
cause.
   
   Set `spark.sql.legacy.useCurrentConfigsForCheckConstraint` to `true` to 
restore the previous behavior.
   
   ### How was this patch tested?
   
   Added six tests to `CheckConstraintSuite`.
   
   - A writer with ANSI mode off, for a cast that the parser builds and one 
that the analyzer builds, and a writer with 
`spark.sql.parser.escapedStringLiterals`.
   - DDL rejection through `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE`, 
including a condition that does not parse under the default configs.
   - DDL acceptance under ANSI mode off and for conditions with an alias or an 
`IDENTIFIER` clause.
   - The session time zone and case sensitivity of a writer, and the catalog 
configs of the session.
   - The constraint name in the errors of a write, for a parsing failure and an 
analysis failure.
   - The legacy config, for both the write and the DDL.
   
   Three of the six tests fail without the fix. The others cover behavior that 
the fix must keep. Turning off each changed branch one at a time makes at least 
one of the tests fail.
   
   The two SPARK-60032 tests of conditions that a session reads differently now 
run those DDLs with `spark.sql.legacy.useCurrentConfigsForCheckConstraint`, so 
they still cover the fallback of SPARK-60032.
   
   ```
   build/sbt 'sql/testOnly *command.v2.CheckConstraintSuite 
*GeneratedColumnWriteSuite *DeleteFromTableSuite *UpdateTableSuite 
*MergeIntoTableSuite *AnalysisConfOverrideSuite *DataSourceV2DataFrameSuite'
   build/sbt 'core/testOnly *SparkThrowableSuite'
   build/sbt 'catalyst/testOnly *ConstraintSuite *ConstraintExpressionSuite 
*connector.catalog.CatalogSuite *RetainedResolutionConfigsSuite 
*ConstraintParseSuite'
   build/sbt -Phive 'hive/testOnly *SparkConfigBindingPolicySuite'
   ```
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Opus 5.5
   


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