Skip to content

[Bug]: LOAD DATA never publishes its first generated AUTO_INCREMENT id — LAST_INSERT_ID() stays 0/stale #31330

Closed

Description

@iamlinjunhong

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Checked in particular: #25100 and #27295 (multi-row INSERT published the last instead of the first generated id — fixed; INSERT path is correct here, LOAD is not); #27237 (REPLACE did not publish — fixed by adding status_stmt handling; the same gap remains for LOAD); #29903/#30004 (hidden fake-PK id leaked into LAST_INSERT_ID — different direction, and already excluded); #27298 (JDBC getGeneratedKeys with an explicit auto-inc value — different mechanism); #29184/#29192 (proxy migration resets LAST_INSERT_ID — environment-specific, not statement semantics). None covers LOAD DATA, whose generated first id never reaches LAST_INSERT_ID().

Branch Name

main

Commit ID

26e3289

Other Environment Information

  • Hardware: Apple M-series 10-core arm64, 16GB RAM
  • OS: macOS 15 (darwin)
  • Single-node all-in-one mo-service (launch config 1 CN + 1 DN + logservice)
  • Client: local mysql CLI (any MySQL-protocol client)

Actual Behavior

TARGET

create table ai_lid (id bigint not null auto_increment, v varchar(10), primary key(id));
truncate table ai_lid;
load data infile '/path/10m_single_col.csv' into table ai_lid (v);   -- 10,000,000 rows
select last_insert_id();  -- expected 1, actual 0

MySQL 8.0.46, identical table and file on the same machine: last_insert_id() returns 1 — the first automatically generated value of the load. MySQL documents this for LOAD DATA just as for multi-row INSERT.

MatrixOne returns 0 after a first-in-session bulk load. After a smaller in-session load the returned value is the previous statement's, proving it is a non-publish and not a reset:

SESSION TRACE (all statements in one session, actual values pasted)

truncate table ai_lid;
insert into ai_lid (v) values ('q');
select 'after_insert',  last_insert_id();   -- 1     (INSERT publishes first id: MySQL-correct)
load data infile '/tmp/mini.csv' into table ai_lid (v);   -- 2 rows
select 'after_load',    last_insert_id();   -- 1     (stale: LOAD consumed ids 2,3 but published nothing)
insert into ai_lid (v) values ('w');
select 'after_insert2', last_insert_id();   -- 4     (proves LOAD really allocated 2,3 from the counter)

The counter is consumed (next insert gets id 4), rows are inserted with correct sequential ids (=2,3 for the mini load; 1..10,000,000 for the big one) — only the publication of the first generated value to LAST_INSERT_ID() is missing. Also reproduced with an explicit parallel 'true' clause (same non-publish).

Why the publication is missing (root cause, whitebox)

The statement-completion switch that copies a statement's generated-key value into the session-visible LAST_INSERT_ID has cases for *tree.Insert, *tree.Replace and *tree.MultiInsert, but no case for *tree.Load (pkg/frontend/status_stmt.go:433-475, the Insert case is at :433-438 — res.lastInsertId = execCtx.proc.GetStatementLastInsertID(); ses.SetLastInsertID(...)). The PRE_INSERT operator that assigns bulk auto ids has the publishing machinery already (pkg/sql/colexec/preinsert/preinsert.go:672-680: proc.SetStatementLastInsertIDIfEarlier(lastInsertValue) for the first generated value; pkg/vm/process/types.go:886-923 implements the statement-wide smallest-value coordinator and also mirrors it into the session-visible LastInsertID), but for a RUN pipeline whose generated value never crosses into the session's post-statement publish switch, select last_insert_id() (which reads proc.GetLastInsertID(), pkg/sql/plan/function/func_unary.go:11272-11274) observes the pre-load value. #27237 fixed the exactly parallel gap for REPLACE by extending this switch; LOAD was left out.

Impact

