Skip to content

[Bug]: LOAD DATA must enforce table constraints and honor IGNORE row semantics #30500

Open

Description

@iamlinjunhong

Additional consolidated scope

LOAD DATA must not bypass foreign-key integrity when it materializes stored generated columns. The new report follows a separate generated-column projection path from unique-key arbitration and IGNORE row handling, but all three expose violations of the same constraint contract: a successful load must not commit rows whose declared constraints are bypassed.

Additional acceptance criteria

  • When a stored generated child-FK column is omitted from the LOAD input list, recompute it from its base columns before validating the foreign key; do not persist NULL as a way around the check.
  • Test valid and invalid generated FK values, plain strict loads, and IGNORE row behavior independently from unique-key and mixed-row IGNORE cases.

Additional reports

  • #28054 — original report and discussion remain on that issue.

Additional consolidated scope

Track constraint arbitration during bulk load: strict LOAD must not persist unique-key conflicts, while IGNORE must skip only invalid rows and retain valid rows. Related reports remain separate reproductions where they exercise distinct paths. Closing a source issue records tracking consolidation only; no fix is claimed.

Additional acceptance criteria

  • Without IGNORE, server-side and LOCAL LOAD DATA reject duplicate unique-key values within the file or against existing rows, matching ordinary INSERT constraint enforcement.
  • With IGNORE, foreign-key-invalid rows are skipped while valid rows are committed; without IGNORE the invalid load remains atomic and errors.
  • Verify affected-row counts and warnings, and keep value conversion/default semantics tracked separately in [Bug]: LOAD DATA must apply mode-aware conversion and missing/empty-field semantics consistently #30499.

Additional reports

  • #30715 — original report and discussion remain on that issue.

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Branch Name

HEAD (detached in Loom task workspace)

Commit ID

429c27761be90c3c865685700cc208e194e61be6

Other Environment Information

  • Hardware parameters: Apple Silicon, darwin/arm64, macOS 15.5
  • OS type: macOS 15.5 (24F74), Go 1.26 arm64
  • Others: standalone mo-service built with make build from the commit above, launched with ./mo-service -launch .loom-test/launch/launch.toml (copy of etc/launch, all ports shifted +20400, frontend on 26401, user dump/111, default sql_mode, no IGNORE/REPLACE keyword in any statement below). MySQL reference: Homebrew [email protected] 8.0.46 on port 23706, mysqld --no-defaults --secure-file-priv set so the same CSV files are readable server-side by both products.

Actual Behavior

A plain LOAD DATA (no IGNORE/REPLACE) into a table with a UNIQUE KEY silently stores rows that violate the unique constraint. All four variants below were run on the same commit:

  1. Duplicate unique values inside the input file — serial server-side LOAD DATA INFILE loads every row and returns success:
-- file dup_uq.csv: rows (1,100,111),(2,100,222),(3,300,333); UNIQUE KEY uk_u(u)
-- load data infile '<D>/dup_uq.csv' into table u1t ...;
-- Query OK, 3 rows affected   (no error)
-- select u, count(*) c from u1t group by u having c>1;
100  2
  1. The same file with PARALLEL 'true': same silent result (3 rows, u=100 twice).
  2. Conflict against pre-existing committed rows: after loading (10,500,555), a second plain load of (11,500,666) succeeds silently; the table then contains both rows with u=500.
  3. LOAD DATA LOCAL INFILE (client upload, default strict session): same silent result (3 rows, u=100 twice).

Controls proving this is a LOAD-path gap and not a disabled constraint:

  • The same duplicate inserted with INSERT INTO ... VALUES correctly fails: ERROR 1062 (23000): Duplicate entry '100' for key 'u'.
  • A subsequent INSERT of the already-loaded duplicate also fails with ERROR 1062: Duplicate entry '100' for key 'u' — i.e. the constraint exists, and the table provably contains the duplicate that LOAD committed.
  • Duplicate primary keys in the identical LOAD statement shape are correctly rejected with ERROR 1062 (23000): Duplicate entry '1' for key 'id' (the recent fix for [Bug]: LOAD DATA inserts duplicate primary keys without error #30411 works for PKs).
  • select * from ukdb.u1t shows both (1,100,111) and (2,100,222); unique-index-based lookups may return either row, so query results become order-dependent.

Expected Behavior

LOAD DATA must enforce declared UNIQUE KEYs the same way INSERT does. MySQL 8.0.46 rejects every case above with the identical statement (server-side INFILE, default strict session):

-- unique dup inside file
ERROR 1062 (23000) at line 1: Duplicate entry '100' for key 'u1t.uk_u'
-- conflict against pre-existing row
ERROR 1062 (23000) at line 1: Duplicate entry '500' for key 'u3t.uk_u'

Exiting MatrixOne behavior for the PRIMARY key (ERROR 1062 ... Duplicate entry '1' for key 'id') shows the intended semantics: a plain strict load aborts on constraint conflicts. The unique key paths must behave the same; anything else silently commits an invalid table state (duplicate entries also land in the unique index's hidden table, so the invariant is broken for subsequent reads and for any later INSERT that happens to touch the duplicated value).

Steps to Reproduce

Create the input files:

printf '1,100,111\n2,100,222\n3,300,333\n' > <D>/dup_uq.csv   # u=100 twice
printf '10,500,555\n' > <D>/uq_pre.csv                         # pre-existing row
printf '11,500,666\n' > <D>/uq_conflict.csv                   # conflicts with pre row

On MatrixOne (standalone mo-service, default session sql_mode, mysql client with --force so later statements run):

drop database if exists ukdb;
create database ukdb;
use ukdb;

-- 1) in-file unique dup, serial server-side load
create table u1t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '<D>/dup_uq.csv' into table u1t
  fields terminated by ',' lines terminated by '\n';
-- Actual: Query OK, 3 rows affected; NO ERROR
select * from u1t order by id;                     -- both (1,100,...) and (2,100,...) stored
insert into u1t values (77, 100, 7);               -- ERROR 1062: Duplicate entry '100' for key 'u'

-- 2) same file, parallel
create table u2t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '<D>/dup_uq.csv' into table u2t
  fields terminated by ',' lines terminated by '\n' parallel 'true';
-- Actual: Query OK, 3 rows affected; NO ERROR

-- 3) conflict against pre-existing committed row
create table u3t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '<D>/uq_pre.csv' into table u3t fields terminated by ',' lines terminated by '\n';
load data infile '<D>/uq_conflict.csv' into table u3t fields terminated by ',' lines terminated by '\n';
select id, u from u3t;                              -- (10,500) AND (11,500) both stored

-- 4) LOCAL upload
create table u6t(id int primary key, u int, v int, unique key uk_u(u));
load data local infile '<D>/dup_uq.csv' into table u6t fields terminated by ',' lines terminated by '\n';
select u, count(*) from u6t group by u having count(*) > 1;   -- 100 | 2

On MySQL 8.0.46, run statements 1 and 3 verbatim (needs the server to be allowed to read , e.g. secure_file_priv including it):

-- 1) yields: ERROR 1062 (23000): Duplicate entry '100' for key 'u1t.uk_u'
-- 3) second load yields: ERROR 1062 (23000): Duplicate entry '500' for key 'u3t.uk_u'

Additional information

Root cause. The plan builder for DML statements skips the unique-key conflict validation specifically for loads. In the shared INSERT/LOAD sink builder, "dedup#2: handle unique key dedup" contains:

// pkg/sql/plan/bind_insert.go, dedup#2 loop:
// LOAD still maintains index tables, but unique-key conflict handling
// is separate from ordinary LOAD's primary-key validation.
if !idxDef.Unique || builder.qry.LoadTag {
    continue
}

(pkg/sql/plan/bind_insert.go:3755-3759). builder.qry.LoadTag is unconditionally true for LOAD DATA (set in pkg/sql/plan/bind_load.go:34), so the unique dedup joins that make INSERT fail with 1062 are never built for any load — serial, parallel, or LOCAL. LOADs still maintain the unique index hidden table, appending one entry per input row, which is why the corruption also reaches the index itself.

