feat: native AssertNotNull #7837
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.
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.
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.
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.
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.
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?
I don't have anything else to add. I think @comphead covered everything.
comphead
parthchandra
Which issue does this PR close?
Closes #7049.
Rationale for this change
When a nullable value is written into a
NOT NULLcolumn or struct field of a DataSource V2 table, Spark wraps it inAssertNotNull. That includesINSERT,DataFrameWriterV2.append, and copy-on-writeUPDATEandMERGEassignments. Comet had no nativeAssertNotNull, 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:
LIMIT(PushProjectionThroughLimit). #7195 already caps a projection's input under a limit, so a native check reads only the rows the limit reads;GROUP BY/DISTINCT(CollapseProject);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
AssertNotNullinnative/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 useslogical_null_count, soNullArray, 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, soINdoes not mistake it for a constant.AssertNotNull(field 79) and a planner arm. A wrong child count returns an error instead of panicking.CometAssertNotNull. It sendswalkedTypePath.mkString("\n", "\n", "\n"), the exact string Spark puts in its message.Errors
SparkError::NotNullAssertViolationnow carrieswalked_type_path. It previously mapped to the wrong JVM error (_LEGACY_ERROR_TEMP_2148).QueryExecutionErrors.notNullAssertViolation(NOT_NULL_ASSERT_VIOLATION). The Spark 3.5 shim raises the plainNullPointerExceptionwith Spark 3.5's message.Rows Spark never evaluates
AssertNotNullstays in Spark (buildAggOp, and the matching preflight inCometExecRule.checkAggregateConversion). This coversGROUP BY/DISTINCTwrites. It applies with or without aLIMIT, which matches the last release for that shape.AssertNotNulldirectly under aGlobalLimitExecwith an offset, or under theLocalLimitExecright below it, stays in Spark (CometExecRule.tagOffsetSkippedChecks). With no shuffle in between, Spark computes it only for the rows theOFFSETkeeps.CometAssertNotNullreportsUnsupportedwhenspark.comet.exec.localLimit.enabled=false, since the projection input cap from #7195 needs Comet local limits.CASE/IF,AND/ORand nativeMergeRowsalready evaluate a fallible expression only on the rows that reach it.AssertNotNullis 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
spark.comet.expression.AssertNotNull.enabled(defaulttrue).spark.comet.exec.localLimit.enablednow also gatesAssertNotNull.SparkError::NotNullAssertViolation: the field and JSON parameter changed fromfieldNametowalkedTypePath. It had no producer before this change.How are these changes tested?
AssertNotNullis aNonSQLExpression, so Spark SQL can't call it, and V1 file tables never haveNOT NULLcolumns. 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.assert_not_null.rs, 12 tests): pass-through without a copy, NULLs in sliced, dictionary, run-end (including a slice inside the NULL run) andNullArrayinputs, 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,ANDandORthat skip the NULL row, in one batch;- native shuffle and aggregation, and a NULL computed by the child;
- a NULL literal of
INTand ofNullType, and a low-cardinality string column;- a lambda, which runs through the codegen dispatcher;
-
LIMITwith AQE on and off;- a sort with
LIMITandOFFSET, with NULLs past the cut and in the skipped rows;- the aggregate and
OFFSETfallbacks;- the disabled-expression and disabled-local-limit fallbacks.
CometIcebergWriteActionSuite(7 new tests): writes intoNOT NULLcolumns, struct fields (including a struct that is itselfNOT NULL), array elements and map values, through SQLINSERTandwriteTo().append(), including a bucketed table withwrite.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 ... LIMITwith AQE on and off;-
INSERT ... OFFSET, andLIMIT ... OFFSET, over a single partition;- a NULL struct written into a struct with a
NOT NULLfield;- copy-on-write
UPDATEandMERGE, including rows that the assignment must not check.SparkErrorConverterSuite: the converted error matches a realAssertNotNull.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 fullCometIcebergWriteActionSuiteon 4.1),CometExecRuleSuite,CometAggregateSuite,CometNativeCastSuite, and theexpressions/cast/limit_projection*.sqlfixtures from #7195;CometExecSuite,CometExpressionSuiteand both TPC-DS plan-stability suites on 4.1 and 4.0, andCometJoinSuiteandGenerateDocsSuiteon 4.1;CometAssertNotNullSuiteandSparkErrorConverterSuite;cargo testfordatafusion-comet-spark-expr,-common,-protoanddatafusion-comet.The new suite is registered in
pr_build_linux.ymlandpr_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,UpdateTableSuiteBaseandMergeIntoTableSuiteBase, and Iceberg'sTestUpdateandTestMerge(which check the error message on Spark 3.5), all exercise this path. Please applyrun-all-spark-profiles,run-spark-3.5-testsandrun-iceberg-tests.Known differences, documented in the compatibility guide
AssertNotNullbuilt by hand through the DataFrame API can fail on a row Spark never evaluates: as an operand of a null-intolerant operator, in anINlist, as the argument of an aggregate with aFILTER, or under aLIMITthat does not directly consume its projection (#7147). Spark's own write plans do not put the check in these places.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 NULLcolumns now stay in the Comet pipeline, including native shuffle and the native Iceberg writer, instead of falling back.