Any application flow that bulk-imports and then references the generated ids — the standard pattern is LOAD; last_insert_id() (or JDBC getGeneratedKeys after LOADS through the same session variables) — silently reads 0 or a stale older id and writes the wrong reference. It is a correctness defect, not a performance one; on the flip side it is a clean one-line-ish fix at the same place REPLACE was fixed (#27237).

Expected Behavior

MySQL 8.0 semantics: after LOAD DATA ... the value of LAST_INSERT_ID() is the first automatically generated AUTO_INCREMENT value successfully inserted by the load (observed: 1 on identical input in this environment). MatrixOne's plain INSERT already implements exactly this first-value rule (verified here: multi-row insert returns 1); LOAD must publish through the same rule — most directly by adding the *tree.Load case to the statement-completion switch (status_stmt.go:433) reading proc.GetStatementLastInsertID(), honoring the existing "smallest non-zero generated value" coordinator so a parallel load also publishes the true first id.

Full reproduction, exactly as Loom ran it
-- MatrixOne: LOAD DATA never publishes its first generated AUTO_INCREMENT id
-- Run with any MySQL-protocol client against MO, then repeat the same against MySQL 8.0.
-- (On some client builds this server needs --default-character-set=utf8mb4 to connect; add it if you
--  see 'ERROR 2013 reading authorization packet'.)

create database if not exists lidrepro;
use lidrepro;
create table ai_lid (id bigint not null auto_increment, v varchar(10), primary key(id));
truncate table ai_lid;

-- 10M-row single-column CSV (generate 37MB; a 2-row file also shows the effect, see below)
-- shell: python3 -c "open('/tmp/mini.csv','w').write('x1\\nx2\\n')"
-- shell: python3 -c "open('/tmp/big.csv','w').write('\n'.join(f'A{i%97}' for i in range(10_000_000))+'\n')"

-- CASE 1: bulk load as the first id-generating statement of the session
load data infile '/tmp/big.csv' into table ai_lid (v);
select sum(1) as n, last_insert_id() as lid;   -- sum(1): a same-batch count(*) can hit an unrelated
--                                              stale-metadata flake; use sum(1) or a fresh session.
-- MO EXPECTED (bug):     n=10000000, lid=0
-- MySQL 8.0 EXPECTED:     n=10000000, lid=1

-- CASE 2: proves ids were really generated and the old value is merely stale
truncate table ai_lid;
insert into ai_lid (v) values ('q');
select 'after_insert', last_insert_id();   -- 1 both MO and MySQL
load data infile '/tmp/mini.csv' into table ai_lid (v);                  -- 2 rows
select 'after_load', last_insert_id();
-- MO EXPECTED (bug):     1  (stale; ids 2,3 consumed but never published)
-- MySQL 8.0 EXPECTED:    2  (first id generated by the load)
insert into ai_lid (v) values ('w');
select 'after_insert2', last_insert_id(); -- 4 on MO (counter confirms LOAD consumed 2,3); 4 on MySQL

-- CASE 3: explicit parallel clause makes no difference on MO
truncate table ai_lid;
load data infile '/tmp/big.csv' into table ai_lid (v) parallel 'true';
select 'after_load_par', last_insert_id(), (select count(*) from ai_lid) as n;
-- MO EXPECTED (bug):     lid=0 (as observed: parallel 'true' clause, load admitted serially
--                        because the file is under the parallel minimum size); MySQL n/a (no PARALLEL syntax)

-- Verification that rows landed with correct sequential ids:
select min(id), max(id), count(*) from ai_lid;

Found by Loom bug hunt (module: custom-82082add71; tests: white-box, black-box, concurrency; severity: S1)

Activity

  1. added
    kind/bug
    severity/s1
    ai-easy
    on Oct 26, 2026
  2. slyunnn commented on Oct 30, 2026

    @slyunnn

    Regression and extended verification for #31330 (2026-10-30)

    Verification Environment

    Main frozen at test start: d39d8a40343ccd40bf665036388df7a40ee867f8, tae: flush eligible AObject prefixes before busy tails (#31723). Reused the actual binary freshly built and verified at this exact revision earlier today; no service-source changes. Native macOS/arm64, Go 1.27.1, GOEXPERIMENT=simd.

    Fresh isolated 2 CN / 1 TN / 1 Log service / Proxy deployment. Proxy localhost:6001, CN1 localhost:16001, CN2 localhost:16002 were all reachable, returned matching git_version(), and each executed the original and extended cases. Clients: PyMySQL MySQL text protocol, including the real LOCAL INFILE upload and OK-packet affected-row/insert-ID fields; maintained BVT used Connector/J 8.0.15. No binary prepared-statement claim.

    What Was Covered

    • OK — First generated-ID LOAD returns OK insert ID 1 and LAST_INSERT_ID() = 1; the original same-connection sequence is INSERT → LOAD → INSERT, with IDs 1 → 2 → 4. Default, explicit serial and requested-parallel modes pass on all 3 endpoints.
    • OK — Empty input, explicit IDs and tables without user AUTO_INCREMENT return no generated OK ID and preserve the session baseline. INLINE, real LOCAL INFILE, a separate session, increment 4 / offset 3, missing-file rejection and successful retry all pass.
    • OK — 32,768-row loads cross the normal batch boundary: exact count, ID uniqueness, extrema and sum are correct, and the next insert receives 32,769.
    • OK — Real parallel extension: a 268,451,139-byte file with 240,002 records executes with 2 reader workers on each endpoint. OK insert ID and session value equal the actual global MIN(id); payload identity, cardinality, uniqueness and sums are exact. Allocation can reserve an initial range, so the parallel oracle does not assume contiguous IDs beginning at 1.
    • OK — All owned databases are removed; connections remain healthy and the test-owned service exits cleanly.
    • Not covered — A fresh MySQL reference-server run, the original 10,000,000-row volume, exhaustive completion schedules or independent-process fault injection. Two reader workers were observed; this does not assert that both CNs processed the same statement.

    Findings

    PR #31623, merge 5cd0b196751635e50ec414d034658b68f26c0392, Publish generated IDs for LOAD DATA, is included in the tested main. Successful LOAD now publishes its statement-generated ID to the MySQL OK response and updates session state only when nonzero. The zero/stale publication defect no longer reproduces.

    MOTR / BVT Coverage

    Newly executed TestRespStatusLoadUsesStatementGeneratedKey and TestStatementLastInsertIDSemantics passed with -count=1. Existing load_last_insert_id.sql (20 statements) and the companion CSV-comment BVT (36) passed twice: 56/56 per run, with teardown checked between runs. Complete load_data group: 1681 passed, 5 existing issue-3433 skips, 0 failed/abnormal; skips are not counted as passes.

    Small endpoint fixtures ran concurrently in separate databases. Resource-bound parallel loads and BVT ran serially to avoid shared-resource/database conflicts. Existing maintained coverage was reused; no duplicate MOTR case, commit or PR was added. The first broad JDBC run lacked allowLoadLocalInfile; its failed report was retained, the client option was corrected, and the accepted complete run passed without changing SQL expectations.

    Final Conclusion

    Fixed on the verified main. Scale-boundary regression was warranted for the claimed multi-batch/parallel extension and is complete: 32,768 rows cover batching; approximately 256 MiB and more than 240,000 records cross the real reader and AP-admission thresholds. No arbitrary 10,000,000-row or additional TKE performance run is needed for this publication defect.

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

Metadata

Metadata

Assignees

Labels

ai-easykind/bugseverity/s1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions