parthchandra opened a new pull request, #7837:
URL: https://github.com/apache/datafusion-comet/pull/7837

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


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