The recent fix for #30411 wired primary-key validation back in for plain loads via a dedicated switch: builder.checkLoadPrimaryKey = loadChecksPrimaryKey(stmt, tableDef) (pkg/sql/plan/bind_load.go:44, predicate at pkg/sql/plan/bind_load.go:262-274) feeding ifNeedCheckPkDup := !builder.qry.LoadTag || builder.checkLoadPrimaryKey (pkg/sql/plan/build_dml_util.go:255) — that is why load ... Duplicate entry '1' for key 'id' now fires for PKs while unique keys stay unchecked. Unique keys simply have no analogous hook.

Relation to existing issues (checked, not duplicates).

Recommended fix. Attach the same unique-index dedup joins (or pre-insert UK arbitration) that INSERT uses to plain strict loads — i.e., let builder.qry.LoadTag no longer bypass dedup#2, gated on the same checkLoadPrimaryKey-style policy: default strict plain load → reject with ERROR 1062 (23000): Duplicate entry ... exactly like INSERT and MySQL; under IGNORE/LOCAL/non-strict keep the current tolerant behavior for the tolerance levels the team chooses for #25470, but even then conflicts should be resolved to the first row rather than committed twice. Backward-compatibility note: tables that already contain silently-loaded duplicates will fail any new strict path until repaired; a repair recipe (deduplication SQL picking one winner per unique value) should be linked in the release notes, since the duplicates are not distinguishable from committed data afterwards.

Stability. Reproduced 4/4 variants (serial, parallel, pre-existing-row conflict, LOCAL upload) across separate sessions on the same build; the INSERT controls failed with 1062 in every run.

Full reproduction, exactly as Loom ran it
#!/bin/bash
# Unique-key bypass of plain LOAD DATA — reproduce on MatrixOne, mirror on MySQL 8.0.
# <D> = a directory the MySQL server may read (secure_file_priv) and MatrixOne can access.
D=/Users/linjunhong/.loom/workspaces/hunt/w3/.loom-test/loaddata
MY=/opt/homebrew/opt/mysql@8.0/bin/mysql

printf '1,100,111\n2,100,222\n3,300,333\n' > $D/dup_uq.csv
printf '10,500,555\n' > $D/uq_pre.csv
printf '11,500,666\n' > $D/uq_conflict.csv

# ---------- MatrixOne (standalone mo-service, frontend 26401, user dump/111) ----------
MOPT="$MY -h127.0.0.1 -P26401 -udump -p111 --default-character-set=utf8mb4 --local-infile=1 --force"
$MY $MOPT -e "drop database if exists ukdb; create database ukdb;"

echo '=== U1: serial server-side load, in-file unique dup (NO IGNORE)'
$MY $MOPT -e "use ukdb; create table u1t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '$D/dup_uq.csv' into table u1t fields terminated by ',' lines terminated by '\\n';
select 'rows', count(*) from u1t;"
# Actual: Query OK, 3 rows affected ; rows = 3  (duplicate u=100 accepted silently)

echo '=== U2: same file with PARALLEL true'
$MY $MOPT -e "use ukdb; create table u2t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '$D/dup_uq.csv' into table u2t fields terminated by ',' lines terminated by '\\n' parallel 'true';
select 'rows', count(*) from u2t;"
# Actual: Query OK, 3 rows affected ; rows = 3

echo '=== U3: conflict against pre-existing committed unique value'
$MY $MOPT -e "use ukdb; create table u3t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '$D/uq_pre.csv' into table u3t fields terminated by ',' lines terminated by '\\n';
load data infile '$D/uq_conflict.csv' into table u3t fields terminated by ',' lines terminated by '\\n';
select id, u from u3t order by id;"
# Actual: (10,500) and (11,500) both stored, loads both report success

echo '=== U4: INSERT control on the same shape'
$MY $MOPT -e "use ukdb; insert into u3t values (99, 987, 1); insert into u3t values (98, 987, 2);"
# Actual: ERROR 1062 (23000): Duplicate entry '987' for key 'u'   (constraint is active for INSERT)

