Repository navigation
fix(sql): validate primary keys for ordinary LOAD DATA - #30421
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
…f8154bac63436073c5df1acc81c9b460da7e0be
Expect duplicate LOAD rejection and rollback, then construct the intentional corrupt fixture with an explicitly exempt INSERT. Preserve the existing PK/unique rejection checks and verify ALTER retains all fixture rows.
|
mo-bot review · Commit: Review completed. Read the assessment. |
…f8154bac63436073c5df1acc81c9b460da7e0be
Ordinary LOAD now validates declared primary keys after main PR matrixorigin#30421. Update the CHECK-policy test to require one FAIL dedup on the primary key for ordinary LOAD, while retaining the bypass for LOAD IGNORE and the positive INSERT IGNORE arbitration control. Preserve all CHECK placement, barrier and exactly-once assertions across the ten existing cases. Validation: focused matrixone_test coverage cases, complete planner package with vet=all, incremental lint, formatting and diff checks passed.
…0637) Join-spill appends can make XFS speculatively allocate beyond EOF. Disk admission tracks logical payload bytes, so automatic capacity refresh can mistake that extra allocation for outside disk consumption, shrink the active cap to current usage, and reject the next write. Preextend the file to the admitted append end before writing, through a shared helper used by both initial hashbuild spill and probe/repartition bucket writes. Keep disk admission before extension and retain file/reservation ownership through terminal cleanup on errors. Budget policy, primary-key validation, and spill record format remain unchanged. ### Validation - Owning packages: `spillio`, `hashbuild`, and `spillutil` passed through `mo-cgo-test`. - Current-main SQL: `TestLoadRejectsDuplicatePrimaryKeys` and `TestHashBuildSharedBudgetRecoverySQL` passed. - Added roundtrip/error, rejected-growth preservation, and cleanup tests. `TestWritePreextendedXFSAllocation` ran and passed on real Linux/XFS; it explicitly skips other filesystems. - Formatting, focused `go vet`, incremental `golangci-lint`, and diff checks passed. - [Real-XFS reproduction and evidence](#30544 (comment)): 400,000 unique composite-key rows, automatic spill budgeting, private XFS LOCAL storage, and real concurrent SQL capacity refresh. With identical input/settings, original code failed with `requested=117712, used=115348584, limit=115348584` and rolled back; patched code imported all rows with correct checksums and complete disk/FD/file cleanup. Patched peak logical/allocated bytes were 176,386,048 / 176,664,576. The causal SQL before/after used issue revision `65bcea5d` to retain its original full-row LOAD plan. The affected production writer/native sources are identical at PR base `309f618995`; current-main public regressions were tested separately because #30527 changed LOAD planning. This does not claim a replay of the original TPCH1000 run or an adjacent-commit bisect of #30421. ### Performance A bounded 64 KiB append microbenchmark measured median 29.35 µs before versus 32.87 µs after (~12% per-append overhead for the extra operations). Two complete SQL comparisons with enough disk space for both versions measured 1.593/1.418 s before versus 1.304/1.460 s after. No SQL slowdown was observed at this scale; large-scale throughput remains unmeasured. Approved by: @XuPeng-SH, @aptend, @aunjgr
) Restore authorized first-line sampling for modern LOAD, and add an explicit session policy for the CN primary-key validation enabled by #30421. The default is intentionally OFF to recover the historical bulk-load behavior. Disabling validation changes correctness semantics; it is not a speedup under equivalent checking. 1. Bind the statement identity with `process.SQLFileAccessContext` before sampling. Previously the unbound context failed file admission and silently fell back to declared column widths. A BLOB column could make millions of short rows look like a small TP query and reduce reader/CN parallelism. Admission, the sample bound, fallback, and scheduling rules remain unchanged. 2. Add dynamic SESSION BOOL `mo_pk_check_by_cn`, default OFF. Both modern and legacy LOAD planners use the session value. OFF omits ordinary LOAD's CN primary-key hash validation; ON retains its current eligible input/target duplicate checks, error 1062, and statement rollback. INSERT checks, index maintenance, foreign keys, and `mo_pk_check_by_dn` remain independently governed. Existing IGNORE/REPLACE and other validation exemptions remain. 3. Reuse session plan invalidation after a changed SET. Other sessions and equivalent/invalid SETs preserve their state. Existing correctness tests explicitly enable the setting instead of changing their duplicate-error assertions. 4. Preserve the owning connection's current LOAD policy through frontend background sessions for CALL and nested CALL. System-variable reads bypass identically named procedure locals, preserving the session/global namespace and existing ordinary local/user-variable lookup. Use the same connection for SET and LOAD: ```sql SELECT @@session.mo_pk_check_by_cn; -- 0 on a new connection SET SESSION mo_pk_check_by_cn = ON; -- enable CN primary-key validation for LOAD SET SESSION mo_pk_check_by_cn = OFF; -- bypass that validation ``` OFF can admit duplicate input primary keys; it does not remove duplicate rows. The independent TN switch can still reject conflicts, but historical testing showed TN ON alone did not detect duplicates within one input file. The new switch is session-only, does not apply to INSERT, and is not an all-unique-index checking switch. See the [versioned design](https://github.com/iamlinjunhong/matrixone/blob/ce6352a010492ebbc8134e014652d40bc2eacfe0/docs/design/load-cn-primary-key-check.md). Validation: - Procedure-policy follow-up `ce6352a010`: both new regressions fail before their respective fixes. Final full frontend package passes (15.357 s); focused background/namespace tests pass (1.142 s); the complete authenticated two-CN LOAD fixture passes (6.870 s). It covers ON/OFF/ON, direct/CALL/nested CALL input and target conflicts, 1062/rollback/recovery, and nil/0/1 same-name procedure locals. Tests use `-count=1 -vet=all`; incremental four-package lint reports 0 issues. Independent gpt-6-astra medium final review passes. - Full owning packages pass on PR base `63a964a82f`: planner 17.387 s, frontend 14.024 s, compiler 10.249 s. Focused cases cover OFF/ON typed plan shape, both planners, resolver errors/defaults, session cache invalidation, and internal compiler delegation. Scoped vet, incremental lint, formatting and diff checks pass. - Authenticated two-CN `TestLoadRejectsDuplicatePrimaryKeys` passes (6.219 s), covering session isolation, OFF/ON/OFF on identical LOAD text, invalid/global SET, prepared INSERT across SETs, and existing duplicate/rollback, composite-key, index, FK, parallel-file and cross-batch cases. PREPARE LOAD is not admitted by the existing parser; this change does not extend it. - Active `ddl/alter.sql` passes normal mo-tester comparison twice: 314 successful statements, 42 existing skips, zero failures each; teardown verified. Five other adjusted duplicate-LOAD BVT blocks retain their existing #3433 skips and were not executed. Their original error oracles remain intact. - Sampling regression checks sampled width/cardinality, header handling and denied file access; it fails without the context fix. Prior unchanged fileservice admission/provider/cancellation checks remain valid. Against the original three COS schemas/objects, the sampling correction restores MULTICN plans and baseline sampled statistics; this is plan evidence, not completed 100M throughput measurement. - Controlled Linux diagnostic build `2196656528` plus the same sampling and switch production patches, 16 CPU / 64 GiB, one identical 2M-row 857,722,330-byte file: **PK-only OFF 5.19 s, ON 9.73 s**, prior-good `b24d1b3115` 5.16 s. Both return 2M rows/distinct keys and key sum 2,000,001,000,000. OFF has six data writers and no hash-build/dedup operators; ON has one data writer and 16 hash-build/dedup operators. These are single bounded runs with different validation semantics, not statistical or original TKE throughput claims. ON input and existing-table conflicts return 1062 with rollback for both parallel options. Original three-CN TKE 100M throughput for the new head remains pending in [run 39540728649](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/39540728649), dispatched for exact commit `579e0a1fad124ac4cafd77a88b018919d80dd21f`. The [earlier workflow run](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/39535688608) targets sampling-only commit `c38e3715539749aee13f3175d4900593b53f6bb8` and cannot validate this switch. Design and integrated final review use gpt-6-astra with medium reasoning. Approved by: @XuPeng-SH, @fengttt
|
Opened #30821 to track the sustained distributed TPCH query-stage regression and its acceptance separately from #30520 (TPCC) and #30544 (LOAD spill). Evidence linking this PR:
#30527 removes full-row hash output from the write branch, but a later-Main diagnostic still observes reader-range mixing through the shared Sink when CN PK checking is enabled. #30697 defaults that checking to OFF and restores sampling context; it is absent from the latest affected nightly and requires fresh-load Q5/Q3 acceptance, not query-only testing against old objects. Existing TPCC and LOAD-only validation does not establish TPCH query recovery. This is not a request to blindly revert the correctness check. #30821 explicitly distinguishes OFF-policy mitigation from an equivalent-semantics ON-path fix, and records the remaining evidence needed before closing the TPCH regression. |
What type of PR is this?
Which issue(s) this PR fixes:
What this PR does / why we need it:
Plain LOAD DATA currently skips primary-key conflict checks. Importing
1,aand1,bcan succeed and store two rows with the same declared primary key, while an equivalent INSERT returns error 1062.Enable existing primary-key validation for ordinary LOAD into real-PK tables. The modern planner uses the existing FAIL dedup join; the legacy foreign-key fallback uses existing fuzzy validation for input and target keys. Keep LOAD's table locks and bulk-write planning. Duplicate input or existing-row conflicts return 1062 and roll back the LOAD. Composite keys retain tuple identity.
This change does not implement LOAD IGNORE/REPLACE conflict resolution or unique-key conflict handling tracked separately in #25470. Existing explicit optimizer/internal exemptions remain. Please have the reporter verify #30411 after merge.
Validation on macOS arm64 / Go 1.27.1:
pkg/sql/planunit-test package, including typed plan tests for modes, composite keys, index maintenance, exemptions, and both legacy CN check settings.TestLoadRejectsDuplicatePrimaryKeysthrough the existing embedded MySQL fixture: input duplicates, existing-row conflicts, rollback/reuse, composite tuples, foreign-key fallback, whole-file fanout, cross-batch input over the bulk-write threshold with both parallel option settings, and transaction visibility.go vet, incremental golangci-lint, formatting and diff checks.Primary-key validation adds hashing/probing work. A bounded local diagnostic (10,000 rows, 2.6 MB CSV, three trials per case) changed median LOAD time from 26.4 to 29.4 ms on an empty target and 23.0 to 26.1 ms on a prepopulated target. This is small-data evidence, not a large-scale throughput or peak-memory benchmark. The local-file tests do not establish remote-CN distribution or byte-offset splitting above the 128 MiB parallel-read threshold. No persistence/wire format changes. Upstream CI is pending.