Skip to content

fix: report INSERT IGNORE constraint warnings - #28459

Merged
XuPeng-SH merged 13 commits into
mainfrom
codex/issue-28254-ignore-warnings-20260909
Sep 11, 2026
Merged

XuPeng-SH merged 13 commits into
mainfrom
codex/issue-28254-ignore-warnings-20260909

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 9, 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

Fixes #28254

What this PR does / why we need it

INSERT IGNORE and UPDATE IGNORE now report one constraint warning for each
row rejected by the existing primary-key, unique-key, or CHECK arbitration
path. The data decision is unchanged. The exact warning count is independent
from the bounded diagnostic records retained for SHOW WARNINGS.

The implementation covers hash-build deduplication, dedup-join probing,
ordered multi-key PreInsertUnique, and CHECK assertion filters. Composite
keys use logical names and type metadata instead of exposing serialized index
bytes. A rejected row whose key cannot be rendered remains rejected and still
contributes to the count; diagnostic rendering is never allowed to change the
IGNORE data path.

Design and implementation

  • Bind diagnostics to one Compile.Run execution attempt. Local operators,
    nested execution, and remote terminal callbacks write to that attempt;
    failed, cancelled, superseded, or panicking attempts are discarded before
    publication.
  • Preserve exact counts with saturating uint64 arithmetic. Retained records
    are bounded to 64 entries, each message to 4 KiB, and the aggregate message
    budget to 256 KiB. Count-only sinks receive the complete count without
    fabricated records; batch and legacy sinks clamp records to the batch total.
  • Capture the attempt sink in remote senders so a late terminal callback cannot
    publish into a later retry. Collector close is linearized with append.
  • Keep CHECK assertion evaluation non-foldable when its per-row warning side
    effect is required. Invalid rows are filtered and valid rows continue.
  • Lazily build and reuse immutable ordered-key metadata only when a retained
    duplicate diagnostic needs it. Malformed metadata, tuple offsets, or key
    rendering are diagnostic-only failures.
  • Reserve MORPC v63 for IGNORE-aware CHECK filtering. MORPC v62 remains the
    existing VARCHAR OCT capability; during rolling upgrades, CHECK filters stay
    coordinator-local until every participating CN advertises v63. Placement
    and serialization gates both recheck the capability.

Unhappy paths and compatibility

  • Retry/cancel/late-terminal paths publish no diagnostics from an unsuccessful
    attempt.
  • Nil or incomplete vectors and legacy plans cannot panic the IGNORE data path.
  • Counts saturate instead of wrapping. Records and message bytes are bounded,
    UTF-8-safe, owned, and reset at statement/attempt boundaries.
  • Ordinary CHECK enforcement and remote source scans keep their existing
    semantics. No goroutine, timer, retry loop, RPC field, or unbounded
    per-row state is introduced.

Test plan

Validated from a clean worktree rebased onto origin/main commit
44b7f90ee1695831663c55288a537c03c15c00e0:

  • pkg/vm/process: warning count/record routing, count-only sink, batch
    clamping, UTF-8 ownership, byte budget; focused -race passed.
  • pkg/sql/compile: protocol v63/v62 compatibility, collector boundaries,
    warning-attempt retry/concurrency; focused -race passed.
  • pkg/frontend: session count saturation, byte/record bounds, and warning
    lifecycle; focused -race passed.
  • pkg/sql/colexec/aggexec: GROUP_CONCAT count-only and retry publication;
    focused tests passed.
  • Full focused -race suites for preinsertunique, dedupjoin, and
    hashbuild passed, together with their warning/IGNORE tests.
  • git diff --check passed after the final review.

The checked-in distributed BVT and a fresh two-version rolling-upgrade cluster
were not rerun for this final bounded-sink-only delta; the deterministic unit
and protocol tests above are the claimed evidence. CI was not awaited.

Review status