echo '=== U6b: prove the silent duplicate is committed; another INSERT of it fails'
$MY $MOPT -e "use ukdb; insert into u1t values (77, 100, 7);"
# Actual: ERROR 1062 (23000): Duplicate entry '100' for key 'u'

echo '=== U6: LOCAL upload, same dup file'
$MY $MOPT -e "use ukdb; create table u6t(id int primary key, u int, v int, unique key uk_u(u));
load data local infile '$D/dup_uq.csv' into table u6t fields terminated by ',' lines terminated by '\\n';
select u, count(*) c from u6t group by u having c > 1;"
# Actual: 100 | 2

echo '=== PK control: same statement shape with primary-key dups (works correctly since #30411)'
$MY $MOPT -e "use ukdb; create table pkc(id int primary key, v int);
load data infile '$D/dup_pk.csv' into table pkc fields terminated by ',' lines terminated by '\\n';"
# Actual: ERROR 1062 (23000): Duplicate entry '1' for key 'id'

# ---------- MySQL 8.0.46 reference (port 23706; same files readable via secure_file_priv) ----------
MOY="$MY -uroot -h127.0.0.1 -P23706 --force"
$MY $MOY -e "drop database if exists ukdb; create database ukdb;"
echo '=== U1mysql'
$MY $MOY -e "use ukdb; create table u1t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '$D/dup_uq.csv' into table u1t fields terminated by ',' lines terminated by '\\n'; select count(*) from u1t;"
# Expected: ERROR 1062 (23000): Duplicate entry '100' for key 'u1t.uk_u'
echo '=== U3mysql'
$MY $MOY -e "use ukdb; create table u3t(id int primary key, u int, v int, unique key uk_u(u));
load data infile '$D/uq_pre.csv' into table u3t fields terminated by ',' lines terminated by '\\n';
load data infile '$D/uq_conflict.csv' into table u3t fields terminated by ',' lines terminated by '\\n'; select count(*) from u3t;"
# Expected: ERROR 1062 (23000): Duplicate entry '500' for key 'u3t.uk_u'

Found by Loom bug hunt (module: custom-a9872c7d6e; tests: unit, white-box, end-to-end)

