n-young commented on code in PR #58867:
URL: https://github.com/apache/spark/pull/58867#discussion_r4525867298


##########
docs/sql-migration-guide.md:
##########
@@ -92,6 +92,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, `aes_encrypt` in CBC or GCM mode without a constant 
non-empty initialization vector (IV) is nondeterministic and is no longer 
constant-folded. Such calls are rejected in contexts that require deterministic 
expressions, including join conditions, column DEFAULT values and generated 
columns. `INSERT ... DEFAULT` also rejects an existing column default 
containing such a call. Calls with deterministic arguments and a constant 
non-empty IV, or a constant ECB mode, remain deterministic. Projections 
containing nondeterministic AES calls can also prevent filter and limit 
pushdown, as other nondeterministic projections do.

Review Comment:
   Updated the migration guide and PR description in 1bfe3d95c31e to cover 
every write filling an existing random-IV AES default, explicitly or 
implicitly, including omitted-column INSERTs and UPDATE/MERGE assignments of 
DEFAULT.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/PullOutNondeterministicSuite.scala:
##########
@@ -53,4 +105,187 @@ class PullOutNondeterministicSuite extends AnalysisTest {
       r.select(a, b, rnd).groupBy(rndref)(rndref.as("rnd"))
     )
   }
+
+  // Analysis must recognize fixed IVs before optimizer constant folding runs.
+  test("aes_encrypt with a foldable fixed IV is deterministic") {
+    val analyzed = analyze(
+      """SELECT aes_encrypt(
+        |  'Spark',
+        |  '0000111122223333',
+        |  'GCM',
+        |  'DEFAULT',
+        |  unhex('000000000000000000000000'))
+        |""".stripMargin)
+    val aesEncrypt = analyzed.expressions.flatMap(_.collect {
+      case aesEncrypt: AesEncrypt => aesEncrypt
+    }).head
+
+    assert(aesEncrypt.deterministic)
+    assert(aesEncrypt.replacement.deterministic)
+    assert(aesEncrypt.replacement.foldable)
+  }
+
+  // SQL wrappers must retain the determinism of their constant replacement 
values.
+  test("fixed AES arguments include runtime-replaceable expressions") {
+    for {
+      (mode, length) <- Seq("GCM" -> 12, "CBC" -> 16)
+      iv <- Seq(
+        s"to_binary('${"00" * length}', 'hex')",
+        s"encode('${"0" * length}', 'utf-8')")
+    } {
+      val expression = s"aes_encrypt('Spark', '0000111122223333', '$mode', 
'DEFAULT', $iv)"
+      val analyzed = analyze(s"SELECT $expression")
+      val aes = analyzed.expressions.flatMap(_.collect { case a: AesEncrypt => 
a }).head
+      assert(aes.deterministic)
+      val replacement = ReplaceExpressions.replace(aes)
+      assert(replacement.deterministic)
+      assert(replacement.foldable)
+      analyze(s"SELECT * FROM TaBlE t JOIN TaBlE2 s ON $expression = X'01'")
+    }
+
+    val analyzed = analyze("SELECT aes_encrypt('Spark', '0000111122223333', 
lower('ECB'))")
+    val aes = analyzed.expressions.flatMap(_.collect { case a: AesEncrypt => a 
}).head
+    assert(aes.deterministic)
+    assert(aes.replacement.foldable)
+  }
+
+  // Extract the guard together with AES so skipped branches remain 
unevaluated.
+  test("AES extraction retains conditional evaluation") {
+    Seq(
+      "CASE WHEN octet_length(k) = 16 THEN aes_encrypt(v, k) END",
+      "if(octet_length(k) = 16, aes_encrypt(v, k), NULL)",
+      "coalesce(if(octet_length(k) <> 16, X'01', NULL), aes_encrypt(v, k))"
+    ).foreach { expression =>
+      checkAesExtraction(expression, _.isInstanceOf[ConditionalExpression])
+    }
+    checkAesExtraction(
+      "octet_length(k) = 16 AND aes_encrypt(v, k) IS NOT NULL", 
_.isInstanceOf[And])
+    checkAesExtraction(
+      "octet_length(k) <> 16 OR aes_encrypt(v, k) IS NOT NULL", 
_.isInstanceOf[Or])
+  }
+
+  // Extracting the higher-order function keeps AES inputs bound to their 
lambda.
+  test("AES extraction retains lambda scope") {
+    checkAesExtraction(
+      "transform(array(v), x -> aes_encrypt(x, '0000111122223333'))",
+      _.isInstanceOf[ArrayTransform])
+    checkAesExtraction(
+      "size(transform(array(v), x -> aes_encrypt(x, '0000111122223333')))",
+      _.isInstanceOf[ArrayTransform])
+  }
+
+  // Predicate subqueries must reach placement validation in their original 
operator.
+  test("predicate subqueries are not nondeterministic evaluation units") {
+    Seq("GROUP BY", "ORDER BY", "DISTRIBUTE BY").foreach { clause =>
+      Seq(
+        "a IN (SELECT a FROM TaBlE WHERE rand(0) > 0.5)",
+        "EXISTS (SELECT a FROM TaBlE WHERE rand(0) > 0.5)"
+      ).foreach { expression =>
+        val select = if (clause == "GROUP BY") "count(*)" else "*"
+        val query = s"SELECT $select FROM TaBlE"
+        if (clause == "GROUP BY") {
+          val error = intercept[SparkException](analyzeClause(query, clause, 
expression))
+          assert(error.getCondition == "INTERNAL_ERROR")
+        } else {
+          val error = intercept[AnalysisException](analyzeClause(query, 
clause, expression))
+          assert(error.getCondition ==
+            
"UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY.UNSUPPORTED_IN_EXISTS_SUBQUERY")
+        }
+      }
+    }
+  }
+
+  // IN values can be extracted independently of the typed ListQuery child.
+  test("nondeterministic IN values are extracted without extracting the list 
query") {
+    val analyzed = analyze(
+      "SELECT count(*) FROM TaBlE GROUP BY rand(0) IN (SELECT a FROM TaBlE)")
+    val extracted = analyzed.collect {
+      case p: Project => p.projectList.flatMap(_.collect { case r: Rand => r })
+    }.flatten
+    assert(extracted.size == 1, analyzed.treeString)
+  }
+
+  // Scalar subqueries retain the existing single-evaluation extraction 
behavior.
+  test("scalar subqueries remain single nondeterministic evaluation units") {
+    for {
+      clause <- Seq("GROUP BY", "ORDER BY")
+      subquery <- Seq(
+        "SELECT rand(0)",
+        "SELECT rand(0) WHERE 1 IN (SELECT a FROM TaBlE)",
+        "SELECT rand(0) WHERE EXISTS (SELECT a FROM TaBlE)")
+    } {
+      val select = if (clause == "GROUP BY") "count(*)" else "*"
+      val analyzed = analyze(s"SELECT $select FROM TaBlE $clause ($subquery)")
+      val extracted = analyzed.collect {
+        case p: Project => p.projectList.flatMap(_.collect { case s: 
ScalarSubquery => s })
+      }.flatten
+      assert(extracted.size == 1, analyzed.treeString)
+    }
+  }
+
+  // Preserve the existing placement of rand when no new evaluation unit is 
present.
+  test("legacy nondeterministic leaves retain conditional extraction") {

Review Comment:
   Added in 1bfe3d95c31e: exact rand(10) RHS AND/OR plan checks, keeping rand 
extracted and the boolean wrapper in Sort; and GROUP BY/ORDER BY/DISTRIBUTE BY 
tests for lambda-bound shuffle(x) and rand(0), extracting the whole 
higher-order function with no missing inputs or nondeterministic operator 
expressions. PullOutNondeterministicSuite passes all 19 tests.



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