Repository navigation
fix: make INSERT IGNORE tolerate NOT NULL violations - #32299
Conversation
## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to matrixorigin#30906 ## What this PR does / why we need it: `INSERT IGNORE` already downgraded duplicate-key, foreign-key and CHECK failures to warnings, but a NULL supplied for a NOT NULL column aborted the whole statement, so a multi-row batch inserted nothing where MySQL keeps the good rows and replaces the offending cells with the column type's implicit default, publishing warning 1048 per adjusted cell: ``` mysql> insert ignore into ig(u,nn,c) values(2,null,1); ERROR 3819 (HY000): constraint violation: Column 'nn' cannot be null ``` Root cause: no value-adjustment stage existed between the constructed row image and the constraint consumers, so the NOT NULL gate in the insert path always raised the hard violation even under statement IGNORE (and the 3819 check-constraint class hid the NOT NULL origin). A second gap surfaced in review of this change: the planner's unique-index skip heuristic decided "this key is all-NULL" from pre-adjustment observations, so an omitted NOT NULL column whose DEFAULT folds to NULL (`u BIGINT NOT NULL DEFAULT (abs(NULL))` under `UNIQUE KEY uk(u)`) escaped unique arbitration and index writes entirely - both rows of `INSERT IGNORE INTO t(id) VALUES (1),(2)` stored as `u=0` with no 1062 and no index entries, and a later strict `INSERT INTO t VALUES (99, 0)` was also accepted. What this PR does (everything below applies under statement IGNORE only; strict statements keep the historical rejections): - Planner (`pkg/sql/plan/bind_insert.go`, `build_load.go`, `opt_misc.go`, `types.go`, `bind_update_fk.go`): coalesce omitted-column and DEFAULT-keyword projections into row-level default expressions, and wrap every NULL-computed NOT NULL cell (DEFAULT expressions, generated columns, dependent defaults, value-scan defaults, LOAD omitted-column defaults) with the same implicit-default fill the executor applies, so every consumer reads the adjusted image; decide the unique-index skip from the value after the fill (`uniqueNullDefaultRefilledForIgnore` - an omitted NOT NULL column with a fillable NULL-folding DEFAULT keeps its key in unique arbitration, lock keys and index-table maintenance); keep computed unique lock-key projections physical for the CHECK/FK barrier filter; build FK parent locks from the adjusted image. - Executors: run the adjustment inside PRE_INSERT (`pkg/sql/colexec/preinsert/preinsert.go`, `types.go`) ahead of CHECK/unique/FK validation and the write - a NULL cell of a NOT NULL column is set to the implicit default of the column type and publishes one warning 1048 `Column 'X' cannot be null`; the shared fill utility (`pkg/sql/colexec/constraint_util.go`) covers every fillable family and keeps the hard 3819 rejection for GEOMETRY/DATALINK/array cells (they have no implicit default); the single-column NOT NULL primary key is resolved by NAME for its NULL-key drop, whatever declaration shape or position it has; the insert main-table leg and its S3 writer (`pkg/sql/colexec/multi_update/insert.go`, `s3writer_delegate.go`) and the minimal external-insert path (`pkg/sql/colexec/insert/insert.go`) apply the same rule, so every INSERT shape (VALUES, INSERT ... SELECT, LOAD, external) honors it. - UPDATE statements keep the strict 3819 rejection for NOT NULL violations on every code path - the IGNORE tolerance is INSERT-shaped only; no UPDATE silently rewrites a NULL violation into the implicit default. Issue-to-test proof (each focused regression was first proven failing on the pre-fix tree and passing after the fix; per-round logs are retained by the loop): the runtime suite `test/distributed/cases/dml/insert/issue_30906_insert_ignore_not_null.test` shows `insert ignore into ig(u,nn,c) values(2,null,1)` succeeding with exactly one warning 1048 and `(2,0,1)` stored; the multi-row batch keeps its good rows and adjusts only the offending cells; the CHECK/unique/FK consumers and later statements evaluate the adjusted values (duplicates of filled values are rejected with 1062, in-statement and cross-statement); and, for the reviewed gap, the omitted NOT NULL `DEFAULT (abs(NULL))` unique column keeps unique maintenance - the first row stores, the loser skips with 1062, and a later strict INSERT of the filled value fails 1062. On a service binary built from the pre-fix tree the same suite fails at exactly the previously-failing statements (missing fills/warnings/1062) while the fixed binary runs it 386/386 in both mo-tester run modes. Two pre-existing goldens drop exactly the two `constraint violation: Column 'X' cannot be null` lines that no longer occur: in `insert_ignore.result` the IGNORE batch into the NOT NULL price column now succeeds, and in `on_duplicate_ignore.result` the `on duplicate key ignore` batch with NULL key values drops those rows like any ignored insert instead of erroring; everything else in those files is untouched (their historical `[unknown result because it is related to issue#15345]` placeholders and pre-existing comparator deltas are byte-identical between the pre-fix and fixed binaries). Tests (all green on the fixed tree): - `pkg/sql/plan/bind_insert_unique_null_default_test.go`: `TestInsertIgnoreUniqueMaintenanceSurvivesFilledNullDefault`, `TestInsertIgnoreFilledNullDefaultKeepsUniqueArbitrationAndIndexWorks` - unique maintenance for filled NULL defaults, nullable/no-default/ strict controls keeping the historical skip, per-index independence. - Planner default normalization: `bind_insert_filled_default_test.go`, `bind_insert_dependent_normalization_test.go`, `bind_insert_computed_notnull_value_scan_test.go`, `bind_load_dependent_default_ignore_test.go`. - Executors: `colexec/preinsert/preinsert_ignorefill_test.go`, `preinsert_alias_test.go`, `preinsert_alias_transition_test.go`, `colexec/constraint_util_ignorefill_test.go`, `colexec/multi_update/insert_ignore_fill_test.go` (per-family fills, per-family rejections, strict checks, PK NULL-key drop by name, aliased source vectors and slot ownership), and the extended `colexec/insert/insert_extwrite_test.go`. - BVT: `issue_30906_insert_ignore_not_null.test` + generated `.result` covering single/multi-row batches, warning multisets, stored images, unique/CHECK/FK interplay, dependent and generated defaults, LOAD IGNORE NULL markers, GEOMETRY/DATALINK rejections and the NULL-default-under-UNIQUE controls. Commands (repository CGo environment; `mo-cgo-test` wraps `go test`; focused selections were run with the same invocation on the pre-fix tree to record the RED side): ./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 \ ./pkg/sql/colexec ./pkg/sql/colexec/preinsert \ ./pkg/sql/colexec/multi_update ./pkg/sql/colexec/insert \ ./pkg/sql/plan # ok colexec 3.7s / preinsert 2.2s / multi_update 6.2s / insert 8.2s / plan 247.3s ./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 ./pkg/sql/plan # re-run after the final change: ok plan 107.6s ./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -race \ -run 'InsertIgnore' ./pkg/sql/plan # ok gofmt -l <changed .go files> # empty go vet -mod=readonly ./pkg/sql/plan ./pkg/sql/colexec/preinsert # clean golangci-lint run -c .golangci.yml \ --new-from-rev 21d67b2 \ ./pkg/sql/plan/... ./pkg/sql/colexec/preinsert/... # 0 issues # BVT (shared mo-tester, JDBC against a local mo-service): java -cp .../mo-tester/lib/'*' io.mo.Tester \ "path=test/distributed/cases/dml/insert/issue_30906_insert_ignore_not_null.test" \ method=run ignore # 386/386 in both run modes (ignore and no-ignore), 0 error bytes Residual risks / pinned divergences (deliberate, documented in the tests): - A NULL for a single-column NOT NULL PRIMARY KEY drops the row in PRE_INSERT (the key cell stays unadjusted; the row's other supplied NULL cells still publish their 1048 warnings); MySQL inserts the implicit-default row and lets duplicate arbitration skip later ones. - UPDATE (including UPDATE IGNORE) keeps the strict 3819 rejection for NOT NULL violations. - GEOMETRY/DATALINK NOT NULL cells keep the 3819 rejection under IGNORE (no implicit default exists for them). - LOAD IGNORE publishes 1048 for a filled cell where MySQL publishes 1263; warnings are one per offending cell (MySQL deduplicates identical messages within a statement). - Omitting a NOT NULL column that has no default keeps the pre-existing `invalid default value` rejection under IGNORE (pre-existing gap, unchanged). - Out-of-range clamping (matrixorigin#27340), INSERT IGNORE AUTO_INCREMENT gaps (matrixorigin#28238) and INSERT IGNORE combined with ON DUPLICATE KEY UPDATE (matrixorigin#28159) remain separate open defects.
Resolve the DIRTY merge state that stalled Mergify's auto-update for PR matrixorigin#32299 (matrixorigin#30906). Hand-resolved the three bind_insert.go content hunks so both the INSERT IGNORE implicit-default-fill machinery and the new upstream contracts survive: - generated-column loop: keep the assignmentIgnore coalescing of dependent-row references to the implicit-default fill, then apply upstream's RequireMySQLConditionalBooleanConsumption gate on the final expression so a native-mode statement still fails closed. - both value-scan default sites: keep the ignore-fill coalescing and take upstream's forceCastExpr2 column-name argument for cast error messages. Adopt upstream's Vector.Shrink(sels, negate, mp) error-returning signature in the ignore path's DropNullPkRowsForIgnore row filter (constraint_util.go), the one semantic drift left by the merge.
A types.T switch that names T_float32/T_float64 must also name the low-precision subfamily members (TestTypeSwitchFamilies / G-TYPESWITCH): setImplicitNotNullDefault now fills the implicit NOT NULL default (+0, all-zero bits) of bf16/float16/float8/float4 columns, and implicitFilledChildDefaultExpr mirrors the same fill as float32(0) assignment-cast to the column type so the INSERT IGNORE foreign-key filter evaluates the value the write pipeline stores. UTs extend the fillable-type enumeration and the plan-side mirrored classification to the four types.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: d58f4f5e311a35d18302796993b47dbe43d15306
Assessment: request_changes
The shared fill/PRE_INSERT design is coherent, and all three earlier findings are resolved. One external LOAD path still corrupts nullable values through aliased vectors.
Model: gpt-6.1-sol / max
Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0
- P2
pkg/sql/colexec/insert/insert.go:274: LOAD DATA ... IGNORE into a writable external table (a BIGINT, b BIGINT NOT NULL DEFAULT (a)), supplying only a with mixed rows 1, NULL, 2.
Impact: The dependent-default projection shares a's flat vector with b. Filling b also overwrites nullable a and clears its NULL bitmap, so the external writer emits (0,0) instead of (NULL,0).
Evidence: build_load.go:1037-1107 stages DEFAULT(a), and bind_insert.go:5878 leaves nullable references unchanged. ColumnExpressionExecutor.Eval and Projection preserve the shared pointer. The external plan bypasses PRE_INSERT's alias separation, while snapshot/restore here handles only constant replacements. Detach aliased flat destinations before filling, retain cleanup ownership, and extend the existing Projection/external-write test to inspect the nullable sibling. Source trace and unexecuted SQL witness are retained in probes/external-alias-source-evidence.md and probes/external_alias.sql.
Validation:
-
Reviewed all 29 changed files, affected consumers, eight discussion entries and four linked issues; saved discussion-assessment.json.
-
Isolation preflight passed: checks/1793977038749319015-2.json; preflight.log.
-
Source integrity, formatting of 25 Go files and discussion coverage passed: checks/1793977777335491897-2.json; static-audit-v2.log. Whitespace diagnostics were limited to three intentional empty golden cells.
-
Frozen-head CI metadata reports 13 successful jobs, including UT, build, SCA and enabled PROXY/PESSIMISTIC BVT; 14 skipped and two neutral jobs were not counted as passes.
-
Focused external tests stopped before compilation because compatible CGo prerequisites are missing: checks/1793977071719084980-2.json; focused-external-tests.log. All five check receipts were reconciled in validation-evidence.json.
Limitations:
-
The finding is established by source tracing; its SQL witness was not executed. No MatrixOne tests, race tests or SQL ran locally.
-
Supplied CI statuses and author validation reports lack raw per-test logs.
The external IGNORE fill runs in place on the child's borrowed batch, and the minimal external-insert plan projects a dependent NOT NULL default on a nullable reference (b DEFAULT (a)) as a raw column reference: the column executor hands b the very flat vector holding a, and the external plan runs no PreInsert whose repeated-vector separation would split the alias. Filling b's slot then also overwrote a's NULL cells with the implicit default and cleared a's live null bitmap, so the writer emitted (0,0) where the load supplied (NULL, 0). checkExternalNotNull now detaches every aliased flat fill destination before the fill: a vector shared by two slots that holds a live NULL and sits in a NOT NULL destination gets operator-owned storage, detached with the same NewVec + UnionBatch copy PreInsert uses on the internal path and booked through ctr.extFillOwned, so insert_external keeps returning the child's slot and freeing the copy on every path out of a batch. Vectors without NULL cells keep the single in-place fill, constants keep the replacement mechanism, and external batches with no NOT NULL destination skip the scan. Reproduced RED on the reviewer's shape through the real Projection chain (writer observed (0,0) instead of (NULL,0)); both new tests pin the sibling, the booking, the writer's cells and the per-batch release.
|
Review disposition — Verified the P2 exactly as traced and reproduced it before touching the code:
Fix (commit New coverage (both RED on
Validation on the new head: RED→GREEN receipts retained ( Re-requesting review. |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 20b8f908f522c7e5a793fb50e31d8543190a48fa
Assessment: approve
The shared fill/PRE_INSERT design remains coherent. The external path reuses vector-copy primitives and its existing cleanup owner to preserve aliased nullable values and release replacement buffers. Earlier findings are resolved; no actionable findings remain.
Model: gpt-6.1-sol / max
Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0
Validation:
-
Assessed all 29 changed paths: qualified 26 unchanged paths against review 5802289697 and inspected all three follow-up files and affected owners. Reconciled 11 discussion entries and four linked issues.
-
Local static audit passed 18 checks, including formatting of 25 Go files. Receipt checks/1793996007073378236-3.json and review-audit.log retained.
-
Reused exact-head successful build, UT, SCA, coverage and PROXY/PESSIMISTIC BVT summaries; considered author-reported regression controls and race results.
Limitations:
-
No fresh Go/native tests or live SQL execution; raw CI and author runtime logs were unavailable.
-
Documented NULL-primary-key, UPDATE and LOAD-diagnostic divergences remain; related assignment, ODKU and auto-ID issues are outside this fix.
|
@Mergifyio queue |
✅ Merged into
|
What type of PR is this?
Which issue(s) this PR fixes:
Related to #30906
What this PR does / why we need it:
INSERT IGNOREalready downgraded duplicate-key, foreign-key and CHECKfailures to warnings, but a NULL supplied for a NOT NULL column aborted
the whole statement, so a multi-row batch inserted nothing where MySQL
keeps the good rows and replaces the offending cells with the column
type's implicit default, publishing warning 1048 per adjusted cell:
Root cause: no value-adjustment stage existed between the constructed
row image and the constraint consumers, so the NOT NULL gate in the
insert path always raised the hard violation even under statement IGNORE
(and the 3819 check-constraint class hid the NOT NULL origin). A second
gap surfaced in review of this change: the planner's unique-index skip
heuristic decided "this key is all-NULL" from pre-adjustment
observations, so an omitted NOT NULL column whose DEFAULT folds to NULL
(
u BIGINT NOT NULL DEFAULT (abs(NULL))underUNIQUE KEY uk(u))escaped unique arbitration and index writes entirely - both rows of
INSERT IGNORE INTO t(id) VALUES (1),(2)stored asu=0with no 1062and no index entries, and a later strict
INSERT INTO t VALUES (99, 0)was also accepted.
What this PR does (everything below applies under statement IGNORE
only; strict statements keep the historical rejections):
pkg/sql/plan/bind_insert.go,build_load.go,opt_misc.go,types.go,bind_update_fk.go): coalesceomitted-column and DEFAULT-keyword projections into row-level default
expressions, and wrap every NULL-computed NOT NULL cell (DEFAULT
expressions, generated columns, dependent defaults, value-scan
defaults, LOAD omitted-column defaults) with the same implicit-default
fill the executor applies, so every consumer reads the adjusted image;
decide the unique-index skip from the value after the fill
(
uniqueNullDefaultRefilledForIgnore- an omitted NOT NULL columnwith a fillable NULL-folding DEFAULT keeps its key in unique
arbitration, lock keys and index-table maintenance); keep computed
unique lock-key projections physical for the CHECK/FK barrier filter;
build FK parent locks from the adjusted image.
(
pkg/sql/colexec/preinsert/preinsert.go,types.go) ahead ofCHECK/unique/FK validation and the write - a NULL cell of a NOT NULL
column is set to the implicit default of the column type and publishes
one warning 1048
Column 'X' cannot be null; the shared fill utility(
pkg/sql/colexec/constraint_util.go) covers every fillable familyand keeps the hard 3819 rejection for GEOMETRY/DATALINK/array cells
(they have no implicit default); the single-column NOT NULL primary
key is resolved by NAME for its NULL-key drop, whatever declaration
shape or position it has; the insert main-table leg and its S3 writer
(
pkg/sql/colexec/multi_update/insert.go,s3writer_delegate.go) and the minimal external-insert path(
pkg/sql/colexec/insert/insert.go) apply the same rule, so everyINSERT shape (VALUES, INSERT ... SELECT, LOAD, external) honors it.
violations on every code path - the IGNORE tolerance is INSERT-shaped
only; no UPDATE silently rewrites a NULL violation into the implicit
default.
Issue-to-test proof (each focused regression was first proven failing on
the pre-fix tree and passing after the fix; per-round logs are retained
by the loop): the runtime suite
test/distributed/cases/dml/insert/issue_30906_insert_ignore_not_null.testshows
insert ignore into ig(u,nn,c) values(2,null,1)succeeding withexactly one warning 1048 and
(2,0,1)stored; the multi-row batch keepsits good rows and adjusts only the offending cells; the CHECK/unique/FK
consumers and later statements evaluate the adjusted values (duplicates
of filled values are rejected with 1062, in-statement and
cross-statement); and, for the reviewed gap, the omitted NOT NULL
DEFAULT (abs(NULL))unique column keeps unique maintenance - the firstrow stores, the loser skips with 1062, and a later strict INSERT of the
filled value fails 1062. On a service binary built from the pre-fix
tree the same suite fails at exactly the previously-failing statements
(missing fills/warnings/1062) while the fixed binary runs it 386/386 in
both mo-tester run modes. Two pre-existing goldens drop exactly the two
constraint violation: Column 'X' cannot be nulllines that no longeroccur: in
insert_ignore.resultthe IGNORE batch into the NOT NULLprice column now succeeds, and in
on_duplicate_ignore.resulttheon duplicate key ignorebatch with NULL key values drops those rowslike any ignored insert instead of erroring; everything else in those
files is untouched (their historical
[unknown result because it is related to issue#15345]placeholders and pre-existing comparatordeltas are byte-identical between the pre-fix and fixed binaries).
Tests (all green on the fixed tree):
pkg/sql/plan/bind_insert_unique_null_default_test.go:TestInsertIgnoreUniqueMaintenanceSurvivesFilledNullDefault,TestInsertIgnoreFilledNullDefaultKeepsUniqueArbitrationAndIndexWorksstrict controls keeping the historical skip, per-index independence.
bind_insert_filled_default_test.go,bind_insert_dependent_normalization_test.go,bind_insert_computed_notnull_value_scan_test.go,bind_load_dependent_default_ignore_test.go.colexec/preinsert/preinsert_ignorefill_test.go,preinsert_alias_test.go,preinsert_alias_transition_test.go,colexec/constraint_util_ignorefill_test.go,colexec/multi_update/insert_ignore_fill_test.go(per-family fills,per-family rejections, strict checks, PK NULL-key drop by name,
aliased source vectors and slot ownership), and the extended
colexec/insert/insert_extwrite_test.go.issue_30906_insert_ignore_not_null.test+ generated.resultcovering single/multi-row batches, warning multisets, stored images,
unique/CHECK/FK interplay, dependent and generated defaults, LOAD
IGNORE NULL markers, GEOMETRY/DATALINK rejections and the
NULL-default-under-UNIQUE controls.
Commands (repository CGo environment;
mo-cgo-testwrapsgo test;focused selections were run with the same invocation on the pre-fix tree
to record the RED side):
Residual risks / pinned divergences (deliberate, documented in the
tests):
PRE_INSERT (the key cell stays unadjusted; the row's other supplied
NULL cells still publish their 1048 warnings); MySQL inserts the
implicit-default row and lets duplicate arbitration skip later ones.
NOT NULL violations.
(no implicit default exists for them).
1263; warnings are one per offending cell (MySQL deduplicates
identical messages within a statement).
pre-existing
invalid default valuerejection under IGNORE(pre-existing gap, unchanged).
([Bug]: INSERT IGNORE maps AUTO_INCREMENT gaps to accepted rows differently from MySQL #28238) and INSERT IGNORE combined with ON DUPLICATE KEY UPDATE
([Compatibility]: INSERT IGNORE with ON DUPLICATE KEY UPDATE is rejected #28159) remain separate open defects.
Base update (upstream main merge, 2026-11-06)
Main advanced past the PR base, and Mergify's
Auto update branchrulecould not resolve the conflicts in
pkg/sql/plan/bind_insert.go(merge state
DIRTY). The branch head now carries a manual merge oforigin/main(2746f81c36) that keeps this PR's behavior and the newupstream contracts side by side:
bind_insert.go: keep the IGNORE fillcoalescing of dependent-row references, then apply upstream's
RequireMySQLConditionalBooleanConsumptiongate on the finalexpression, so native-mode statements keep failing closed;
take upstream's extended
forceCastExpr2signature so cast errorscarry the column name;
pkg/sql/colexec/constraint_util.go: the NULL-PK row filter adoptsupstream's error-returning
Vector.Shrink(sels, negate, mp)signature(the one make-wide semantic drift the merge left behind).
Post-merge re-validation of the merged tree (logs retained by the loop;
mo-cgo-testwrapsgo test, counts fresh with-count=1):Those runs include the fresh upstream tests in the merged packages
(pre-insert PK-history retry, conditional-boolean consumption gates,
forceCastExpr2cast-error naming), confirming the interactions areclean in both directions. The branch is current with
mainagain; theremote CI run on the new head carries the distributed BVT suite.
CI repair: complete the float family in the fill switches (r16)
The
UT Coverage on Ubuntu/x86job failedTestTypeSwitchFamilies(
pkg/container/types): the twotypes.Tswitches this PR adds listed onlyT_float32/T_float64, which names a part of the float family withoutcovering the low-precision subfamily (
T_bf16,T_float16,T_float8,T_float4) — the repository's G-TYPESWITCH gate requires every member, andthe omission was not intended. Both switches now cover the whole family:
pkg/sql/colexec/constraint_util.go(setImplicitNotNullDefault): abf16/float16/float8/float4cell now fills all-zero bits (+0, code0 in every one of these formats — the exact zero
CanonicalLowPrecFloatpins), so under
INSERT IGNOREa NULL in a NOT NULL low-precision-floatcolumn stores
0with warning 1048, like every other numeric.pkg/sql/plan/bind_insert.go(implicitFilledChildDefaultExpr): the samefill is mirrored as
float32(0)assignment-cast to the column type (thedecimal families' shape), so the IGNORE foreign-key filter evaluates the
value that gets stored; if a cast cannot be built the classification
degrades to unmirrored (write side still fills; the FK existence check sees
the raw NULL and skips the row), never to rejected.
Extended tests:
TestBatchDataNotNullFillForIgnoreAdjustsEveryFillableTypeadds one kept-value/one-NULL pair per new column and pins the stored zero and
the per-cell 1048 warning;
TestImplicitFilledChildDefaultExprMirrorsRuntimeFillrequires mirrored, type-preserving constants for the four types.
Validation:
TestTypeSwitchFamiliesreproduced the CI failure on the parenthead (exit 1, the two switch findings) and passes after the change;
mo-cgo-test -count=1over./pkg/sql/colexec ./pkg/sql/colexec/insert ./pkg/sql/colexec/multi_update ./pkg/sql/colexec/preinsert ./pkg/sql/planall ok; gofmt/vet/lint clean on the changed packages.
Review fixes: BINARY padding and constant-NULL materialization (r17)
Addressing the mo-bot review of head
2afbf798— two P2 findings. Each wasreproduced first (focused UTs on the parent state, plus a rebuilt pre-fix
mo-servicefor the SQL witness), then fixed and re-run green; the new headis
a2bf1e6054.Finding 1 — INSERT IGNORE filled BINARY(n) with the empty payload.
setImplicitNotNullDefaulttreated BINARY like the variable-width stringfamily, so a NULL in
BINARY(n)stored 0 bytes while an ordinaryempty-string assignment right-pads 0x00 to the declared width (the
string→binary cast rule that
test_files/dtype/binary.resultpins). Theplanner mirror had the same blind spot.
pkg/sql/colexec/constraint_util.go): theT_binarycase nowwrites n zero bytes — the value an ordinary
''assignment stores — andkeeps the empty payload only when the width has no room, mirroring the
cast's
len < widthguard.VARBINARYstays variable-width/empty.pkg/sql/plan/bind_insert.go,implicitFilledChildDefaultExpr):the empty varbinary payload is evaluated through
makePlan2AssignmentCastExprto the column type — BINARY takes theordinary assignment cast (the strict-cast gate excludes it) — so the
IGNORE foreign-key filter evaluates the value that gets stored; a cast
that cannot be built degrades the mirror to unmirrored, never diverging.
2afbf798:TestBatchDataNotNullFillForIgnoreAdjustsEveryFillableTypefailed at the binary(2) slot (
expected: []byte{0x0, 0x0}, actual: []byte{});the pre-fix SQL witness stored
HEX(b)='' /LENGTH(b)=0 for theIGNORE-filled row while the ordinary
''assignment stored0000/2.r15_binsection stores the IGNORE-filled row and the ordinary''assignment row and pins parity —HEX(b)/LENGTH(b)=0000/2 forboth rows;
VARBINARY(4)keeps the empty payload (0).Finding 2 — LOAD IGNORE aborted on a NOT NULL column whose omitted default
folds to a constant NULL. The projected default arrives as a
NewConstNullbroadcast, which owns no backing storage (no data area at all), so the
fill's in-place setter hit
internal error: vector idx out of range: 0 > 0and killed the load instead of filling its rows.
pkg/sql/colexec/constraint_util.go):BatchDataNotNullFillForIgnoredetects a constant NULL broadcast and replaces it (via the new
constImplicitNotNullDefaultVec) with a constant carrying the implicitdefault, built through the same shared per-type rule as the in-place fill
so the two shapes can never diverge; the logical length is preserved, so
every row keeps its row, and one warning 1048 is published per adjusted
row. A NOT NULL column whose type has no implicit default keeps the
constraint violation rather than being silently corrupted.
pkg/sql/colexec/multi_update:fillMainInsertNotNullForIgnoreinstallsthe replacements back into the batch the write legs read, and the s3
writer delegate runs the fill before
SelectColumnstakes itsvector-pointer snapshot.
2afbf798:TestBatchDataNotNullFillForIgnoreReplacesConstNullBroadcastsand
TestCheckExternalNotNullIgnoreFillsConstNullVectorboth failed withthe internal error; green after the fix.
TestBatchDataNotNullFillForIgnoreConstNullWithoutDefaultKeepsViolation(no silent fill for types without an implicit default), and the
external-write IGNORE-gate test. The BVT
r15_ldsection drivesbigint NOT NULL default (abs(null))end to end throughload data inline ... ignore— rows fillu=0with one warning 1048 each.Validation on the new head: focused
-count=1package runs ofpkg/sql/colexec,.../insert,.../multi_update,.../preinsert(allok) andpkg/sql/plan(allok, no plan input changed after the greenrun);
gofmt -lover the changed files clean;go vetandgolangci-lint run(the repo--new-from-revboundary) over the changedpackages clean after fixing the two lint findings the change itself
introduced (gofmt composite-literal elision as the repo's golangci gofmt
formats it, and a prealloc in the new test); the
-raceselection over allfive packages green. The issue BVT suite was regenerated against the built
binary (pure insertion before the final statement, prior expectations
byte-identical) and screened in both
ignoreandnoignoremo-tester modeswith zero errors; the incidental
insert_ignore.sqlscreen shows the samecolumn-annotation-only mismatches (varchar width
-1vs10, data rowsidentical) it showed on the parent head before this change, while the
pushed CI runs green on the same expectations.
Review fixes: explicit cleanup ownership for external IGNORE fill replacements (r18)
Review
PRR_kwDOFEPiGM8AAAABWbzuFA(heada2bf1e60): the external(write-file) pipeline leaked one constant replacement per affected batch,
because the vector
constImplicitNotNullDefaultVecallocates is installedinto the child's borrowed batch — Projection overwrites every slot on its
next Call and frees only its executor-owned originals, external Insert owns
no buffer for the child's batch, and the synchronous writer releases nothing —
so the mpool's pointer registry retained each replacement's storage.
checkExternalNotNullnow snapshots the batch's vector pointers only whena NOT NULL slot holds a constant NULL broadcast (the one shape the fill
replaces; ordinary batches take no snapshot) and books every slot the fill
exchanged into
ctr.extFillOwned, each paired with the displacedchild-owned vector. Booking by pointer diff also covers the partial-fill
error path: the shared helper installs earlier slots before a later
unfillable column fails the statement, and those installs are booked the
same way.
insert_externalis the explicit cleanup owner: it drains the bookedreplacements on every path out of a batch — fill rejection, write
failure, success, and a panicking unwind — restoring each child's borrowed
slot before freeing the replacement's storage. The drain runs at the first
unclaimed moment after the synchronous writer consumed the batch and
before the child batch leaves the Call, so Reset and Free never carry an
outstanding entry.
a2bf1e60: driving the real Projection-to-external-Insertchain with six const-NULL batches made the mpool's registry-backed on-heap
counter grow one object per batch (7 after the second batch, 8 after the
third) and both failure-shaped calls leave +32 bytes recorded. Green on
the new head, and every driven pool closes with zero outstanding bytes.
TestExternalInsertOwnsConstFillReplacements(the actualmulti-batch lifecycle requested by the review, flat counters across six
batches with one warning 1048 per adjusted row),
TestExternalInsertReleasesFillOnWriteFailure(the replacement isreleased with the failed write; counters return to the pre-call value),
and
TestExternalInsertReleasesPartialFillOnViolation(a partiallyinstalled replacement before a geometry const NULL keeps its violation
without leaving the booked installation behind). The direct-level test
still pins that the batch slot holds the replacement right after
checkExternalNotNull— the written value contract is unchanged.-count=1run ofpkg/sql/colexec,.../insert,.../multi_update,.../preinsert(allok),gofmt -lover the three changed files clean,go vetandgolangci-lint run(repo--new-from-revboundary) clean, and the-raceselection over the five executor/plan packages green. No plan-sideinput or BVT expectation changed this round: the r16 plan UT and r17 BVT
receipts keep covering the SQL contract.
Review fixes: detach aliased flat destinations from the external IGNORE fill (r19)
The third review round (
PRR_kwDOFEPiGM8AAAABWdfqIQ) flagged the one remaining external LOAD path where the IGNORE fill could still corrupt values:LOAD DATA ... IGNOREinto a writable external table with(a BIGINT, b BIGINT NOT NULL DEFAULT (a))and a file supplying onlyawith mixed rows(1, NULL, 2)projectedb's stagedDEFAULT (a)as a raw column reference —coalesceGeneratedColIgnoreFillRefsleaves a nullable reference un-rewritten, the column executor hands the projection the very vector holdinga, and the external plan runs no PRE_INSERT whose repeated-vector separation would split the alias. The flat leg of the fill then rewrotebin place, also settinga's NULL cell to the implicit default and clearing the null bitmap, so the writer emitted(0,0)instead of(NULL,0).[colref a, colref b]over(1, NULL, 2)made the writer observe(1,1) (0,0) (2,2)(ut-r19-red-alias.log, exit 1 on the pre-fix head; the component-level sibling oracle fails the same way).checkExternalNotNullnow detaches aliased flat fill destinations before the fill: a vector shared by another slot that holds a live NULL and sits in a NOT NULL destination gets operator-owned independent storage (the sameNewVec+UnionBatchdetach PreInsert's repeated-vector separation performs on the internal path), booked through the existingctr.extFillOwnedownership soinsert_externalreturns the child's borrowed slot and frees the copy on every exit path of a batch — fill rejection, write failure, success, panic unwind. Vectors with no NULL cell keep the single in-place fill (the fill only rewrites NULL cells), constant broadcasts keep the existing replacement mechanism, no-destination batches skip the scan, and non-external plans keep the PRE_INSERT separation unchanged.TestCheckExternalNotNullIgnoreDetachesAliasedFlatDestinationpins the component contract (sibling's live NULL kept, destination filled in detached storage, booked pair released with the slot returned, outstanding flat),TestExternalInsertIgnoreFillKeepsAliasedNullableSiblingdrives two batches through the actual Projection-to-writer lifecycle — the writer receivesa = 1, NULL, 2untouched whileb = 1, 0, 2carries the implicit default with one warning per batch, the child-owned vector survives unmodified, and the mpool's registry-backed counters stay flat across batches — andTestCheckExternalNotNullIgnoreDetachesEachAliasedDestinationpins the two-destination-tied-to-one-source counterexample (each dependent NOT NULL column gets its own detach and its own adjusted-row warning instead of a shared single copy swallowing the second column's report). All three fail on the parent's production code and pass on the fix.-count=1run ofpkg/sql/colexec,.../insert,.../multi_update,.../preinsertallok,gofmt -lclean over the three changed files,go vetandgolangci-lint runclean, and the-raceselection over the five executor/plan packages green. No plan-side or BVT expectation changed this round.