Activity

  1. added
    kind/bug
    on Oct 17, 2026
  2. Ariznawlll commented on Oct 19, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:官方 main
    • commit:75ff736835c3d00d40dc00a0a1d3b11129388e5b
    • 部署方式:macOS arm64,隔离的单进程 LOG/TN/CN,fresh 数据目录,frontend 16001;该 commit 当天本地编译。
    • 测试日期:2026-10-19

    原问题验证

    普通 LOAD DATA LOCAL INFILE 仍可把文件内重复的非主键 UNIQUE 值写入表;普通 INSERT 对相同冲突返回 ERROR 1062 (23000): Duplicate entry '7' for key 'u'。与 issue 已记录的根因一致,未新建重复 bug。

    Happy Path 覆盖

    1. 对已由 LOAD 写出重复值的表执行 ALTER TABLE ... ADD COLUMN extra INT NOT NULL DEFAULT 9 AFTER v,DDL 成功;表扫描读到 (id,u,v,extra)=(1,7,1.10,9),(2,7,2.20,9),说明表数据仍完整且新列默认值正确。
    2. 对正常的 INSERT 对照表,第一行 (1,7,1.10) 写入成功,第二行相同 UNIQUE 值被正确拒绝为 1062/23000。

    Unhappy Path 覆盖

    1. 文件内容为 1,7,1.10 与 2,7,2.20,目标表定义 id INT PRIMARY KEY, u INT, v DECIMAL(10,2), UNIQUE KEY uk_u(u);不带 IGNORE/REPLACE 的 LOAD DATA LOCAL INFILE 错误地成功。对三个全新表分别重复 LOAD → COPY ALTER → 读取,每次结果均为:WHERE u=7 的索引查询 COUNT(*)=1,而强制扫描的 WHERE u+0=7 为 COUNT(*)=2。相同表、相同已提交数据出现不一致的查询结果。
    2. 失败后的可用性:未见连接中断;索引查询与扫描查询都能完成,但结果不同。这里没有触发应有的唯一约束失败,不能把它记为失败原子性通过。

    白盒验证

    当前 pkg/sql/plan/bind_insert.go 的 dedup#2 仍在 builder.qry.LoadTag 为真时跳过 UNIQUE 冲突验证;pkg/sql/plan/bind_load.go 设置该标志。EXPLAIN WHERE u=7 显示 Join Type: INDEX 和 Index Table Scan on load_unique.uk_u,EXPLAIN WHERE u+0=7 为普通 Table Scan。这支持“同一个已破坏的唯一约束导致路径依赖的错误结果”,不额外假定新的根因。

    回归测试

    本次探索按要求没有新增仓库测试或 PR。修复 #30500 时,建议在回归中同时断言:普通 LOAD 拒绝重复 UNIQUE;若存在修复前的脏表,COPY ALTER 后不能让索引路径漏行或错误地宣称完整结果。

    测试证据

    最小复现 SQL:

    CREATE TABLE t (id INT PRIMARY KEY, u INT, v DECIMAL(10,2), UNIQUE KEY uk_u(u));
    -- CSV: 1,7,1.10\n2,7,2.20\n
    LOAD DATA LOCAL INFILE '<fixture>/load_unique.csv' INTO TABLE t
      FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (id,u,v);
    ALTER TABLE t ADD COLUMN extra INT NOT NULL DEFAULT 9 AFTER v;
    SELECT COUNT(*) FROM t WHERE u=7;   -- MO: 1, Index Table Scan
    SELECT COUNT(*) FROM t WHERE u+0=7; -- MO: 2, Table Scan

    三次全新建表对照均为 indexed_count=1, scan_count=2;对应本地隔离证据为 /private/tmp/mo-explore-run-20261019/load_unique.csv 和本轮命令输出。

    测试结论

    测试不通过。

  3. changed the title [-][Bug]: LOAD DATA silently stores duplicate unique-key values that INSERT and MySQL reject[/-] [+][Bug]: LOAD DATA must enforce table constraints and honor IGNORE row semantics[/+] on Oct 22, 2026
  4. Ariznawlll commented on Oct 26, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:官方 main;源码 commit:5fe08a3307e246e1ab9951ab690b50557af0f509(已包含 [Bug]: LOAD DATA inserts duplicate primary keys without error #30411 的修复合并提交 ba0cd6dd9ed766c1effdda042d681c3b5bef70c8)。
    • 部署:隔离本地单节点 LOG/TN/CN;服务端 VERSION() 为 8.0.30-MatrixOne-v1.3.0;测试日期:2026-10-26。

    原问题验证

    用同一 CSV 1,alpha\n1,beta\n2,gamma\n,每轮新建 id INT PRIMARY KEY 的空表,在 mo_pk_check_by_cn=0(当前默认值)下执行普通 LOAD DATA INFILE:3/3 报成功,每轮得到 [(1,alpha),(1,beta),(2,gamma)],COUNT(*)=3、COUNT(DISTINCT id)=2。同一表形状的普通 INSERT 对重复主键正确返回 1062,确认约束本身存在。

    Happy Path 覆盖

    将同一会话显式设为 mo_pk_check_by_cn=1,相同 CSV 在另外三个全新空表中 3/3 返回 1062,失败后每张表仍是 0 行。同一连接随后仍可查询。此前也核对合法 CSV/JSONLINE 的失败后修正文件重试可精确装载。

    Unhappy Path 覆盖

    默认 mo_pk_check_by_cn=0 的严格 LOAD 未拒绝文件内重复主键,错误值持久化;这一行为与 #30411 的验收结果不一致。mo_pk_check_by_dn=off,不存在开启 DN 检查的混淆。

    白盒验证

    pkg/sql/plan/bind_load.go:301-325 仅在会话变量 mo_pk_check_by_cn=1 时启用 checkLoadPrimaryKey;pkg/sql/plan/bind_insert.go:154-164 在 LOAD 且该标志为 false 时跳过 dedup。后续提交 460b96365a(#30697)把 CN PK 检查设为 opt-in,当前 pkg/frontend/variables.go 默认 0。本轮未运行 Go UT/-race。

    回归测试

    本轮未修改仓库测试或 PR。建议在 #30500 的 strict LOAD 约束矩阵中同时验证默认 OFF 与显式 ON;只测 ON 会掩盖生产默认路径。原 #30411 的回归用例与修复提交仍可复用。

    测试证据

    隔离复现脚本:/private/tmp/mo-sdk-io-20261026/pk_gate_probe.py;三轮分别输出 SETTING 0 ... LOAD_OK ROWS [(1,'alpha'),(1,'beta'),(2,'gamma')] 和 SETTING 1 ... 1062 ... ROWS []。这是对 #30500 的新边界证据,不另开重复 issue。

    测试结论

    测试不通过。

  5. Ariznawlll commented on Oct 26, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 官方 main commit:5fe08a3307e246e1ab9951ab690b50557af0f509;服务端 8.0.30-MatrixOne-v1.3.0;2026-10-26。
    • 隔离本地单节点 LOG/TN/CN,Python SDK 0.1.16 / Python 3.11;只在隔离数据库中建表。

    原问题验证

    进一步覆盖 SDK 的原生 Arrow IPC LOAD DATA 路径:analytics.upload_arrow(create=False) 将 2500 个不同主键加末尾重复主键 1,按 127 行切批写入已有 PRIMARY KEY 表。三个新建表 3/3 均错误地报告成功并提交 2501 行,但 COUNT(DISTINCT id)=2500。随后同表正常插入其他唯一键仍成功,说明非法状态已经提交而不是客户端计数错误。

    Happy Path 覆盖

    在另三个新建表的连接上先设置 mo_pk_check_by_cn=1,同一 SDK Arrow 写入含重复键的输入 3/3 返回 1062,失败后目标表均保持 COUNT(*)=0;修正为唯一键 [1,2] 后 3/3 成功恢复两行,连接可用。这是与错误路径相邻的正确原子性对照。

    另外,analytics.read_parquet() 的同一三行 [1,2,1] 文件经 FileRelation.import_into() 走 INSERT INTO ... SELECT,在 CN gate=0 和 1 两组各 3/3 均正确返回 1062、目标空表。问题因此更精确地限于 SDK 的 Arrow IPC LOAD 路径,不是所有文件关系导入均绕过主键。

    Unhappy Path 覆盖

    默认 mo_pk_check_by_cn=0 下,严格 Arrow LOAD 漏掉文件内后段重复主键,upload_arrow() 的返回值 2501 和目标表状态一致但都违反主键约束。后续 INSERT 触及重复键时正常报 1062。输入同时含 DECIMAL(19,2) 与中文 TEXT,说明该现象不依赖只有一列的简化表形状。

    白盒验证

    clients/python/matrixone/analytics.py:49-90 的 _write_transaction() 临时启用 mo_pk_check_by_dn=1 和 STRICT_ALL_TABLES,但没有启用当前 main 中 LOAD 主键检查所需的 mo_pk_check_by_cn;服务端的默认 CN 开关仍为 0。与本 issue 已记录的默认 gate 行为同根,不另提重复 bug。SDK 文档声称 Arrow upload 在 COMMIT 前启用 TN 主键检查,修复/回归时还应验证对当前 CN gate 的实际效果。

    回归测试与证据

    本轮未新增仓库测试或 PR。脚本 /private/tmp/mo-sdk-analytics-deep-20261026/late_duplicate_probe.py 输出三轮 COUNT(*)=2501, COUNT(DISTINCT id)=2500;pk_cn_gate_control.py 输出三轮 1062、空表、修正输入后 [1,2];relation_import_pk_probe.py 输出 INSERT SELECT 的双 gate 原子性对照。建议 #30500 回归包含 Arrow IPC 格式及“末尾跨批重复键”的默认/显式 gate 对照。

    测试结论

    测试不通过。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions