Skip to content

[Bug]: CREATE TABLE can attach a stale incoming foreign key to a replacement table #29852

Closed

Description

@XuPeng-SH

Summary

A concurrent parent-table creation can apply a planned incoming foreign-key repair to a same-name child table that was dropped and recreated without that foreign key. The replacement child then has inconsistent FK metadata and rejects inserts that should be valid.

I reproduced this on PR #29837 and on its exact main base (dd38098853ea197699ed3fac3e69dc53975ac061) using the same deterministic post-planning/pre-effects schedule. This is a pre-existing common CREATE/forward-FK repair bug, not a regression attributed to #29837.

Reproduction

Use two CNs with pessimistic RC. The synchronization point is after Session B has planned the parent CREATE (including incoming-FK repair from the old child) and before it applies that repair. The deterministic reproduction uses a test-only post-plan barrier.

-- Session A: create a child referencing a parent that does not exist yet.
CREATE DATABASE fk_forward_repro;
SET foreign_key_checks = 0;
CREATE TABLE fk_forward_repro.child (
  id INT PRIMARY KEY,
  pid INT,
  CONSTRAINT fk_forward FOREIGN KEY (pid)
    REFERENCES fk_forward_repro.parent(id)
);
SET foreign_key_checks = 1;
CREATE TABLE fk_forward_repro.guard (id INT);

-- Session A: begin and retain a transaction after dropping an unrelated table.
BEGIN;
DROP TABLE fk_forward_repro.guard;

-- Session B: start this after Session A retains the transaction, then pause
-- after planning and before CREATE effects / incoming-FK repair.
CREATE TABLE fk_forward_repro.parent (id INT PRIMARY KEY);

-- Session A, while Session B is paused:
DROP TABLE fk_forward_repro.child;
CREATE TABLE fk_forward_repro.child (id INT PRIMARY KEY, pid INT);
COMMIT;

-- Resume Session B. Its parent CREATE succeeds. Check the new child:
SHOW CREATE TABLE fk_forward_repro.child;
SELECT COUNT(*) FROM mo_catalog.mo_foreign_keys
 WHERE db_name = 'fk_forward_repro' AND table_name = 'child';
INSERT INTO fk_forward_repro.child VALUES (1, 999);

Expected: the replacement child has no FK and the INSERT succeeds. Actual: its physical table ID is new and the catalog FK row count is zero, but SHOW CREATE TABLE contains the old fk_forward constraint and the INSERT fails with error 20101 (Cannot add or update a child row: a foreign key constraint fails). Both CREATE statements succeed.

Root cause

The common CREATE forward-repair path consumes the plan-time FksReferToMe entries, resolves the child by database/table name, then attaches the old FK definition to whichever relation currently has that name. It does not verify that the relation is the same child generation or that it still declares the pending FK. The relevant path is ddl.go in the common CREATE repair loop.

Revalidate current FK facts and participant identity/column bindings before metadata effects, and use the existing retry/replanning mechanism if they changed. The validation must cover incoming child participants; checking only the outgoing parent identity does not close this case.

Evidence

  • PR public-SQL reproduction and exact-main controlled comparison both fail with the same persisted stale constraint and rejected INSERT.
  • The baseline comparison restores all five PR-changed production files from the main commit above. Its only diagnostic change is a test scheduling callback, so the bug predates the PR's lifecycle admission/snapshot logic.
  • No data-loss claim is made; the observed impact is incorrect schema/constraint behavior and rejected valid writes.

Activity

  1. added
    kind/bug
    on Oct 11, 2026
  2. XuPeng-SH commented on Oct 11, 2026

    @XuPeng-SH
    ContributorAuthor

    Additional review observations from PR #29837, recorded here at the reporter's request. These are non-blocking risks or coverage gaps, distinct from the confirmed stale incoming-FK repair defect described above. They are not additional reproduced failures or mandatory scope expansion for this FK fix.

    • Lock fairness: the base already uses WriterFair=false. The PR adds shared-lock use cases, which may increase the waiting window for exclusive locks under sustained shared-lock traffic. There is currently no evidence that it introduces a new starvation failure, so this observation alone is not a blocker. A focused progress check under sustained contention would provide stronger evidence; the existing setting alone does not rule out an increased risk.
    • Catalog-query cost: counting 12/14 queries does not establish a performance regression. The prior path also performs history/branch checks, and ordinary SELECT/DML does not enter these newly added checks. Compare equivalent old/new paths by actual latency and contention. Existing concurrency tests demonstrate that unrelated TRUNCATE makes progress in the targeted convoy scenario; they do not establish lower uncontended TRUNCATE latency or improved throughput. Those claims require comparative measurement.
    • Coverage gaps: compact regressions are worthwhile for cancellation/deadline expiry while waiting for the target table lock and for PITR-protected fallback. For cancellation/deadlines, assert prompt termination, intact table identity/data, and successful subsequent use. For PITR, assert the protected table follows the correct broad path and preserves recovery behavior. These are coverage gaps; no corresponding implementation error has yet been identified.

    Treat the first two points as risk/measurement boundaries and the third as targeted validation work. Do not present an unmeasured possibility as a confirmed defect, or treat lack of reproduction as a substitute for necessary validation.

  3. self-assigned this
    on Oct 11, 2026
  4. Ariznawlll commented on Oct 12, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:main
    • commit:02a2823c2007d5e4fb4ada148e93743df337551a
    • 部署方式:本地嵌入式双 CN,执行 pkg/tests/issues 的确定性并发测试
    • 测试日期:2026-10-12

    原问题验证

    运行 TestIssue29852ForwardCreateReplacementGeneration:一个 CN 已规划父表 CREATE、等待锁期间,另一个 CN 删除含待绑定外键的旧 child,再新建同名但无外键的 child。用测试钩子固定等待时序,不依赖随机竞争。连续 3 次均成功完成父表创建;替换 child 的表 ID 与旧表不同,mo_foreign_keys 无残留,SHOW CREATE TABLE 无旧外键,向新 child 插入原本会违反旧外键的行成功。原先“旧外键错误附着在新 child 上”的现象未再复现。

    Happy Path 覆盖

    运行 TestIssue29852ForwardCreateNeighborSchedules:原 child 仍有待绑定外键时,父表创建后外键必须生效;另一个父/子交错创建时序也成功完成并保持外键。两个分支均连续 3 次通过。

    Unhappy Path 覆盖

    对保留外键的 child 插入无对应 parent 的非法 pid,均按预期被外键约束拒绝;对已替换且不再声明外键的 child 执行同样插入则成功。双 CN 测试没有卡住或超时。

    白盒验证

    用 lockservice.SetWaiterEnqueuedHookForTest 固定 post-plan/pre-effects 等待窗口,并检查替换前后物理表 ID、mo_foreign_keys、DDL 和实际写入行为。此次未做长时间混沌或生产规模压力测试。

    回归测试

    主仓库已有 确定性双 CN UT,本轮执行 -count=3 通过。本问题必须控制精确并发时序,这一 UT 比 SQL-only MOTR 更适合持续覆盖,因此未增加无法稳定触发该时序的 MOTR 用例;无需 big-data 数据量来替代时序验证。

    测试证据

    • go test ./pkg/tests/issues -run 'TestIssue29852ForwardCreate(NeighborSchedules|ReplacementGeneration)' -count=3:ok github.com/matrixorigin/matrixone/pkg/tests/issues 8.593s。
    • 已有回归源码

    测试结论

    测试通过。

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