← Back to Pull requests

feat: native AssertNotNull #7837

Open
parthchandra opened this pull request with 1354 lines diff across 20 files
View on GitHub
parthchandra parthchandra commented on Dec 03, 2026 02:24 UTC
Author

Which issue does this PR close?

Closes #7049.

Rationale for this change

When a nullable value is written into a NOT NULL column or struct field of a DataSource V2 table, Spark wraps it in AssertNotNull. That includes INSERT, DataFrameWriterV2.append, and copy-on-write UPDATE and MERGE assignments. Comet had no native AssertNotNull, so the projection holding it fell back to Spark. With no exchange in front of the writer, that also pushed the whole native Iceberg write back to iceberg-java. With an exchange, it forced the JVM columnar shuffle in place of native shuffle.

Spark checks one row at a time, and only the rows an operator above actually reads. Comet checks a whole batch at a time. So a native check must not see rows Spark never evaluates. Spark's optimizer puts the write's check in three places where that matters:

  • directly under a LIMIT (PushProjectionThroughLimit). #7195 already caps a projection's input under a limit, so a native check reads only the rows the limit reads;

  • inside a final aggregate for GROUP BY/DISTINCT (CollapseProject);

  • on Spark 4.1+, under an OFFSET, where Spark's generated code skips the offset rows that the #7195 cap still includes.
  • This PR handles the last two, so Comet does not raise an error that Spark would not.

    What changes are included in this PR?

    Native expression

  • AssertNotNull in native/spark-expr (predicate_funcs/assert_not_null.rs). It returns the child's array unchanged (no copy) and fails if any row is NULL. It uses logical_null_count, so NullArray, dictionary and run-end arrays are covered. Only the top-level value is checked, as in Spark. On an empty batch it returns an empty array, so IN does not mistake it for a constant.

  • New proto message AssertNotNull (field 79) and a planner arm. A wrong child count returns an error instead of panicking.

  • Serde CometAssertNotNull. It sends walkedTypePath.mkString("\n", "\n", "\n"), the exact string Spark puts in its message.
  • Errors

  • The existing, unused SparkError::NotNullAssertViolation now carries walked_type_path. It previously mapped to the wrong JVM error (_LEGACY_ERROR_TEMP_2148).

  • The Spark 4.x shim raises QueryExecutionErrors.notNullAssertViolation (NOT_NULL_ASSERT_VIOLATION). The Spark 3.5 shim raises the plain NullPointerException with Spark 3.5's message.
  • Rows Spark never evaluates

  • An aggregate whose result expressions hold AssertNotNull stays in Spark (buildAggOp, and the matching preflight in CometExecRule.checkAggregateConversion). This covers GROUP BY/DISTINCT writes. It applies with or without a LIMIT, which matches the last release for that shape.

  • A projection holding AssertNotNull directly under a GlobalLimitExec with an offset, or under the LocalLimitExec right below it, stays in Spark (CometExecRule.tagOffsetSkippedChecks). With no shuffle in between, Spark computes it only for the rows the OFFSET keeps.

  • CometAssertNotNull reports Unsupported when spark.comet.exec.localLimit.enabled=false, since the projection input cap from #7195 needs Comet local limits.

  • Comet's CASE/IF, AND/OR and native MergeRows already evaluate a fallible expression only on the rows that reach it. AssertNotNull is not on the "cannot fail" lists, so those stay lazy. Tests pin this.
  • Docs

  • user-guide/latest/expressions.md: a "Not-null checks" entry.

  • user-guide/latest/compatibility/index.md: a new "Errors from AssertNotNull" section.
  • Config and public surface

  • New key, generated from the class name: spark.comet.expression.AssertNotNull.enabled (default true).

  • spark.comet.exec.localLimit.enabled now also gates AssertNotNull.

  • SparkError::NotNullAssertViolation: the field and JSON parameter changed from fieldName to walkedTypePath. It had no producer before this change.
  • How are these changes tested?

    AssertNotNull is a NonSQLExpression, so Spark SQL can't call it, and V1 file tables never have NOT NULL columns. The expression tests therefore build it through the DataFrame API, and the write tests use Iceberg. Every error test compares the exception class and message against Spark, and checks that Comet ran the check natively.

  • Rust (assert_not_null.rs, 12 tests): pass-through without a copy, NULLs in sliced, dictionary, run-end (including a slice inside the NULL run) and NullArray inputs, top-level-only checking, a NULL constant on empty and non-empty batches, the evaluation selection, a NULL computed by the child, field metadata, and the wrong-child-count error.

  • CometAssertNotNullSuite (new, 13 tests):

  • - every type, including decimal(38,18) bounds, NaN and -0.0, dates 0001-01-01 and 9999-12-31, timestamp and timestamp_ntz, non-ASCII strings, and nested structs, arrays and maps;
    - Spark's error at batch boundaries, with non-ASCII and emoji paths;
    - IF, CASE, AND and OR that skip the NULL row, in one batch;
    - native shuffle and aggregation, and a NULL computed by the child;
    - a NULL literal of INT and of NullType, and a low-cardinality string column;
    - a lambda, which runs through the codegen dispatcher;
    - LIMIT with AQE on and off;
    - a sort with LIMIT and OFFSET, with NULLs past the cut and in the skipped rows;
    - the aggregate and OFFSET fallbacks;
    - the disabled-expression and disabled-local-limit fallbacks.
  • CometIcebergWriteActionSuite (7 new tests): writes into NOT NULL columns, struct fields (including a struct that is itself NOT NULL), array elements and map values, through SQL INSERT and writeTo().append(), including a bucketed table with write.distribution-mode=none. Also:

  • - a NULL in each kind of column, with one row per batch, checking that no data files are left behind;
    - INSERT ... LIMIT with AQE on and off;
    - INSERT ... OFFSET, and LIMIT ... OFFSET, over a single partition;
    - a NULL struct written into a struct with a NOT NULL field;
    - copy-on-write UPDATE and MERGE, including rows that the assignment must not check.
  • SparkErrorConverterSuite: the converted error matches a real AssertNotNull.eval() for empty, simple, deep and non-ASCII paths.
  • Run locally on Spark 3.5, 4.0 and 4.1, on current main:

  • CometAssertNotNullSuite, SparkErrorConverterSuite, SerdeRegistrationSuite, the new Iceberg tests (the full CometIcebergWriteActionSuite on 4.1), CometExecRuleSuite, CometAggregateSuite, CometNativeCastSuite, and the expressions/cast/limit_projection*.sql fixtures from #7195;

  • CometExecSuite, CometExpressionSuite and both TPC-DS plan-stability suites on 4.1 and 4.0, and CometJoinSuite and GenerateDocsSuite on 4.1;

  • before rebasing, also Spark 4.2 for CometAssertNotNullSuite and SparkErrorConverterSuite;

  • cargo test for datafusion-comet-spark-expr, -common, -proto and datafusion-comet.
  • The new suite is registered in pr_build_linux.yml and pr_build_macos.yml.

    Not run locally: Spark's own SQL suites with Comet enabled, and the Iceberg Spark tests. These matter here: Spark's RuntimeNullChecksV2Writes, DataSourceV2SQLSuite, UpdateTableSuiteBase and MergeIntoTableSuiteBase, and Iceberg's TestUpdate and TestMerge (which check the error message on Spark 3.5), all exercise this path. Please apply run-all-spark-profiles, run-spark-3.5-tests and run-iceberg-tests.

    Known differences, documented in the compatibility guide

  • Comet checks a whole batch at a time. When a batch holds more than one bad value, the error can name a different column than Spark's, or be another kind of error, such as a cast overflow from another row. Both engines still fail, and nothing is written.

  • An AssertNotNull built by hand through the DataFrame API can fail on a row Spark never evaluates: as an operand of a null-intolerant operator, in an IN list, as the argument of an aggregate with a FILTER, or under a LIMIT that does not directly consume its projection (#7147). Spark's own write plans do not put the check in these places.

  • With native local limits off, checks on array elements and map values still run through the codegen dispatcher.
  • Performance
    There is no microbenchmark. The kernel is a constant-time null count for plain arrays and returns the child's array without copying it. The gain is that writes into NOT NULL columns now stay in the Comet pipeline, including native shuffle and the native Iceberg writer, instead of falling back.

    Diff: 1354 lines (+1338 / -16) across 20 files Reviewer: comphead Review duration: 1500m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.72) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 1354 lines diff across 20 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    8 items
    comphead comphead commented on code on Dec 03, 2026 17:30 UTC
    Code Review
    spark/src/main/scala/org/apache/spark/sql/comet/operators.scala:1
    @@ -2466,6 +2473,12 @@ trait CometBaseAggregate[T <: BaseAggregateExec] extends CometOperatorSerde[T] {
         if (resultExpressions.map(_.toAttribute) == naturalOutput) {
           return Some(builder.setHashAgg(hashAggBuilder).build())
         }
    +    // Spark folds a write's NOT NULL checks into the aggregate below a LIMIT, and evaluates them
    +    // only for the groups the limit reads. The native projection would check every group.
    +    if (resultExpressions.exists(_.exists(_.isInstanceOf[AssertNotNull]))) {

    CollapseProject folds the write's Project into the Aggregate whether or not a LIMIT sits above it (the case p @ Project(_, agg: Aggregate) arm in Spark 4.1.1's Optimizer.scala). So this gate keeps the final aggregate in Spark for every INSERT ... SELECT ... GROUP BY into a NOT NULL column, even though Spark evaluates every group there too. The comment says "below a LIMIT", but the check does not look for one. Could this tag only aggregates whose output a limit in the same stage consumes, the way tagOffsetSkippedChecks does for projections? Then the common no-limit GROUP BY write would run natively. If you keep it unconditional for now, the comment should say so and point to a follow-up issue.

    comphead comphead commented on code on Dec 03, 2026 17:30 UTC
    Code Review
    spark/src/test/scala/org/apache/comet/CometAssertNotNullSuite.scala:1
    @@ -0,0 +1,367 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *   http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +package org.apache.comet
    +
    +import org.apache.spark.sql.{Column, CometTestBase, DataFrame}
    +import org.apache.spark.sql.catalyst.expressions.{And, CaseWhen, Cast, CreateNamedStruct, Divide, GetStructField, GreaterThan, If, IsNotNull, IsNull, Literal, Or}
    +import org.apache.spark.sql.catalyst.expressions.objects.AssertNotNull
    +import org.apache.spark.sql.comet.CometBaseAggregate
    +import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
    +import org.apache.spark.sql.execution.SparkPlan
    +import org.apache.spark.sql.functions.{col, sum, transform}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.types.{DoubleType, IntegerType, NullType}
    +
    +import org.apache.comet.rules.CometExecRule
    +
    +/**
    + * `AssertNotNull` is a `NonSQLExpression`, so SQL file tests cannot call it. These tests build it
    + * through the DataFrame API, as Spark's encoders and V2 table writes do.
    + */
    +class CometAssertNotNullSuite extends CometTestBase {
    +  import testImplicits._
    +
    +  private val allTypes = """SELECT * FROM VALUES
    +    (true, cast(-128 AS TINYINT), 2147483647, cast(-9223372036854775808 AS BIGINT),
    +      cast('NaN' AS FLOAT), cast('-Infinity' AS DOUBLE),
    +      cast('99999999999999999999.999999999999999999' AS DECIMAL(38, 18)),
    +      cast(-0.01 AS DECIMAL(10, 2)), '你好, 世界', cast('こんにちは' AS BINARY),
    +      DATE '0001-01-01', TIMESTAMP '1900-01-01 00:00:00 UTC',
    +      TIMESTAMP_NTZ '9999-12-31 23:59:59.999999',
    +      array(1, NULL), array(named_struct('x', cast(NULL AS INT), 'm', map('k', 1))),
    +      map('ключ', array(1, NULL)),
    +      named_struct('a', NULL, 'b', array(named_struct('c', 'é')),
    +        'm', map('k', cast(NULL AS INT)))),
    +    (false, cast(127 AS TINYINT), -2147483648, cast(9223372036854775807 AS BIGINT),
    +      cast(-0.0 AS FLOAT), cast(1e308 AS DOUBLE),
    +      cast('-99999999999999999999.999999999999999999' AS DECIMAL(38, 18)),
    +      cast(99999999.99 AS DECIMAL(10, 2)), '', cast('' AS BINARY),
    +      DATE '9999-12-31', TIMESTAMP '2262-04-11 23:47:16.854775 UTC',
    +      TIMESTAMP_NTZ '0001-01-01 00:00:00',
    +      array(), array(), map(), named_struct('a', 1, 'b', array(), 'm', map()))
    +    AS t(b, i8, i32, i64, f, d, dec38, dec10, s, bin, dt, ts, ntz, arr, arr_st, m, st)"""
    +
    +  private def assertNotNull(df: DataFrame, column: String, path: Seq[String]): Column =
    +    getColumnFromExpression(AssertNotNull(df.col(column).expr, path))
    +
    +  private def checkNative(df: => DataFrame): (SparkPlan, SparkPlan) =
    +    checkSparkAnswerAndImpl(df, native = Seq("assertnotnull"))
    +
    +  /** Both engines fail with the same exception class and message, and Comet fails natively. */
    +  private def assertSameNotNullError(query: => DataFrame, checkNative: Boolean = true): Unit = {
    +    val df = query
    +    if (checkNative) {
    +      val plan = stripAQEPlan(df.queryExecution.executedPlan)
    +      checkCometOperators(plan)
    +      assertExpressionImpl(plan, native = Seq("assertnotnull"), dispatched = Nil)
    +    }
    +    checkSparkAnswerMaybeThrows(df) match {
    +      case (Some(sparkError), Some(cometError)) =>
    +        assertSameNotNullViolation(sparkError, cometError)
    +      case result => fail(s"Expected both Spark and Comet to fail, got $result")
    +    }
    +  }
    +
    +  /** `query(passing)` matches Spark natively, and `query("true")` fails as Spark does. */
    +  private def checkPassesAndFails(passing: String)(query: String => DataFrame): Unit = {
    +    checkNative(query(passing))
    +    assertSameNotNullError(query("true"))
    +  }
    +
    +  test("AssertNotNull returns non-null values of every type natively") {
    +    withTempPath { dir =>
    +      // Spark 3.5 refuses to write dates before 1582 unless told not to rebase them.
    +      withSQLConf(
    +        SQLConf.PARQUET_REBASE_MODE_IN_WRITE.key -> "CORRECTED",
    +        SQLConf.PARQUET_INT96_REBASE_MODE_IN_WRITE.key -> "CORRECTED") {
    +        sql(allTypes).write.parquet(dir.getCanonicalPath)
    +      }
    +      withParquetTable(dir.getCanonicalPath, "tbl") {
    +        val df = spark.table("tbl")
    +        checkNative(df.select(df.columns.toSeq.map(c => assertNotNull(df, c, Seq(c)).as(c)): _*))
    +      }
    +    }
    +  }
    +
    +  test("AssertNotNull fails with Spark's error on a NULL") {
    +    val input = sql("""SELECT * FROM VALUES
    +      (1, 'a', named_struct('x', 1), array(1), map('k', 1)),
    +      (2, 'b', named_struct('x', 2), array(CAST(NULL AS INT)), map('k', CAST(NULL AS INT))),
    +      (3, NULL, named_struct('x', NULL), array(3), map('k', 3)),
    +      (NULL, 'd', NULL, NULL, NULL),
    +      (5, 'e', named_struct('x', 5), array(5), map('k', 5)) AS t(i, s, st, arr, m)""")
    +    withTempPath { dir =>
    +      input.repartition(1).write.parquet(dir.getCanonicalPath)
    +      withParquetTable(dir.getCanonicalPath, "tbl") {
    +        // A batch size of 2 puts each NULL in a later batch than the first.
    +        withSQLConf(CometConf.COMET_BATCH_SIZE.key -> "2") {
    +          for ((column, path) <- Seq(
    +              "i" -> Seq("i"),
    +              "s" -> Seq("top level Product or row object"),
    +              "st" -> Seq("s", "a"),
    +              "arr" -> Seq("arr"),
    +              "m" -> Seq("m"),
    +              "i" -> Seq("列_1", "😀 field"))) {
    +            assertSameNotNullError {
    +              val df = spark.table("tbl")
    +              df.select(assertNotNull(df, column, path))
    +            }
    +          }
    +          // NULLs inside a non-null struct, array or map pass; only the value itself is checked.
    +          val df = spark.table("tbl").where("i IS NOT NULL")
    +          checkNative(df.select(Seq("st", "arr", "m").map(c => assertNotNull(df, c, Seq(c))): _*))
    +        }
    +      }
    +    }
    +  }
    +
    +  test("AssertNotNull in a branch Spark does not take is not evaluated") {
    +    val input = sql("""SELECT * FROM VALUES
    +      (1, named_struct('a', 1, 'b', 'x')),
    +      (-1, NULL),
    +      (2, named_struct('a', 2, 'b', NULL)) AS t(i, st)""")
    +    withTempPath { dir =>
    +      // One file, so the skipped NULL row shares a batch with rows the check does run on.
    +      input.repartition(1).write.parquet(dir.getCanonicalPath)
    +      withParquetTable(dir.getCanonicalPath, "tbl") {
    +        val df = spark.table("tbl")
    +        val st = df.col("st").expr
    +        val checkedA = AssertNotNull(GetStructField(st, 0, Some("a")), Seq("st", "a"))
    +        // How Spark writes a nullable struct into a struct column with a NOT NULL field. Its NULL
    +        // branch has the target type, where field `a` is not nullable.
    +        val struct =
    +          CreateNamedStruct(
    +            Seq(Literal("a"), checkedA, Literal("b"), GetStructField(st, 1, Some("b"))))
    +        val rebuilt = If(IsNull(st), Literal(null, struct.dataType), struct)
    +        checkNative(df.select(getColumnFromExpression(rebuilt)))
    +
    +        val caseWhen =
    +          CaseWhen(Seq(GreaterThan(df.col("i").expr, Literal(0)) -> checkedA), Some(Literal(0)))
    +        checkNative(df.select(getColumnFromExpression(caseWhen)))
    +
    +        // AND and OR evaluate their right side only for rows the left side has not decided.
    +        val positive = GreaterThan(checkedA, Literal(0))
    +        checkNative(df.select(getColumnFromExpression(And(IsNotNull(st), positive))))
    +        checkNative(df.select(getColumnFromExpression(Or(IsNull(st), positive))))
    +      }
    +    }
    +  }
    +
    +  // Spark's write plans put the check right before the shuffle that feeds the writer.
    +  test("AssertNotNull feeds native shuffle and aggregation") {
    +    withParquetTable((0 until 100).map(i => (i, s"k${i % 7}")), "tbl") {
    +      val df = spark.table("tbl")
    +      val checked =
    +        df.select(
    +          assertNotNull(df, "_1", Seq("_1")).as("v"),
    +          assertNotNull(df, "_2", Seq("_2")).as("k"))
    +      val (_, cometPlan) = checkNative(checked.repartition(4, col("k")))
    +      assert(
    +        collect(cometPlan) { case s: CometShuffleExchangeExec => s }.nonEmpty,
    +        s"expected native shuffle in:\n$cometPlan")
    +      checkNative(checked.groupBy("k").agg(sum("v")))
    +    }
    +    // A NULL reaching the check fails the native shuffle write with Spark's error.
    +    withParquetTable((0 until 100).map(i => (i, if (i == 57) null else s"k${i % 7}")), "nulls") {
    +      assertSameNotNullError {
    +        val df = spark.table("nulls")
    +        df.select(
    +          assertNotNull(df, "_1", Seq("_1")).as("v"),
    +          assertNotNull(df, "_2", Seq("_2")).as("k"))
    +          .repartition(4, col("k"))
    +      }
    +    }
    +  }
    +
    +  test("AssertNotNull checks the value its child computes") {
    +    withParquetTable(Seq((1, 1), (2, 0), (3, 3)), "tbl") {
    +      withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
    +        // 2.0 / 0.0 is NULL without ANSI, from inputs that are not NULL.
    +        checkPassesAndFails("_2 != 0") { predicate =>
    +          val df = spark.table("tbl").where(predicate)
    +          val ratio =
    +            Divide(Cast(df.col("_1").expr, DoubleType), Cast(df.col("_2").expr, DoubleType))
    +          df.select(getColumnFromExpression(AssertNotNull(ratio, Seq("ratio"))))
    +        }
    +      }
    +    }
    +  }
    +
    +  test("AssertNotNull on an empty input and on a NULL literal") {
    +    withParquetTable(Seq((1, "a"), (2, "b"), (3, null)), "tbl") {
    +      // With no row there is nothing to check. The filter may leave no batch at all, so the
    +      // Rust tests cover a NULL constant over an empty batch.
    +      for (dataType <- Seq(IntegerType, NullType)) {
    +        checkPassesAndFails("_1 > 10") { predicate =>
    +          spark
    +            .table("tbl")
    +            .where(predicate)
    +            .select(getColumnFromExpression(AssertNotNull(Literal(null, dataType), Seq("c"))))
    +        }
    +      }
    +      // A filter that removes the NULLs first leaves nothing to fail on.
    +      val df = spark.table("tbl").where("_2 IS NOT NULL")
    +      checkNative(df.select(assertNotNull(df, "_2", Seq("_2"))))
    +    }
    +  }
    +
    +  test("AssertNotNull on a low-cardinality string column") {
    +    withTempPath { dir =>
    +      // Few distinct values, so Parquet writes the column with a dictionary. The scan may decode
    +      // it; the Rust tests cover a dictionary array that reaches the check.
    +      spark
    +        .range(1000)
    +        .selectExpr(
    +          "id",
    +          "CASE WHEN id = 999 THEN NULL WHEN id % 2 = 0 THEN 'ä' ELSE '日本' END AS s")
    +        .repartition(1)
    +        .write
    +        .parquet(dir.getCanonicalPath)
    +      withParquetTable(dir.getCanonicalPath, "tbl") {
    +        checkPassesAndFails("id < 999") { predicate =>
    +          val df = spark.table("tbl").where(predicate)
    +          df.select(assertNotNull(df, "s", Seq("s")))
    +        }
    +      }
    +    }
    +  }
    +
    +  test("AssertNotNull inside a lambda matches Spark") {
    +    // How Spark writes array<int> into a column of array<int NOT NULL>.
    +    withParquetTable(Seq((1, Seq(Option(1), Option(2))), (2, Seq(Option(3), None))), "tbl") {
    +      def checked(predicate: String): DataFrame =
    +        spark
    +          .table("tbl")
    +          .where(predicate)
    +          .select(
    +            transform(
    +              col("_2"),
    +              x => getColumnFromExpression(AssertNotNull(x.expr, Seq("_2", "element")))))
    +      // The lambda runs in Comet through the JVM codegen dispatcher, not as a native expression.
    +      checkSparkAnswerAndImpl(checked("_1 = 1"), dispatched = Seq("transform"))
    +      val failing = stripAQEPlan(checked("true").queryExecution.executedPlan)
    +      checkCometOperators(failing)
    +      assertExpressionImpl(failing, native = Nil, dispatched = Seq("transform"))
    +      assertSameNotNullError(checked("true"), checkNative = false)
    +    }
    +  }
    +
    +  test("AssertNotNull under a LIMIT checks only the rows the limit reads") {
    +    withTempPath { dir =>
    +      // One file in id order, so the limit reads rows in order and stops well before the NULL in
    +      // row 57.
    +      spark
    +        .range(100)
    +        .selectExpr("CAST(IF(id = 57, NULL, id) AS INT) AS v")
    +        .coalesce(1)
    +        .write
    +        .parquet(dir.getCanonicalPath)
    +      withParquetTable(dir.getCanonicalPath, "tbl") {
    +        for (aqe <- Seq(true, false)) {
    +          withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString) {
    +            val df = spark.table("tbl")
    +            val checked = df.select(assertNotNull(df, "v", Seq("v")).as("v")).limit(5)
    +            // A collect limit, and a local limit, which Spark puts under a global limit.
    +            checkNative(checked)
    +            checkNative(checked.agg(sum("v")))
    +          }
    +        }
    +      }
    +    }
    +  }
    +
    +  test("AssertNotNull after a sort with a LIMIT checks only the top rows") {
    +    // Several files, so the top rows come from more than one partition. The NULL sorts last.
    +    withParquetTable((0 until 100).map(i => Tuple1(if (i == 42) None else Some(i))), "tbl") {
    +      val df = spark.table("tbl")
    +      val sorted = df.orderBy(col("_1").asc_nulls_last)
    +      val checked = sorted.select(assertNotNull(sorted, "_1", Seq("_1")).as("v"))
    +      checkNative(checked.limit(5))
    +      checkNative(checked.limit(5).offset(2))
    +      // The NULL sorts first, into the OFFSET rows, which Spark skips before projecting.
    +      val nullsFirst = df.orderBy(col("_1").asc_nulls_first)
    +      checkNative(
    +        nullsFirst.select(assertNotNull(nullsFirst, "_1", Seq("_1")).as("v")).limit(5).offset(1))
    +    }
    +    // Spark projects only the global top rows. With the five-way local parallelism, row 20 leads a
    +    // partition, so it is in that top 5 but not the global top 5. Row 1 is one of the OFFSET rows.
    +    withParquetTable(
    +      (0 until 100).map(i => (i, if (i == 1 || i == 20) None else Some(i))),
    +      "t2") {
    +      val sorted = spark.table("t2").orderBy("_1")
    +      val checked = sorted.select(assertNotNull(sorted, "_2", Seq("_2")).as("v"))
    +      checkNative(checked.limit(5).offset(2))
    +    }
    +  }
    +
    +  test("AssertNotNull planned below an OFFSET stays in Spark") {
    +    withTempPath { dir =>
    +      // One file in id order, with the NULL in the first row, which the OFFSET skips.
    +      spark
    +        .range(10)
    +        .selectExpr("CAST(IF(id = 0, NULL, id) AS INT) AS v")
    +        .coalesce(1)
    +        .write
    +        .parquet(dir.getCanonicalPath)
    +      withParquetTable(dir.getCanonicalPath, "tbl") {
    +        // coalesce(1) leaves nothing to shuffle before the OFFSET, so Spark projects only the
    +        // rows the OFFSET keeps. The aggregate keeps the OFFSET off the root, where a collect
    +        // would read every row.
    +        val df = spark.table("tbl").coalesce(1)
    +        val checked = df.select(assertNotNull(df, "v", Seq("v")).as("v"))
    +        for (limited <- Seq(checked.offset(1), checked.limit(3).offset(1))) {
    +          checkSparkAnswerAndFallbackReason(
    +            limited.agg(sum("v")),
    +            CometExecRule.OffsetSkippedCheckReason)
    +        }
    +      }
    +    }
    +  }
    +
    +  test("AssertNotNull folded into an aggregate keeps the aggregate in Spark") {
    +    withParquetTable((0 until 20).map(i => (i % 5, i)), "tbl") {
    +      // Spark merges the check into the aggregate's result expressions, as it does for a write
    +      // of GROUP BY ... LIMIT, and evaluates them only for the groups a limit reads.
    +      val grouped = spark.table("tbl").groupBy("_1").agg(sum("_2").as("s"))
    +      val checked =
    +        grouped.select(assertNotNull(grouped, "_1", Seq("k")).as("k"), col("s"))
    +      checkSparkAnswerAndFallbackReason(checked, CometBaseAggregate.AssertNotNullInResult)
    +    }

    This test pins the fallback reason but has no LIMIT and no NULL, so it does not show the result the gate protects. Nothing tests the case the gate exists for: a NULL group past a LIMIT, where Spark succeeds and a native result projection would fail. A case like groupBy(...).agg(...), with the check on a column that is NULL only for a group the LIMIT does not read, compared against Spark, would pin it. The same shape through INSERT ... SELECT ... GROUP BY ... LIMIT in CometIcebergWriteActionSuite would cover the real write plan.

    comphead comphead commented on code on Dec 03, 2026 17:30 UTC
    Code Review
    spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala:1
    @@ -2167,6 +2203,11 @@ case class CometExecRule(session: SparkSession, queryStagePrep: Boolean = false)
         val aggregateExpressions = agg.aggregateExpressions
         val groupingExpressions = agg.groupingExpressions
     
    +    // The aggregate serde leaves these to Spark; see CometBaseAggregate.AssertNotNullInResult.
    +    if (agg.resultExpressions.exists(_.exists(_.isInstanceOf[AssertNotNull]))) {
    +      return false
    +    }

    The same exists(_.exists(_.isInstanceOf[AssertNotNull])) predicate is written three times: here, in tagOffsetSkippedChecks (line 1550) and in CometBaseAggregate (operators.scala line 2478). A single helper next to the serde, for example CometAssertNotNull.containsCheck(exprs: Seq[Expression]), would keep the three call sites in sync and give the cross-reference comment here one place to point to.

    comphead comphead commented on code on Dec 03, 2026 17:30 UTC
    Code Review
    native/spark-expr/src/predicate_funcs/assert_not_null.rs:1
    @@ -0,0 +1,354 @@
    +// Licensed to the Apache Software Foundation (ASF) under one
    +// or more contributor license agreements.  See the NOTICE file
    +// distributed with this work for additional information
    +// regarding copyright ownership.  The ASF licenses this file
    +// to you under the Apache License, Version 2.0 (the
    +// "License"); you may not use this file except in compliance
    +// with the License.  You may obtain a copy of the License at
    +//
    +//   http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing,
    +// software distributed under the License is distributed on an
    +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    +// KIND, either express or implied.  See the License for the
    +// specific language governing permissions and limitations
    +// under the License.
    +
    +use std::fmt::{Display, Formatter};
    +use std::hash::{Hash, Hasher};
    +use std::sync::Arc;
    +
    +use arrow::array::{new_empty_array, RecordBatch};
    +use arrow::datatypes::{DataType, FieldRef, Schema};
    +use datafusion::common::{internal_err, Result};
    +use datafusion::physical_expr::PhysicalExpr;
    +use datafusion::physical_plan::ColumnarValue;
    +
    +use crate::SparkError;
    +
    +/// Spark's `AssertNotNull`: returns its child unchanged, and fails if any row is NULL.
    +#[derive(Debug, Eq)]
    +pub struct AssertNotNull {
    +    child: Arc<dyn PhysicalExpr>,
    +    /// Spark's `walkedTypePath.mkString("\n", "\n", "\n")`, reported in the error.
    +    walked_type_path: String,
    +}
    +
    +impl Hash for AssertNotNull {
    +    fn hash<H: Hasher>(&self, state: &mut H) {
    +        self.child.hash(state);
    +        self.walked_type_path.hash(state);
    +    }
    +}
    +
    +impl PartialEq for AssertNotNull {
    +    fn eq(&self, other: &Self) -> bool {
    +        self.child.eq(&other.child) && self.walked_type_path == other.walked_type_path
    +    }
    +}

    The hand-written Hash and PartialEq impls compare the same two fields a derive would. AtLeastNNonNulls in the same directory derives #[derive(Debug, PartialEq, Eq, Hash)] over Vec<Arc<dyn PhysicalExpr>>, so #[derive(Debug, PartialEq, Eq, Hash)] here should compile and lets lines 38-49 go.

    comphead comphead commented on Dec 03, 2026 17:30 UTC
    Reviewer

    I checked the kernel, serde and error mapping against AssertNotNull in Spark 3.5.8, 4.0.1 and 4.1.1. The check is top-level only, the null test is a batch-level logical_null_count, and both shims rebuild Spark's exception (the plain NullPointerException on 3.5, NOT_NULL_ASSERT_VIOLATION on 4.x). The CometExecRule and aggregate changes are justified by Spark's lazy evaluation under LIMIT/OFFSET. Scala tests are the right choice here since AssertNotNull is a NonSQLExpression. The comments below are about how wide the aggregate gate is, one missing test of what that gate actually protects, and two small cleanups. I did not build or run anything, and I could not tie the CI (fork) failure to this diff from the thread data.

    andygrove andygrove commented on code on Dec 03, 2026 20:04 UTC
    Code Review
    spark/src/test/scala/org/apache/comet/CometAssertNotNullSuite.scala:1
    @@ -0,0 +1,367 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *   http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +package org.apache.comet
    +
    +import org.apache.spark.sql.{Column, CometTestBase, DataFrame}
    +import org.apache.spark.sql.catalyst.expressions.{And, CaseWhen, Cast, CreateNamedStruct, Divide, GetStructField, GreaterThan, If, IsNotNull, IsNull, Literal, Or}
    +import org.apache.spark.sql.catalyst.expressions.objects.AssertNotNull
    +import org.apache.spark.sql.comet.CometBaseAggregate
    +import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
    +import org.apache.spark.sql.execution.SparkPlan
    +import org.apache.spark.sql.functions.{col, sum, transform}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.types.{DoubleType, IntegerType, NullType}
    +
    +import org.apache.comet.rules.CometExecRule
    +
    +/**
    + * `AssertNotNull` is a `NonSQLExpression`, so SQL file tests cannot call it. These tests build it
    + * through the DataFrame API, as Spark's encoders and V2 table writes do.
    + */
    +class CometAssertNotNullSuite extends CometTestBase {
    +  import testImplicits._

    The import testImplicits._ on this line is unused. ./mvnw test-compile -Pspark-3.5,delta -Pstrict-warnings stops with Unused import here, and scalafix will flag it too. Could you drop it?

    andygrove andygrove commented on Dec 03, 2026 20:05 UTC
    Contributor

    I don't have anything else to add. I think @comphead covered everything.

    Reviewers
    Assignees
    parthchandra parthchandra
    Labels
    risk: low confidence: 88.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.1% · Lower = rushed or shallow review
    88.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.5% · Safe to merge
    8.5%