The complete final diff was reviewed with GPT-6 medium after implementation.
The review found and the implementation closed the batch-total clamp and
collector cumulative-limit edge cases. No remaining P0/P1/P2 correctness,
lifecycle, compatibility, or performance blocker was identified.

Final head: 566d6f0547e47127c4fb1601ceadebd8d0faac95.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Sep 9, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deep review of exact head 40ff1dc (base 91d7297), covering the 20-file change map: duplicate-key formatting and hash-build/probe/ordered-arbiter producers, CHECK planner/runtime behavior, bounded accumulator, session/remote sinks, and protobuf/deep-copy metadata propagation.

The count-versus-retained-record split is a sound design, and duplicate diagnostics are guarded by IGNORE semantics and successful producing calls. The ordinary multi-key arbiter records only the selected rejection. CHECK FILTER evaluates/shrinks sequentially, which avoids counting a row again in later CHECK filters. However, the CHECK warning side effect is missing two execution contracts: ownership of the retained message, and non-foldability for row-accurate counts. Both are P2 blockers described inline.

Validation/evidence: source-traced through constant-vector allocation, function executor folding/free, frontend diagnostic storage and remote collectors. Reviewed the focused UT/BVT additions and the author's package/race/BVT evidence; the reported BVT runner's post-run report-move failure is not treated as a clean end-to-end exit. No independent full MatrixOne SQL/UT run was executed for this review. Exact-head ALL CI 34311766283 was queued at the snapshot, with auxiliary PR CI in progress; the pending gate was explicitly waived and I did not poll. COMMENT only as requested.

// Keep the value false so the surrounding FILTER
// removes this row, while retaining one bounded
// warning record per ignored row.
warnings.Add(moerr.ER_CHECK_CONSTRAINT_VIOLATED, errMsg)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Own the CHECK message before retaining it as a warning

errMsg is obtained with QuickBytesToStr(value), which is an unsafe, zero-copy string view of the message argument vector. This new path stores that view in WarningAccumulator.Messages and then in the session/remote collector. Neither WarningAccumulator.Add/Flush, errInfo.pushStored, nor remoteWarningCollector.AppendWarningBatch clones the string. The source message is materialized as a constant vector; FunctionExpressionExecutor.Free frees its parameter executor and FixedVectorExpressionExecutor.Free releases that vector's data/area through mpool. The diagnostic intentionally survives this execution boundary for SHOW WARNINGS (or terminal remote serialization), so it now references released storage. Reuse/poisoning of that allocation corrupts the reported CHECK name/message.

Clone the message once before the first retained warning, or establish an owning-copy contract in the diagnostic sink. Add a lifetime regression that emits the warning, releases/poisons or overwrites the source vector storage, and only then reads the retained diagnostic. The current test reads the warning while its source vector is still alive, so it cannot detect this.

errMsg := functionUtil.QuickBytesToStr(value)
res := vector.MustFunctionResult[bool](result)
ignore := statementIgnore(proc)
var warnings process.WarningAccumulator

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Disable scalar folding for the new per-row warning side effect

The CHECK assertion overload still has volatile == false (its INTERNAL/STRICT class does not make CannotFold() true), but it now emits one warning per row. A legal counterexample is CREATE TABLE t(v INT, CONSTRAINT ck CHECK (FALSE)); INSERT IGNORE INTO t VALUES (1),(2),(3);: all three rows must be skipped and counted as three warnings. The assertion's arguments are constants; FunctionExpressionExecutor.doFold calls finishFolding with execLen=1 and subsequently broadcasts the cached result to the batch. Consequently the warning-producing loop runs once, not once for each rejected row. Planning-time folding can move this side effect even earlier; repeated/prepared evaluation must not reuse a warning-producing scalar result.

Mark the assertion overload non-foldable (or separate a pure predicate from an explicitly row-count-aware warning operator), preserving runtime batching. Add a result-level constant-false CHECK test that checks the total warning count for multiple rows, plus repeated prepared execution/empty-input coverage. The existing new test uses a nonconstant flag vector and calls the function directly, bypassing the expression-executor folding path.

@XuPeng-SH
XuPeng-SH force-pushed the codex/issue-28254-ignore-warnings-20260909 branch from 40ff1dc to fb92649 Compare September 9, 2026 05:21

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Force review conclusion: COMMENT (own PR; APPROVE/REQUEST_CHANGES are not allowed). Exact head: e68efc0

Confirmed blocker

P2 — Mixed-version execution can turn an INSERT IGNORE CHECK rejection into a statement error.

Location: pkg/sql/plan/build_constraint_util.go:204; the filter is attached in pkg/sql/compile/compile.go:5507 and serialized through pkg/sql/compile/remoterun.go:843.

Counterexample:

CREATE TABLE src(v INT);
INSERT INTO src VALUES (-1), (2);
CREATE TABLE dst(v INT, CONSTRAINT ck_pos CHECK(v > 0));
INSERT IGNORE INTO dst SELECT v FROM src;

During a rolling upgrade, if the coordinator/CN running this PR sends the new _check_constraint_assert plan to a CN still running the previous implementation, that receiver resolves the existing assertion function and returns NewConstraintViolation for -1 without IGNORE-aware handling. The statement fails instead of skipping -1 and inserting 2. The current protocol gate does not distinguish this capability.

Please add a capability boundary for IGNORE-aware CHECK execution, keep a compatible filtering path until all participating CNs support it, or evaluate the assertion on a compatible coordinator. Add a mixed-version regression with valid/invalid rows and ordinary non-IGNORE enforcement.

Prior findings

The prior three findings were verified fixed: borrowed CHECK warning bytes are now owned, constant folding no longer collapses per-row warnings, and failed retry diagnostics are staged/committed by attempt.

Test evidence / unverified risks

No mixed-version cluster reproduction was run. Additional gaps include real IGNORE DML with deterministic retry, 64-record diagnostic boundaries, composite/prefix keys, legacy/malformed metadata, performance, teardown/reuse, and upgrade/downgrade testing. The current CI run still had UT/coverage/SCA/BVT pending at inspection; pending checks were not treated as completed evidence.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed the mixed-version CHECK finding in 042226e. MORPC v59 gates IGNORE-aware CHECK execution: older/unknown capability keeps the filter on the coordinator, upgraded clusters retain distributed execution, and serialization rechecks capability. Ordinary CHECK behavior is preserved.

Validation: compile/defines owning packages passed; TestIgnoreCheck and TestCheckConstraintAssert both passed with -race -count=20; incremental SCA reported 0 issues. The PR body now records the tests, temporary mixed-version performance cost, and the limitation that no real two-binary cluster run was performed. No rebase or unrelated scheduler/CodeQL edits.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Force review of head 234a49b, against live main/merge-base 2a6fe7f. COMMENT only for this self-authored PR.

Conclusion: not ready for implementation sign-off. The current merge conflict is a delivery blocker, but it is not the only remaining gate.

[P1] Provide and separately approve a versioned design for the execution-warning lifecycle/protocol change.

The original missing-warning bug is a focused correctness issue; the current solution has grown beyond adding diagnostics at existing rejection sites. It introduces a shared BaseProcess warning-attempt state machine (Begin/Commit/Abort), changes Compile.Run retry publication, and adds generation-bound remote warning admission. It also introduces an IGNORE-aware CHECK capability boundary and coordinator placement/serialization fallback. These are changes to cross-owner lifecycle, retry/idempotency and mixed-version execution contracts. The handwritten production delta is 668 added/deleted lines excluding tests and generated protobuf output. Both the scope and lifecycle/protocol complexity trigger the current mo-dev/mo-self-review design-first gate.

The PR body provides useful design notes, but the current tree, body, issue #28254 and review/comment history do not identify an approved, exact versioned design revision covering this change. The warning-attempt discussion in the draft JSON_TABLE RFC is for issue #28036 and is neither an approved design nor a design linked to this implementation. Please record the ownership/publication/generation model, surviving-attempt versus transaction-commit semantics, nested/internal/remote execution boundaries, count/order/retention contract, mixed-version rollout/fallback, resource/hot-path budget and validation decisions in a versioned document; obtain a distinct design approval before implementation sign-off. This is a mandatory artifact/decision gate, not a request for optional supplementary tests.

