Skip to content

[Bug]: Temporary-table alias maps must use unambiguous keys and retire stale aliases #30583

Closed

Description

@iamlinjunhong

Additional consolidated scope

The session temporary-table alias map must identify (database, alias) pairs without collisions and retire mappings when their physical table is already gone. These are separate failure paths in the same per-session alias maps: an ambiguous composite key can resolve to another object's identity, while a missing physical table can leave a stale alias after DROP TEMPORARY TABLE IF EXISTS reports success.

Additional acceptance criteria

  • Names such as database x, alias y.t and database x.y, alias t remain distinct across create, lookup, drop, and recreate.
  • If another session drops the database containing a temporary table, DROP TEMPORARY TABLE IF EXISTS retires the owner's stale alias; recreation and subsequent DML succeed.
  • Verify forward/reverse/identity maps remain consistent for dotted names and missing physical tables.

Additional reports

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

Consolidated tracking scope

Track the duplicate stale-alias report triggered when another session drops the database containing a live session temporary table. The linked reports are retained as separate reproductions where they exercise different code paths. Closing a linked issue is an administrative consolidation only; no fix is claimed here.

Acceptance criteria

  • After the backing database is dropped, DROP TEMPORARY TABLE IF EXISTS completes without leaving an unusable alias.
  • The session can create, resolve, and drop a new temporary table with the same alias afterward.
  • Keep this cleanup path separate from cross-session physical-name access and orphan-GC defects.

Included reports

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

Original canonical report (preserved verbatim)

Is there an existing issue for the same bug?

Checked the issues in duplicates_checked. #27042 (CLOSED) is a different trigger with a different root cause: a failing CREATE TEMPORARY TABLE ... CLONE leaving a ghost alias; this report is about an EXISTING, fully working temporary table whose physical storage is legitimately destroyed by another session's DROP DATABASE, after which the DROP TEMPORARY TABLE IF EXISTS cleanup path never runs. #30495/#30496/#30507 cover cross-session physical-name access and orphan GC, not this alias-cleanup path. None of them matches.

Branch Name: main (workspace detached HEAD)
Commit ID: 75ff736
Other Environment Information:

  • Hardware: Apple Silicon (arm64), 32GB
  • OS: macOS 15.7 (darwin/arm64)
  • Others: standalone mo-service launched with ./mo-service -launch ./.loom-test/launch/launch.toml (launch files derived from etc/launch with every port shifted by LOOM_TEST_PORT_OFFSET=20000: e.g. [cn.frontend] port = 26001, log-service 52000s, cn port-base 38000, tn port-base 39000, status-port 27001; data dirs under .loom-test/). Client: mysql CLI Ver 9.7.1; reference server: MySQL 8.0.46 (Homebrew [email protected], port 23306).

Actual Behavior

MatrixOne implements session temporary tables as persistent physical tables (__mo_tmp_<session>_<db>_<alias>) plus a per-session alias map. When another session drops the database, the physical table is destroyed with it (this part is recorded MatrixOne behavior - see test/distributed/cases/temporary/temporary_table_limitation.result, which answers the same-session variant with Unknown database test_temp_db). The owning session is left with a stale alias, and the state is then self-contradictory and unrecoverable:

  1. DROP TEMPORARY TABLE IF EXISTS tst returns success (OK) but does NOT remove the session alias;
  2. CREATE TEMPORARY TABLE tst(...) then fails forever with ERROR 1050 (42S01): table tst already exists;
  3. INSERT INTO tst values(...) / SELECT ... FROM tst fail with ERROR 1146 (42S02): no such table loomr.tst.

The same session simultaneously gets "already exists" and "does not exist" for the same name. The only in-session workarounds are picking a different table name or disconnecting.

Expected Behavior

After DROP TEMPORARY TABLE IF EXISTS tst returns success in that session, the alias tst must be released so that CREATE TEMPORARY TABLE tst(...) succeeds again and the following INSERT/SELECT work - exactly what MySQL 8.0 does with the identical two-session reproduction (evidence below: A_recreated | 1, no errors).

The MatrixOne-side grounding is its own alias model: the user-visible object named tst IS the session alias (the physical name is an internal detail). A DROP TEMPORARY that reports success must therefore at minimum retire the alias; that is exactly what the normal path does via RetireTemporaryTable -> RemoveTempTableByRealName (pkg/frontend/session.go:944). The bug is that this cleanup is skipped when the physical relation is already gone.

Steps to Reproduce

Reproduced with the script below (run as-is; it opens session A on a fifo, runs session B inline, then drives session A again). Only the two sessions' overlap matters; two interactive mysql consoles in the same order work identically.

#!/bin/bash
# Two overlapping mysql sessions. Session A stays open (reads from a fifo);
# session B drops and recreates the database that hosts A's temporary table;
# then session A drops its temp table and tries to re-create it.
M="mysql -h 127.0.0.1 -P 26001 -uroot -p111 --protocol=tcp --default-character-set=utf8mb4 --table --force"
rm -f /tmp/loom_a.in /tmp/loom_a.out; mkfifo /tmp/loom_a.in
$M < /tmp/loom_a.in > /tmp/loom_a.out 2>&1 &
APID=$!
exec 3>/tmp/loom_a.in
echo "drop database if exists loomR; create database loomR; use loomR; create temporary table tst(a int primary key, b int); insert into tst values (1,100); select 'A_ready' as m, count(*) as c from tst;" >&3
sleep 2
$M -e "drop database loomR; create database loomR;"
echo "use loomR; drop temporary table if exists tst; select 'A_after_drop_tmp' as m; create temporary table tst(a int); insert into tst values (7); select 'A_recreated' as m, count(*) as c from tst;" >&3
sleep 2
exec 3>&-; wait $APID
cat /tmp/loom_a.out

Expected (and verified on MySQL 8.0.46 with the same script, only connection params changed to -P 23306 -uroot): the last SELECT prints A_recreated | 1.
Actual (MatrixOne): ERROR 1050 ... table tst already exists, ERROR 1146 ... no such table loomr.tst, ERROR 1146 ... table "tst" does not exist - the name stays wedged for the whole session.

Additional information

Root cause is in the DROP TEMPORARY TABLE executor (pkg/sql/compile/ddl.go, dropTable flow):

  1. The alias resolves fine: session.GetTempTable(dbName, tblName) rewrites tst to its physical __mo_tmp_... name (ddl.go:4698-4707).
  2. The physical relation is gone (destroyed by the other session's DROP DATABASE), so dbSource.Relation(...) fails. With GetIfExists() the code returns nil immediately - ddl.go:4756-4762: if rel == nil { if rel, err = dbSource.Relation(...); err != nil { if qry.GetIfExists() { return nil }; return err } }.
  3. Because of that early return, the if isTemp cleanup block at ddl.go:4764-4773 (temporaryRetire.add(...) / owner.RetireTemporaryTable(dbName, originTableName, tblName, indexes)) never executes, so the session alias map (ses.tempTables / tempTablesRev, pkg/frontend/session.go:761-813) keeps the stale mapping.
  4. The next CREATE TEMPORARY TABLE tst hits the alias-exists check in createSessionTemporaryTable (pkg/sql/compile/temporary_ddl.go:99-104) and returns moerr.NewTableAlreadyExists (ERROR 1050). DML that resolves the alias then targets a physical table that no longer exists (ERROR 1146).

Without IF EXISTS the same early-return problem exists one line below (return err), and the alias is still not cleaned either.

Suggested fix (recommendation): in the temporary-table branch of the drop path, treat the alias as the object being dropped - when the physical relation is missing but the session alias exists, still retire the alias mapping (owner.RetireTemporaryTable / session RemoveTempTableByRealName) and return success for IF EXISTS; for the non-IF-EXISTS form, clean the alias as well and keep returning the "no such table" error (the table is genuinely absent). Healthy-table drops keep the existing retire path unchanged, so no existing data or behavior is affected - this only changes the branch where the mapping would otherwise be left dangling.

Related observations kept out of scope of this report (single root cause per report): the DROP DATABASE itself legitimately destroying another session's temp physical (recorded MatrixOne behavior, see temporary_table_limitation.result), and the session's current-database pointer being reset to none after the drop (cosmetic error-text difference).

Full reproduction, exactly as Loom ran it
#!/bin/bash
# Two overlapping mysql sessions against MO. Reproduced verbatim with:
#   bash repro_stale_alias.sh            # MatrixOne (port 26001, root/111)
#   bash repro_stale_alias_mysql80.sh    # MySQL 8.0 reference (port 23306, root, empty password)
# (the *_mysql80.sh variant is this same script with the M= line changed to -P 23306 -uroot)
M="mysql -h 127.0.0.1 -P 26001 -uroot -p111 --protocol=tcp --default-character-set=utf8mb4 --table --force"
rm -f /tmp/loom_a.in /tmp/loom_a.out; mkfifo /tmp/loom_a.in
$M < /tmp/loom_a.in > /tmp/loom_a.out 2>&1 &
APID=$!
exec 3>/tmp/loom_a.in
echo "drop database if exists loomR; create database loomR; use loomR; create temporary table tst(a int primary key, b int); insert into tst values (1,100); select 'A_ready' as m, count(*) as c from tst;" >&3
sleep 2
$M -e "drop database loomR; create database loomR;"
echo "use loomR; drop temporary table if exists tst; select 'A_after_drop_tmp' as m; create temporary table tst(a int); insert into tst values (7); select 'A_recreated' as m, count(*) as c from tst;" >&3
sleep 2
exec 3>&-; wait $APID
cat /tmp/loom_a.out

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

Activity

  1. added
    kind/bug
    on Oct 19, 2026
  2. changed the title [-][Bug]: DROP TEMPORARY TABLE IF EXISTS leaves a stale alias once the temp table's database was dropped[/-] [+][Bug]: DROP TEMPORARY TABLE IF EXISTS must clear stale aliases after its backing database is dropped[/+] on Oct 22, 2026
  3. changed the title [-][Bug]: DROP TEMPORARY TABLE IF EXISTS must clear stale aliases after its backing database is dropped[/-] [+][Bug]: Temporary-table alias maps must use unambiguous keys and retire stale aliases[/+] on Oct 22, 2026
  4. XuPeng-SH commented on Oct 23, 2026

    @XuPeng-SH
    Contributor

    QA follow-up for PR #30864 (head e96252d978fcbc512ea41a86df4c58435ca80ded)

    I independently inspected the exact-head source and CI evidence. The newly added fallback in pkg/frontend/temporary_ddl.go:104-117 can evict unrelated temporary aliases in the same session/database when the dropped root has no generation component:

    • pkg/sql/compile/temporary_ddl.go falls back to defines.GenTempTableName(sessionID, db, alias) when the session-temporary-DDL owner is not admitted (including c.isInternal / executor transactions and protocol versions below MORPCVersion55).
    • On a missing relation, pkg/sql/compile/ddl.go calls RetireTemporaryTable(..., nil). For a generationless name, trimming the root alias leaves the shared __mo_tmp_<session>_<db>_ prefix; the loop then removes every same-db entry matching it from the forward/reverse/identity maps.

    The exact-head MatrixOne ALL CI run 39784391770 independently exhibits a related temporary-table regression: the pessimistic multi-CN BVT fails at test/distributed/cases/git4data/clone/temporary_table_clone.sql:174, DROP TEMPORARY TABLE temp_src, with no such table clone_temp_target.temp_src (165/166 statements pass in that file). The required check and coverage merge also fail downstream of the standalone BVT failure; UT, coverage producer, SCA, and Compose BVT jobs pass. I did not run the MatrixOne harness locally.

    Please restrict prefix cleanup to roots that are provably generation-scoped, or record explicit root-to-index ownership so cleanup removes only that root's children. Add regression coverage with at least two unrelated temporary roots in one database, covering the generationless internal/legacy path and missing-root retirement. Keeping this issue open; no tester handoff until the fix is validated.

  5. added a commit that references this issue on Oct 25, 2026
    aeaa273
  6. added
    ai-easy
    on Oct 25, 2026
  7. Ariznawlll commented on Oct 26, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:官方 main

    • commit:5fe08a3307e246e1ab9951ab690b50557af0f509;隔离构建的 mo-service 构建信息为此完整 SHA 且 vcs.modified=false

    • 部署方式:macOS arm64;独立数据目录,1 LogService、1 TN、2 CN(26101/26102)及本地 MatrixOne Proxy(26001),无共享 TKE

    • 测试日期:2026-10-26

    • 对应研发修复:PR #30864 已 MERGED,merge commit 在上述官方 main SHA 祖先链中。

    原问题验证

    同一会话创建 db_x.y.t 与 db_x.y.t 两张临时表,分别读出 (1,11)、(2,22);删除前者不影响后者,重建前者后读出 (3,33)。另由 peer 删除含 live 临时表的数据库,owner 的 DROP TEMPORARY TABLE IF EXISTS 清理旧别名,重建数据库和同名临时表后读出 7。三组新库 3/3,MOTR 重复后 9/9。

    Happy Path 覆盖

    1. 带点名称的 create/lookup/drop/recreate 相互独立;旧别名退休后新建与 DML 正常。

    Unhappy Path 覆盖

    1. peer 删除数据库制造缺失物理表,owner 的 IF EXISTS 清理后没有残留映射污染;所有测试数据库在 finally 清理。

    白盒验证

    本次以真实 MySQL 协议和 SQL 产品路径验收;未额外运行 Go UT/-race,不以代码审查代替运行结果。

    回归测试

    已加入 MOTR #278 的 script/14_issue_regression/issue_20261026_recent_assigned_sql.py 和配对 .out。本地 MOTR 定向 --repeat 3 成功 3/3;每次脚本在三组独立数据库重复本 issue 断言,因此本 issue 共 9/9。完整 MOTR suite 与远端 CI 未运行,不能声称全套通过。

    测试证据

    MOTR #278 的回归脚本;定向运行目录 /private/tmp/mo-qa-new-20261026-ROza73/motr-278/var/log/run-1792982597562506000;脚本以精确值/行数断言,失败即退出非零。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

ai-easykind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions