Skip to content

fix: make INSERT IGNORE tolerate NOT NULL violations - #32299

Merged
mergify[bot] merged 8 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-30906-main-cfb4a77c
Nov 6, 2026
Merged

mergify[bot] merged 8 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-30906-main-cfb4a77c

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Related to #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 21d67b276d67215368a7f454d3b7064fbb706919 \
  ./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):

Base update (upstream main merge, 2026-11-06)

Main advanced past the PR base, and Mergify's Auto update branch rule
could not resolve the conflicts in pkg/sql/plan/bind_insert.go
(merge state DIRTY). The branch head now carries a manual merge of
origin/main (2746f81c36) that keeps this PR's behavior and the new
upstream contracts side by side:

  • generated-column loop in bind_insert.go: keep the IGNORE fill
    coalescing of dependent-row references, then apply upstream's
    RequireMySQLConditionalBooleanConsumption gate on the final
    expression, so native-mode statements keep failing closed;
  • both value-scan default sites: keep the IGNORE fill coalescing and
    take upstream's extended forceCastExpr2 signature so cast errors
    carry the column name;
  • pkg/sql/colexec/constraint_util.go: the NULL-PK row filter adopts
    upstream'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-test wraps go test, counts fresh with -count=1):

./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=40m \
  ./pkg/sql/colexec ./pkg/sql/colexec/insert \
  ./pkg/sql/colexec/multi_update ./pkg/sql/colexec/preinsert        # all ok
./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=40m \
  ./pkg/sql/plan                                                    # ok 98.9s
gofmt -l <changed .go files>                      # empty
go vet -mod=readonly ./pkg/sql/plan ./pkg/sql/colexec \
  ./pkg/sql/colexec/preinsert ./pkg/sql/colexec/insert \
  ./pkg/sql/colexec/multi_update                   # clean
golangci-lint run -c .golangci.yml \
  --new-from-rev 21d67b276d67215368a7f454d3b7064fbb706919 \
  ./pkg/sql/plan/... ./pkg/sql/colexec/...          # 0 issues
./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -race -timeout=30m \
  -run 'InsertIgnore|MainTableIgnore|IgnoreFill|NotNull|Alias|LoadIgnore|ImplicitFilled' \
  ./pkg/sql/colexec ./pkg/sql/colexec/insert ./pkg/sql/colexec/multi_update \
  ./pkg/sql/colexec/preinsert ./pkg/sql/plan      # all ok under race

Those runs include the fresh upstream tests in the merged packages
(pre-insert PK-history retry, conditional-boolean consumption gates,
forceCastExpr2 cast-error naming), confirming the interactions are
clean in both directions. The branch is current with main again; the
remote 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/x86 job failed TestTypeSwitchFamilies
(pkg/container/types): the two types.T switches this PR adds listed only
T_float32/T_float64, which names a part of the float family without
covering the low-precision subfamily (T_bf16, T_float16, T_float8,
T_float4) — the repository's G-TYPESWITCH gate requires every member, and
the omission was not intended. Both switches now cover the whole family:

  • pkg/sql/colexec/constraint_util.go (setImplicitNotNullDefault): a
    bf16/float16/float8/float4 cell now fills all-zero bits (+0, code
    0 in every one of these formats — the exact zero CanonicalLowPrecFloat
    pins), so under INSERT IGNORE a NULL in a NOT NULL low-precision-float
    column stores 0 with warning 1048, like every other numeric.
  • pkg/sql/plan/bind_insert.go (implicitFilledChildDefaultExpr): the same
    fill is mirrored as float32(0) assignment-cast to the column type (the
    decimal 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: TestBatchDataNotNullFillForIgnoreAdjustsEveryFillableType
adds one kept-value/one-NULL pair per new column and pins the stored zero and
the per-cell 1048 warning; TestImplicitFilledChildDefaultExprMirrorsRuntimeFill
requires mirrored, type-preserving constants for the four types.

Validation: TestTypeSwitchFamilies reproduced the CI failure on the parent
head (exit 1, the two switch findings) and passes after the change;
mo-cgo-test -count=1 over ./pkg/sql/colexec ./pkg/sql/colexec/insert ./pkg/sql/colexec/multi_update ./pkg/sql/colexec/preinsert ./pkg/sql/plan
all 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 was
reproduced first (focused UTs on the parent state, plus a rebuilt pre-fix
mo-service for the SQL witness), then fixed and re-run green; the new head
is a2bf1e6054.

Finding 1 — INSERT IGNORE filled BINARY(n) with the empty payload.
setImplicitNotNullDefault treated BINARY like the variable-width string
family, so a NULL in BINARY(n) stored 0 bytes while an ordinary
empty-string assignment right-pads 0x00 to the declared width (the
string→binary cast rule that test_files/dtype/binary.result pins). The
planner mirror had the same blind spot.

  • Runtime (pkg/sql/colexec/constraint_util.go): the T_binary case now
    writes n zero bytes — the value an ordinary '' assignment stores — and
    keeps the empty payload only when the width has no room, mirroring the
    cast's len < width guard. VARBINARY stays variable-width/empty.
  • Planner (pkg/sql/plan/bind_insert.go, implicitFilledChildDefaultExpr):
    the empty varbinary payload is evaluated through
    makePlan2AssignmentCastExpr to the column type — BINARY takes the
    ordinary 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.
  • Reproduction on 2afbf798: TestBatchDataNotNullFillForIgnoreAdjustsEveryFillableType
    failed at the binary(2) slot (expected: []byte{0x0, 0x0}, actual: []byte{});
    the pre-fix SQL witness stored HEX(b)='' / LENGTH(b)=0 for the
    IGNORE-filled row while the ordinary '' assignment stored 0000/2.
  • BVT: the r15_bin section stores the IGNORE-filled row and the ordinary
    '' assignment row and pins parity — HEX(b)/LENGTH(b) = 0000/2 for
    both 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 NewConstNull
broadcast, 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 > 0
and killed the load instead of filling its rows.

  • Fix (pkg/sql/colexec/constraint_util.go): BatchDataNotNullFillForIgnore
    detects a constant NULL broadcast and replaces it (via the new
    constImplicitNotNullDefaultVec) with a constant carrying the implicit
    default, 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: fillMainInsertNotNullForIgnore installs
    the replacements back into the batch the write legs read, and the s3
    writer delegate runs the fill before SelectColumns takes its
    vector-pointer snapshot.
  • Reproduction on 2afbf798: TestBatchDataNotNullFillForIgnoreReplacesConstNullBroadcasts
    and TestCheckExternalNotNullIgnoreFillsConstNullVector both failed with
    the internal error; green after the fix.
  • New coverage: the two const-NULL UTs above,
    TestBatchDataNotNullFillForIgnoreConstNullWithoutDefaultKeepsViolation
    (no silent fill for types without an implicit default), and the
    external-write IGNORE-gate test. The BVT r15_ld section drives
    bigint NOT NULL default (abs(null)) end to end through
    load data inline ... ignore — rows fill u=0 with one warning 1048 each.

Validation on the new head: focused -count=1 package runs of
pkg/sql/colexec, .../insert, .../multi_update, .../preinsert (all
ok) and pkg/sql/plan (all ok, no plan input changed after the green
run); gofmt -l over the changed files clean; go vet and
golangci-lint run (the repo --new-from-rev boundary) over the changed
packages 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 -race selection over all
five 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 ignore and noignore mo-tester modes
with zero errors; the incidental insert_ignore.sql screen shows the same
column-annotation-only mismatches (varchar width -1 vs 10, data rows
identical) 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 (head a2bf1e60): the external
(write-file) pipeline leaked one constant replacement per affected batch,
because the vector constImplicitNotNullDefaultVec allocates is installed
into 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.

  • checkExternalNotNull now snapshots the batch's vector pointers only when
    a 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 displaced
    child-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_external is the explicit cleanup owner: it drains the booked
    replacements 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.
  • Reproduction on a2bf1e60: driving the real Projection-to-external-Insert
    chain 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.
  • New coverage: TestExternalInsertOwnsConstFillReplacements (the actual
    multi-batch lifecycle requested by the review, flat counters across six
    batches with one warning 1048 per adjusted row),
    TestExternalInsertReleasesFillOnWriteFailure (the replacement is
    released with the failed write; counters return to the pre-call value),
    and TestExternalInsertReleasesPartialFillOnViolation (a partially
    installed 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.
  • Validation on the new head: the focused batched -count=1 run of
    pkg/sql/colexec, .../insert, .../multi_update, .../preinsert (all
    ok), gofmt -l over the three changed files clean, go vet and
    golangci-lint run (repo --new-from-rev boundary) clean, and the
    -race selection over the five executor/plan packages green. No plan-side
    input 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 ... IGNORE into a writable external table with (a BIGINT, b BIGINT NOT NULL DEFAULT (a)) and a file supplying only a with mixed rows (1, NULL, 2) projected b's staged DEFAULT (a) as a raw column reference — coalesceGeneratedColIgnoreFillRefs leaves a nullable reference un-rewritten, the column executor hands the projection the very vector holding a, and the external plan runs no PRE_INSERT whose repeated-vector separation would split the alias. The flat leg of the fill then rewrote b in place, also setting a's NULL cell to the implicit default and clearing the null bitmap, so the writer emitted (0,0) instead of (NULL,0).

  • Reproduced before fixing: driving the real Projection chain with [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).
  • checkExternalNotNull now 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 same NewVec + UnionBatch detach PreInsert's repeated-vector separation performs on the internal path), booked through the existing ctr.extFillOwned ownership so insert_external returns 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.
  • New coverage: TestCheckExternalNotNullIgnoreDetachesAliasedFlatDestination pins the component contract (sibling's live NULL kept, destination filled in detached storage, booked pair released with the slot returned, outstanding flat), TestExternalInsertIgnoreFillKeepsAliasedNullableSibling drives two batches through the actual Projection-to-writer lifecycle — the writer receives a = 1, NULL, 2 untouched while b = 1, 0, 2 carries 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 — and TestCheckExternalNotNullIgnoreDetachesEachAliasedDestination pins 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.
  • Validation on the new head: RED→GREEN receipts retained, the batched -count=1 run of pkg/sql/colexec, .../insert, .../multi_update, .../preinsert all ok, gofmt -l clean over the three changed files, go vet and golangci-lint run clean, and the -race selection over the five executor/plan packages green. No plan-side or BVT expectation changed this round.

## 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.
@XuPeng-SH

XuPeng-SH commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: d58f4f5e311a35d18302796993b47dbe43d15306

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Review disposition — PRR_kwDOFEPiGM8AAAABWdfqIQ (aliased flat vector corrupted by the external IGNORE fill): fixed.

Verified the P2 exactly as traced and reproduced it before touching the code:

  • RED (pre-fix, head d58f4f5e31): driving the real Projection-to-external-Insert chain with the review's shape — ProjectList = [colref pos0 (a), colref pos0 (b DEFAULT (a))], a BIGINT nullable, b BIGINT NOT NULL, supply (1, NULL, 2) — the writer observed (1,1) (0,0) (2,2) instead of (1,1) (NULL,0) (2,2): bind_insert.go's coalesceGeneratedColIgnoreFillRefs leaves the nullable a reference raw, the column executor hands b the very vector holding a, and the flat leg of BatchDataNotNullFillForIgnore fills b in place, so a's NULL cell was overwritten with the implicit default and its null bitmap cleared. Reproduction receipt: ut-r19-red-alias.log (exit 1, both the component-level sibling oracle and the writer-capture oracle fail with the review's mechanism).

Fix (commit 20b8f908f5): checkExternalNotNull now detaches every aliased flat fill destination before the fill runs (detachAliasedFillDestinations in pkg/sql/colexec/insert/insert.go): a vector shared by two slots that actually holds a NULL and sits in a NOT NULL destination gets operator-owned independent storage (NewVec + UnionBatch, the same detach PreInsert's repeated-vector separation uses on the internal path), and each detachment is booked through the existing ctr.extFillOwned lifecycle, so insert_external still returns the child's borrowed slot and releases the copy on every path out of the Call — fill rejection, write failure, success and panic unwind alike. Vectors without NULLs keep the single in-place fill (the fill only rewrites NULL cells), constants keep the existing replacement mechanism (they own no shared storage to corrupt), and non-external plans keep Detaching in PRE_INSERT as before.

New coverage (both RED on d58f4f5e31, GREEN on the new head):

  • TestCheckExternalNotNullIgnoreDetachesAliasedFlatDestination (component): the shared vector keeps its live NULL, the destination's slot runs in detached storage, ctr.extFillOwned holds exactly the booked pair, the release hands the borrowed slot back, and the pool's outstanding returns to the pre-call level.
  • TestExternalInsertIgnoreFillKeepsAliasedNullableSibling (operator): the writer receives a = 1, NULL, 2 untouched with b = 1, 0, 2 carrying the implicit default and one warning per batch, the child-owned supply vector still owns its NULL row after the statement, and the registry-backed counters stay flat across batches — no detach copy outlives its batch. Pools close with zero outstanding bytes.

Validation on the new head: RED→GREEN receipts retained (ut-r19-red-alias.log exit 1 → ut-r19-green-alias.log exit 0), the batched -count=1 run of pkg/sql/colexec, .../insert, .../multi_update, .../preinsert all ok, gofmt -l clean over the three changed files, go vet and golangci-lint run (repo --new-from-rev boundary) clean, and the -race selection over the five executor/plan packages green. No plan-side input changed this round.

Re-requesting review.

@XuPeng-SH

XuPeng-SH commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 20b8f908f522c7e5a793fb50e31d8543190a48fa

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 647eaf9 at 21:53 UTC

1 h 38 min in the queue, 1 h 6 min of it CI.

So far

3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify mergify Bot added the queued label Nov 6, 2026

This branch was previously deployed

1 inactive deployment
ci — 53237d88 Deployed Nov 6, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants