Repository navigation
[GLUTEN-10215][VL] Delta write: Native top-level NOT NULL checks - #12647
Conversation
There was a problem hiding this comment.
Took a close pass over this, mostly on the native side. The overall shape looks good and the fallback posture is genuinely conservative, so these are all about the check itself rather than the design. One of them (the getNullCount() early-outs) I think is a real correctness risk worth resolving before merge; the rest are robustness/perf/structure.
Note: AI assisted review
| if (rowVector->mayHaveNulls()) { | ||
| const auto nullCount = rowVector->getNullCount(); | ||
| if (nullCount.has_value()) { | ||
| if (*nullCount > 0) { | ||
| return 0; | ||
| } | ||
| } else { | ||
| for (auto row = 0; row < rowCount; ++row) { | ||
| if (rowVector->isNullAt(row)) { | ||
| return 0; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| for (int i = 0; i < numColumnsToCheck; ++i) { | ||
| const auto ordinal = safeColumnOrdinals.elems()[i]; | ||
| const auto child = rowVector->childAt(ordinal); | ||
| VELOX_CHECK_NOT_NULL(child, "Column vector is null when checking Delta invariant."); | ||
| if (!child->mayHaveNulls()) { | ||
| continue; | ||
| } | ||
| const auto nullCount = child->getNullCount(); | ||
| if (nullCount.has_value()) { | ||
| if (*nullCount > 0) { | ||
| return i; | ||
| } | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Correctness risk: getNullCount() isn't a sound gate for a NOT NULL check.
Both early-outs in this function (the rowVector one here, the child one below) treat getNullCount() == 0 as "no nulls" and skip the scan. Two problems, checked against the Velox revision we vendor:
- Wrapped vectors.
DictionaryVector::mayHaveNulls()is overridden to recurse into the base values (velox/vector/DictionaryVector.h:72-81), butgetNullCount()is not — it returnsBaseVector::nullCount_, i.e. only the wrapper's own nulls buffer (velox/vector/BaseVector.h:198). A dictionary whose wrapper nulls were reset (setNulls(nullptr)/clearNulls()setnullCount_ = 0, seevelox/vector/BaseVector.cpp:620,642,660) but whose base values contain nulls at referenced indices passesmayHaveNulls()and then takes thecontinuebranch. - Staleness.
nullCount_is a cached data-dependent statistic, not a maintained invariant.setNull()does not invalidate it (BaseVector.h:416-423); onlyresetDataDependentFlags()does, and that is called just fromensureWritable()/prepareForReuse()(BaseVector.h:980-993).
A wrapper-local or stale 0 means we continue and silently write a NULL into a NOT NULL column — no exception, table invariant broken, nothing downstream catches it. The opposite (a stale > 0) fails a valid write with a spurious DeltaInvariantViolationException. Velox itself only uses the mayHaveNulls() || getNullCount() == 0 shortcut on flat vectors it owns (velox/vector/arrow/Bridge.cpp:510), where it is an optimization rather than a correctness gate.
Since this is enforcing a table constraint, I don't think we can trust the cached count. Either gate the early-out on child->isFlatEncoding(), or drop it entirely and always scan — per the next comment, the scan can be made cheaper than it is today anyway.
There was a problem hiding this comment.
Good catch, thanks. You're right that the cached count can't be trusted for an invariant check, so in a007c3f I dropped getNullCount() entirely. Each constrained column now goes through a DecodedVector, so nulls in the base of a dictionary or constant wrapper are included, and the nulls are counted with bits::countNulls. Row-level nulls are read straight from the RowVector's own nulls buffer, since that one is always flat.
I also moved the scan into VeloxColumnarBatch::firstNullColumnIndex so it could be unit tested. VeloxColumnarBatchTest now covers a stale null count of 0, a dictionary with a null count of 0 over a null base value, a dictionary whose indices skip the null, a null constant, a null row, and a child that's longer than the batch.
| for (auto row = 0; row < rowCount; ++row) { | ||
| if (child->isNullAt(row)) { | ||
| return i; | ||
| } | ||
| } |
There was a problem hiding this comment.
The advertised fast path rarely fires, and this fallback is the expensive one.
nullCount_ is std::nullopt for essentially everything a Velox pipeline hands us: wrapInDictionary() leaves it unset, and ensureWritable() / prepareForReuse() reset it to nullopt. So in practice this per-row loop is the common path, not the "near-free metadata read" described in the PR body — a virtual isNullAt() per row per constrained column, plus dictionary indirection for dictionary-encoded columns (which is exactly what you get reading Parquet/Delta sources). That probably explains why the benchmark came out neutral.
Decoding once and counting bits is both sound (fixes the previous comment) and considerably faster:
DecodedVector decoded(*child, allRows);
if (decoded.mayHaveNulls() &&
bits::countNulls(decoded.nulls(&allRows), 0, rowCount) > 0) {
return i;
}(DecodedVector::nulls(const SelectivityVector*) — velox/vector/DecodedVector.h:146; bits::countNulls — velox/common/base/Nulls.h:59.) Or, if you'd rather not build a DecodedVector, bits::countNulls(child->rawNulls(), 0, rowCount) for the flat case. Either way it's a word-at-a-time scan instead of per-row virtual dispatch, and it removes the need to trust getNullCount() at all.
There was a problem hiding this comment.
Done, pretty much your snippet: decode with allRows, then bits::countNulls(decoded.nulls(&allRows), 0, numRows).
I was curious about the neutral benchmark as well, so I re-ran it and timed the JNI call on its own. On a 2M-row append (~490 batches) the check takes about 2 ms, both before and after this change. In these pipelines the vectors reaching the writer happened to take the old shortcut, so the per-row loop wasn't what made the old numbers neutral. Either way the new version is the correct one and costs nothing measurable. The native path now comes out about the same as an unconstrained write, and the row CHECK fallback is 21–28% slower. The numbers are in the description.
| isNativeWritable, | ||
| nativeInvariantChecker |
There was a problem hiding this comment.
The checker is silently dropped in the sibling write branch.
This call is the else of if (writeFilesOpt.isDefined) (L204). The WriteFilesExec branch calls the other executeWrite(sparkSession, plan, writeSpec, job) overload, which has no nativeInvariantChecker parameter — so if we ever reach it holding a checker, no NOT NULL constraint is enforced anywhere: the plan no longer carries DeltaInvariantCheckerExec either, and the write silently succeeds with invalid data.
Today that's unreachable — GlutenOptimisticTransaction only builds the checker when V1WritesUtils.getWriteFilesOpt(empty2NullPlan).isEmpty, and nothing applied between there and here (Transitions.toBatchPlan, GlutenDeltaOptimizedWriterExec) can introduce a WriteFilesExec. But that's an invariant spread across two files with nothing enforcing it, and the failure mode is silent data corruption rather than an error.
Could we make it fail loudly — e.g. require(nativeInvariantChecker.isEmpty, "...") in the writeFilesOpt.isDefined branch, or thread the checker through that overload as well? Everything else in this PR fails safe; this is the one path that doesn't.
There was a problem hiding this comment.
Agreed, this shouldn't depend on an invariant spread across two files. Both writers (src-delta33 and src-delta4) now require(nativeInvariantChecker.isEmpty, ...) in the writeFilesOpt.isDefined branch (a007c3f), so it fails loudly instead of writing unchecked. I didn't thread the checker through that overload, because WriteFilesExec runs its own tasks and there's no iterator there to wrap.
The other half, not building a checker when the plan has a WriteFilesExec, now lives in one place, GlutenDeltaInvariantChecker.forWrite (3da00cd), instead of being repeated in both transactions.
| private def checkRow(row: InternalRow): Unit = { | ||
| var i = 0 | ||
| while (i < notNullConstraints.size) { | ||
| val (ordinal, constraint) = notNullConstraints(i) | ||
| if (row.isNullAt(ordinal)) { | ||
| throw DeltaInvariantViolationException(constraint) | ||
| } | ||
| i += 1 | ||
| } | ||
| } |
There was a problem hiding this comment.
notNullConstraints is a Seq — a List in practice, since create builds it with collect/map — so both .size and apply(i) are O(n), and .size is re-evaluated on every iteration, making this O(n^2) per row. Small n, but this runs for every row of every non-offloaded write, so it seems worth precomputing.
columnOrdinals is already materialized as an Array above; a parallel array of constraints would make this allocation- and traversal-free:
@transient private lazy val constraints: Array[NotNull] =
notNullConstraints.map(_._2).toArray
private def checkRow(row: InternalRow): Unit = {
var i = 0
while (i < columnOrdinals.length) {
if (row.isNullAt(columnOrdinals(i))) {
throw DeltaInvariantViolationException(constraints(i))
}
i += 1
}
}That would also let the batch path at L63 use constraints(failedConstraintIndex) instead of notNullConstraints(failedConstraintIndex)._2, which pays the same O(n) apply cost.
There was a problem hiding this comment.
Fixed in a007c3f. The checker now takes columnOrdinals: Array[Int] and constraints: Array[NotNull] as parallel arrays, so both the batch path and the row path are plain array lookups. I also added GlutenDeltaInvariantCheckerSuite for the row path; it doesn't need the native library.
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.apache.spark.sql.delta.constraints |
There was a problem hiding this comment.
This file is byte-identical to backends-velox/src-delta40/main/scala/org/apache/spark/sql/delta/constraints/GlutenDeltaInvariantChecker.scala — I diffed the two copies and there isn't a single character of difference.
backends-velox/src-delta/main/scala is already registered as a shared source root across Delta versions (pom.xml:1699), and everything this file touches (Constraints.NotNull, SchemaUtils.DELTA_COL_RESOLVER, DeltaInvariantViolationException) is identical on 3.3 and 4.0 — otherwise the two copies couldn't be identical. Could this live in src-delta once instead of twice?
Worth doing while the file is new: the delta33/delta40 copies of GlutenOptimisticTransaction have already drifted (DeltaInvariantCheckerExec(spark, ...) vs DeltaInvariantCheckerExec(...)), and a duplicated checker will drift the same way — except here a divergence means one Delta version enforces constraints differently from the other.
There was a problem hiding this comment.
Good point, moved. There's a single copy now, in backends-velox/src-delta/main/scala/org/apache/spark/sql/delta/constraints/GlutenDeltaInvariantChecker.scala (a007c3f). Since #13271 the 4.x side is src-delta4, so this one file covers Delta 3.3 and 4.4. It also compiles against Delta 2.4 for the Spark 3.4 build, where it isn't used.
The same drift concern applied to the code deciding whether to use the checker, which was still duplicated in both GlutenOptimisticTransactions, so that moved into the same file as forWrite (3da00cd).
|
/delta-test |
|
🔄 Delta Spark UT started by @felipepessoto (~2.5 h). View run |
|
/delta-test |
|
🔄 Delta Spark UT started by @felipepessoto (~2.5 h). View run |
…-not-null-checks apache#13271 replaced backends-velox/src-delta40 with src-delta4. The PR's src-delta40 changes move there: GlutenDeltaInvariantChecker goes to src-delta4, and the GlutenOptimisticTransaction changes go into src-delta4's glutenPhysicalPlan helper, which now also returns the native invariant checker for the Velox writer.
- Find nulls by decoding each constrained column and counting its nulls a word at a time, instead of trusting the cached null count: it can be stale, and on a dictionary or constant wrapping it misses the nulls of the wrapped values. The scan moves into VeloxColumnarBatch::firstNullColumnIndex, with unit tests. - Fail the write if a native invariant checker reaches the WriteFilesExec branch of GlutenDeltaFileFormatWriter, which cannot apply it. - Keep the checker's column ordinals and constraints in parallel arrays. - Move GlutenDeltaInvariantChecker into the shared src-delta tree, so that every Delta version enforces the constraints the same way. - Undo the reindentation of the spotless:off src-delta4 writer. - Test the checker without a native library, and NOT NULL violations in data read from Parquet and with optimized writes.
…e Delta docs A partitioned native write sorts the rows natively before writing them. The native NOT NULL check runs after that sort, on the JVM, so violations keep Delta's DeltaInvariantViolationException instead of being wrapped in a GlutenException. Test it on Spark 3.5 and 4.x, including an empty string partition value that Delta turns into a null, and update VeloxDelta.md, which still described the row-based check for every NOT NULL write.
…lace Both Delta transactions picked the checker with the same lines. Move them into GlutenDeltaInvariantChecker.forWrite, which also keeps Delta's row checker when spark.databricks.delta.constraints.convertEmptyToNullForStringPartitionCol is off and the table has a string partition column. Delta then checks the empty strings themselves, while the native checker would see the nulls the writer turns them into, and would fail writes that Delta accepts.
|
@felipepessoto thanks for the thorough review, and sorry it took a while to get back to this. I merged main (the 4.x side now lives in cc @zhouyuan @zhztheplayer, since you asked on #12030 why this isn't an offloaded expression. The design note in the description covers that. |
Move the NOT NULL tests into the existing DeltaNativeWriteSuite of each Delta tree, which drops DeltaNativeWriteInvariantSuite and the helpers it copied. Each tree keeps three tests: - a native write with neither Delta's row checker nor C2R, and its violation, with and without optimized writes; - CHECK constraints keep DeltaInvariantCheckerExec; - violations on a partitioned table. Drop the Parquet-source test. VeloxColumnarBatchTest covers dictionary encodings directly, and the end-to-end test could not ensure them. Shorten the checker's doc comment, which repeated the PR description.
|
Thanks for addressing the comments. I’ve checked the latest revision and verified the null-bitmap handling, write-path guards, array lookups, and shared implementation. The fallback paths also look correct. No further blockers from my review. |
| val rowInvariantPlan = if (constraints.isEmpty) { | ||
| // Compared to vanilla Delta, we simply avoid adding the invariant checker | ||
| // when the constraint list is empty, to prevent the unnecessary transitions | ||
| // from being added around the invariant checker. | ||
| empty2NullPlan | ||
| } else { | ||
| DeltaInvariantCheckerExec(empty2NullPlan, constraints) | ||
| } |
There was a problem hiding this comment.
Have we tried to write a columnar version of DeltaInvariantCheckerExec ?
I asked a similar question about CheckDeltaInvariant and haven't found the clue why that direction isn't feasible in the PR description and other places, or did I miss something?
There was a problem hiding this comment.
My bad @zhztheplayer, I only just saw your comment on #12030 from before it was closed as stale. I missed it, and I wish I'd seen it sooner, because you were right to push back on this.
The reason we put the check in the writer was to keep Delta's own DeltaInvariantViolationException. An error raised inside Velox only reaches Spark as a GlutenException, so the check had to throw on the JVM. In the writer's task the batches are already on the JVM and sorted, so nothing native runs above it. We never tried a columnar DeltaInvariantCheckerExec.
I've prototyped your approach since, and there's no real blocker. I wrote a ColumnarToColumnarExec at Delta's position that calls the same firstNullColumnIndex, and tested it on Spark 3.5.
On unpartitioned writes it works as is. On partitioned writes, and on optimized writes with more than one input partition, Velox pulls the node's batches through the writer's native sort or the shuffle's hash projection, so the exception comes back as a GlutenException. Delta's row checker has the same problem there today.
I think @felipepessoto #13560/#13561 fix that: they keep Java exceptions intact when they pass through native code. With a small local stand-in for his change, every path kept Delta's exception, and Delta's CHECK errors on partitioned writes came out right too. At Delta's position the node also runs before the writer turns empty partition strings into nulls, so the guards our writer approach needed go away. The only cost I saw is that the node splits the native sort into its own stage.
If we don't want to wait for #13561, the writer can lift the node above its native sort. I tested that too: Delta's exception came through on every path, and the sort stayed in the same stage. It still needs the empty-partition-string guard, and the lift can be removed once #13561 lands.
Which would you prefer: the lifted version now, or the node at Delta's position on top of #13561? And should CHECK, generated-column and nested NOT NULL constraints go into this PR or a follow-up?
There was a problem hiding this comment.
Thanks for the explanation. I prefer a node over this approach but #13561 might need to take some time to land. Do you think there's a way to keep a very small workaround just for this feature, to unwrap GlutenException into a DeltaInvariantViolationException by some heuristics? E.g., matching on the error message, etc?
There was a problem hiding this comment.
Yes to unwrap the GlutenException into a DeltaInvariantViolationException I went with matching on the error message, as you suggested:
- When the write fails, the transaction looks for the exact NOT NULL message of each constraint the node checks. If it finds one, it rethrows Delta's
DeltaInvariantViolationException. Any other error is rethrown as is. - There's a TODO to remove this once [VL] Preserve Java exceptions through native iterators #13561 lands.
I also moved the check into its own node, GlutenDeltaInvariantCheckerExec, placed where Delta puts DeltaInvariantCheckerExec, so the writer changes are gone.
…Exec Plan GlutenDeltaInvariantCheckerExec where Delta plans its row-based DeltaInvariantCheckerExec, instead of wrapping the Velox writer's task iterator. The writer no longer takes a checker. When native code pulls the node's batches (the writer's sort on partitioned writes, the optimized-write shuffle), it keeps only the violation's text. The transaction then finds that text in the failure and rethrows Delta's DeltaInvariantViolationException, until apache#13561 keeps Java exceptions across native code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zhztheplayer
left a comment
There was a problem hiding this comment.
Just a nit from my end, thanks.
| plan = glutenPhysicalPlan( | ||
| spark, empty2NullPlan, constraints, nativeInvariantChecker, isOptimize, writeOptions), |
There was a problem hiding this comment.
nit: Can we create the nativeInvariantChecker inside the glutenPhysicalPlan method? As we already passed constraints here, to reduce the overlapping among the arguments?
There was a problem hiding this comment.
Good idea added this in 13b7af9 soglutenPhysicalPlan now creates the checker itself and its arguments are back to what they are on main.
…alPlan glutenPhysicalPlan already gets the constraints, so it now creates the checker itself and its arguments are back to what they are on main. The unwrap moves into a catch around the native write. It takes the checker from the plan's GlutenDeltaInvariantCheckerExec and leaves failures that Delta's InnerInvariantViolationException already handles to Delta's catch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| case NonFatal(e) if InnerInvariantViolationException.unapply(e).isEmpty => | ||
| val checker = glutenPlan.collectFirst { | ||
| case exec: GlutenDeltaInvariantCheckerExec => exec.checker | ||
| } | ||
| throw checker.flatMap(_.findViolation(e)).getOrElse(e) |
There was a problem hiding this comment.
nit: can we turn findViolation to a static method so we don't need the unwrap here? In another word, can we make findViolation independent of constraints? Since it is a workaround that will be removed shortly anyway.
There was a problem hiding this comment.
Done in 8c56429. findViolation is static now: it reads the column name from the NOT NULL violation's text and rebuilds Delta's exception, so the transaction calls it directly. Thanks for the insight.
findViolation no longer needs the checker's constraints. It finds the text of a NOT NULL violation in the failure, takes the column name from it and rebuilds Delta's exception with the constructor Delta uses. Both transactions call it directly, so the transaction no longer looks up the checker in the plan. NOT NULL violations from Delta's row checker whose text reaches the driver only inside a GlutenException now keep Delta's exception type too. CHECK violations still do not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
What changes are proposed in this pull request?
Delta writes on Velox check constraints with Delta's row-based
DeltaInvariantCheckerExec, so one top-levelNOT NULLcolumn is enough to turn every written batch into rows and back. This PR checks top-levelNOT NULLon the Velox batches instead.GlutenDeltaInvariantCheckerExecis a columnar node planned where Delta putsDeltaInvariantCheckerExec. It's used only when every constraint is a top-levelNOT NULL; aCHECK, a generated column or a nestedNOT NULLkeeps Delta's node.VeloxColumnarBatch::firstNullColumnIndex). It decodes each column, so dictionary and constant vectors are covered and the cached null count isn't trusted.DeltaInvariantViolationException. When native code pulls the node's batches (the writer's sort on partitioned writes, the optimized-write shuffle), only the exception's text survives, so the transaction looks for that text in the failure and rethrows Delta's exception. This is a stopgap until [VL] Preserve Java exceptions through native iterators #13561 keeps Java exceptions across native code.Spark 3.5 and 4.x each have their own copy of the transaction, which is why the wiring and the end-to-end tests appear twice.
Related issue: #10215. Supersedes #12030.
How was this patch tested?
VeloxColumnarBatchTest: dictionary and constant vectors, stale null count.GlutenDeltaInvariantCheckerSuite: which constraints are checked natively, and finding the violation in the failures Spark and Gluten produce.DeltaNativeWriteSuite(3.5 and 4.x): the new node replaces Delta's; violations on plain, partitioned and optimized writes; aCHECKkeeps Delta's node.I ran the Delta suites locally on Spark 3.5 and 4.1. No PR CI job runs them; the nightly Spark 3.5 job does.
Was this patch authored or co-authored using generative AI tooling?
Generated-by: IBM Bob, Claude Code (claude-opus-5-5)
cc @felipepessoto @zhztheplayer @zhouyuan