Existing findings and delivery status:

  • The historical CHECK borrowed-message and constant-folding issues have corresponding owned-message/volatile fixes and focused regressions.
  • The previous retry-diagnostic finding has corresponding attempt staging and remote-generation changes; those changes are also why the lifecycle design must now be explicit.
  • The previous mixed-version CHECK finding has a coordinator fallback and serialization recheck. Current head reserves v62 but advertises only v59, so it intentionally does not enable the distributed CHECK fast path. The obsolete v59 statement in an earlier comment is superseded by the current body/code.
  • GitHub still reports CONFLICTING. Rebase/conflict resolution is required, especially with overlapping warning/protocol work; re-review the resulting semantic delta and affected evidence. A merge conflict alone is not evidence of a runtime defect.

Evidence/limits: inspected live issue/PR comments and all prior review findings, inventoried the complete 29-file change, and traced the newly introduced attempt/protocol boundaries sufficiently to establish the gate. git diff --check passed. The PR reports exact-head source-matched Linux/amd64 owning-package and focused race passes; earlier BVT evidence predates the latest compatibility changes. I did not run native tests, wait for CI, or claim a real mixed-version reproduction. Per the mandatory design-first workflow, the missing design stops full downstream implementation approval; this review does not certify all requested SQL/transaction/counterexample paths or assert a newly reproduced runtime bug. Head and base were rechecked unchanged before submission.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Re-review of head 94f88ef against live main/merge-base 269d59a. COMMENT only for this self-authored PR.

Conclusion: the previous design-gate blocker is resolved; no new concrete runtime blocker found. GitHub now reports MERGEABLE.

Design-first record: independently reviewed revision 1 of docs/design/INSERT_IGNORE_WARNING_DIAGNOSTICS.md at this exact head, blob 1c0e856aaf94bb31230e7ec00865209b59429352, and record design PASS before implementation sign-off. This closes my review at 234a49b. The new ownership model reuses main's common Compile.Run attempt collector instead of introducing a second BaseProcess generation state machine. Accepted boundaries: publication is successful Compile.Run, not transaction COMMIT; warning arbitration follows existing execution/constraint order rather than promising SQL input ordering across parallel producers; v62 CHECK execution remains disabled until a separate rollout advances the advertised capability.

Implementation findings/closure:

  • Local duplicate/CHECK producers follow GetWarningSink; nested execution retains the existing context/process handoff. Remote senders capture the destination before RPC and never rediscover a newer process/session sink at terminal delivery. Collector close linearizes against append, discards failed attempts and makes late callbacks inert. Retry compilation gets a fresh collector.
  • Hash-build, probe and ordered multi-key arbitration record their actual rejected rows without changing accepted-row/auto-increment decisions. The arbiter stops at its selected first conflict; CHECK barrier filtering removes rejected rows before subsequent checks. Ordinary non-IGNORE rejection stays an error.
  • CHECK messages own their bytes and the function is non-foldable, retaining the earlier fixes for lifetime and constant-false multi-row counts. The planner's coalesce-to-true preserves CHECK's NULL/unknown semantics.
  • Metadata is carried through additive protobuf fields and deepcopy; bounds/nil-type checks and recoverable tuple formatting keep malformed diagnostic rendering from reversing the normal IGNORE decision. Legacy metadata retains the best-effort fallback. The formatting refactor is shared with ordinary duplicate errors, without altering their rejection decision.
  • Each producer/collector retains at most 64 diagnostics while the count saturates separately. Formatting stops after each producer's retention capacity, not globally after the first 64 warnings across every batch. No per-row state is accumulated for the full statement, new worker or retry loop is introduced.
  • Reserved MORPC v62, coordinator placement and serialization recheck address the old CHECK mixed-version failure. Current latest remains v59; ordinary CHECK is unchanged. Old workers are not claimed to acquire the new duplicate-warning capability merely by receiving additive metadata.

Scope/evidence limits: PK/UK/CHECK diagnostics are the defined change; FK and NOT NULL/value-conversion behavior are not newly implemented here. Read the complete current change map and deltas since my prior review, existing findings, producer/sink/retry consumers, generated metadata paths and protocol tests. git diff --check passed. The author reports exact-head normal owning-package tests, focused race tests and full race passes for the three duplicate-producing operator packages. I did not independently rerun native/SQL suites or wait for CI.

Non-blocking evidence clarification: the two 34-check BVT runs predate the final sink-routing refactor. The added targeted sink/late-terminal tests cover that refactor, but this is not a fresh end-to-end retry or two-binary upgrade run. The design's validation paragraph also asks for public composite/64-record cases, whereas the checked-in BVT shows the simpler PK/UK/CHECK cases and the 64-record/bounds proof is in UT. Please keep that coverage distinction explicit (or align the validation record); I am not treating supplementary test preference alone as a blocker. Head/base were rechecked unchanged before submission.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Re-force-reviewed exact head 566d6f0 against main 44b7f90. COMMENT only for this self-authored PR.

Conclusion: no new concrete runtime blocker found. The previous design PASS remains valid after reviewing revision 2 of docs/design/INSERT_IGNORE_WARNING_DIAGNOSTICS.md (blob 8453e9e4cb2f5397fde971f060f407cd9917755e); I record design PASS for this revision as well. Its updated sink bounds and v63 rollout match the current implementation.

Key revalidation:

  • Batch/legacy/count-only routing now preserves the complete count without subtracting records a count-only sink never receives. Record slices are clamped to the declared batch total; collector retention is cumulative, not reset per append. Counts saturate independently of the 64-record, 4-KiB/message and 256-KiB retained-message limits.
  • Collector append/close share the mutex. Failed/retried attempts discard, successful attempts transfer once, and remote senders retain the initiating sink rather than finding a later retry's sink. GROUP_CONCAT and nested-session count routing use the same optional sink contracts.
  • PK/UK/hash-build/ordered multi-key producers still report their existing arbitration decision, with diagnostic-only formatting failure. CHECK remains non-foldable and filters rejected rows before subsequent checks; retained message bytes are owned. No new accepted-row or auto-increment decision is added by the warning code.
  • MORPC v63 is now uniquely assigned and advertised for IGNORE-aware CHECK; v62 retains VARCHAR OCT. Coordinator fallback and serialization recheck guard older cluster capability. Additive key metadata/deepcopy preserve legacy-plan fallback; this does not claim old workers emit the newly added duplicate diagnostics.
  • Public BVT now includes composite-key rendering and the 64-record boundary, addressing the earlier coverage-description mismatch. Its warning_limit case checks retained records and surviving data; exact totals beyond retention are established by UT, not that SQL case.

Scope remains PK/UK/CHECK warnings for existing IGNORE rejection paths. FK, NOT NULL and conversion behavior are not newly implemented by this PR. Publication remains successful Compile.Run, not transaction COMMIT; ordering follows existing arbitration/producer arrival, not a promised global input-row order.

Evidence/limits: reviewed the current producer/planner/protocol/sink change map, revision-2 design, prior findings and sink delta from 94f88ef, generated-field schema/deepcopy, and focused test/BVT oracles. Author-reported owning-package and focused/full operator race passes were considered as reported; no new native tests, distributed BVT or two-binary rolling-upgrade run was performed by this review. The final bounded-sink delta's BVT/upgrade evidence limitation is explicitly documented and is not by itself a blocker. CI was not awaited, no repository files were changed, and head/base were rechecked before posting.

This branch was previously deployed

1 inactive deployment
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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Compatibility]: IGNORE skips constraint violations without populating MySQL warnings

3 participants