Skip to content

WITH RECURSIVE CTE referencing recursive table twice crashes server (fatal error: stack overflow) #32795

Closed

Description

@Ariznawlll

[Bug Report] WITH RECURSIVE CTE referencing the recursive table twice causes server crash (fatal error: stack overflow)

Summary

A single WITH RECURSIVE statement that references the recursive table twice in the recursive member causes the whole mo-service process to crash with fatal error: stack overflow (exit code 2), instead of returning a semantic error like MySQL does.

The recursive descent happens in the plan builder: buildTable → bindCte → bindRecursiveCte → bindSelect → bindSelectClause → buildFrom → buildTable → ... loops forever until the goroutine stack exceeds the 1 GB limit.

This is a server-crashing (DoS-class) bug: any client able to run a recursive CTE can take down the whole MatrixOne instance.


Environment

Item Value
MatrixOne version 8.0.30-MatrixOne-v1.3.0 (development build)
Git commit 094c0b33bd9f0a37a76f242367c4ad6a3fa39ac8
Branch codex/32670-tenant-index-read (commit subject: "fix: allow tenant admin read-only index inspection", 2026-11-13)
Source repo https://github.com/matrixorigin/matrixone
OS / Arch macOS 14.5, darwin/arm64 (Apple M3, 16 GB)
Go toolchain go1.27.1-X:simd darwin/arm64
Client mysql CLI + PyMySQL (MySQL protocol, 127.0.0.1:6001)
Deployment single-node local launch: ./mo-service -launch ./etc/launch/launch.toml

Minimal Reproduction

Step 1 — start a standalone MatrixOne instance (single-node):

./mo-service -launch ./etc/launch/launch.toml

Step 2 — run this single statement. No database creation, no USE, no session variables needed — a bare query is enough:

mysql -h 127.0.0.1 -P 6001 -u dump -p111 -e \
  "WITH RECURSIVE qn AS (SELECT 1 FROM qn UNION ALL SELECT 1 FROM qn) SELECT * FROM qn;"

or as plain SQL:

WITH RECURSIVE qn AS (
    SELECT 1 FROM qn
    UNION ALL
    SELECT 1 FROM qn
)
SELECT * FROM qn;

Observed: the client immediately gets

ERROR 2013 (HY000): Lost connection to MySQL server during query

and the mo-service process terminates shortly after with exit code 2. The instance must be restarted manually; it does not recover on its own.

Verified with the stock mysql CLI too (not just the programmatic client), so the crash is client-independent:

$ mysql -h 127.0.0.1 -P 6001 -u dump -p111 -e "
  CREATE DATABASE IF NOT EXISTS d1; USE d1;
  WITH RECURSIVE qn AS (SELECT 1 FROM qn UNION ALL SELECT 1 FROM qn) SELECT * FROM qn;"
ERROR 2013 (HY000) at line 3: Lost connection to MySQL server during query
# mo-service then exits with code 2 (fatal error: stack overflow)

Expected Behavior (MySQL 8.0 reference)

MySQL rejects this statement with a semantic error (the recursive table may only be referenced once, and not in a subquery), keeping the server alive:

ERROR 3575 (HY000): In recursive query block of Recursive Common Table Expression 'qn',
the recursive table must be referenced only once, and not in any subquery.

MO already handles several other malformed recursive CTEs correctly (e.g. WITH RECURSIVE qn AS (SELECT 1 FROM qn) SELECT * FROM qn returns error 1064 with the proper message). The double reference case is the one that slips through validation and crashes.


Actual Behavior — Crash Log

runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0x... stack=[0x..., 0x...]
fatal error: stack overflow

runtime stack:
runtime.throw(...)
runtime.newstack()
runtime.morestack()

goroutine 4592 [running]:
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable(...)  query_builder.go:13772
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable(...)  query_builder.go:14403
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable(...)  query_builder.go:14348
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildFrom(...)   query_builder.go:13035
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).bindSelectClause(...) query_builder.go:9490
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).bindSelect(...)  query_builder.go:6741
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).bindRecursiveCte(...) query_builder.go:6050
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).bindCte(...)     query_builder.go:6318
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable(...)  query_builder.go:13865
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable(...)  query_builder.go:14403
github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable(...)  query_builder.go:14348
... (the same buildTable → bindCte → bindRecursiveCte → bindSelect → bindSelectClause → buildFrom → buildTable cycle repeats thousands of times until stack exhaustion)

Key cycle (package pkg/sql/plan, file query_builder.go):

buildTable (13865)
  → bindCte (6318)
    → bindRecursiveCte (6050)
      → bindSelect (6741)
        → bindSelectClause (9490)
          → buildFrom (13035)
            → buildTable (14348 / 14403)   // re-enters the same CTE
              → bindCte (6318)             // ... and loops again

Root-Cause Analysis

bindRecursiveCte (query_builder.go:6050) re-enters plan building for the recursive member. When the recursive table qn is referenced twice, the second reference re-triggers bindCte → bindRecursiveCte for the same, still-being-bound CTE. There is no "binding in progress / already-bound" guard, so the builder recurses on itself indefinitely instead of either:

  1. returning the "recursive table must be referenced only once" semantic error (the correct behavior), or
  2. recognizing the self-reference and stopping the recursion.

The fix should add a re-entrancy guard (mark the CTE as being bound and error out / short-circuit on a second entry) and/or enforce the single-reference rule before descending into bindRecursiveCte.


Additional Context

  • Discovered while running the upstream MySQL functional test suite (mysql-test/t/with_recursive.test, which --sources include/with_recursive.inc) against MatrixOne for compatibility comparison. The crashing statement is one of the early cases in that file.
  • The same crash reproduces both when the statement is run alone (minimal repro above) and as part of the full test sequence. Because the infinite recursion happens in a goroutine, the process sometimes dies a few seconds after the statement returns, which can make the trigger look non-deterministic — but the stack trace is always the same bindRecursiveCte cycle.
  • Other malformed recursive CTEs in the same file (self-reference without anchor, recursion before anchor, mutual recursion qn ↔ qn2) are rejected correctly; only the double-reference form crashes the server.

Severity

Critical / High — unauthenticated-by-design SQL input that reliably crashes the entire database process (availability impact, DoS).

Activity

  1. added
    kind/bug
    on Nov 16, 2026
  2. added theissue type on Nov 16, 2026
  3. added this to the MO-202611 milestone on Nov 16, 2026
  4. Ariznawlll commented on Nov 16, 2026

    @Ariznawlll
    CollaboratorAuthor

    Additional finding — this is a whole bug class, not a single statement.

    I fuzzed the recursive-CTE space around the original repro. The crash is triggered by any form in which the recursive table is referenced more than once inside the recursive member, regardless of syntax:

    Variant Result
    Normal recursion (single reference) ✅ works
    SELECT 1 FROM qn UNION ALL SELECT 1 FROM qn (2 refs) 💥 stack overflow
    recursive table referenced 3× (UNION ALL ×2) 💥 stack overflow
    2 refs with UNION (dedup) instead of UNION ALL 💥 stack overflow
    two CTEs each self-referencing twice 💥 stack overflow
    double-reference CTE nested inside a subquery 💥 stack overflow
    double-reference CTE inside INSERT INTO t WITH RECURSIVE ... 💥 stack overflow
    double-reference CTE on both sides of an outer UNION 💥 stack overflow
    self-join in recursive member (FROM qn JOIN qn q2 ON ...) ⚠️ rejected with 1064 unsupport multiple recursive table expr in recursive CTE (no crash)
    recursive table referenced in a WHERE subquery ⚠️ rejected with 1064 (no crash)
    column-count mismatch ⚠️ rejected with 1064 (no crash)

    Useful clue for the fix: the self-join case is already caught by an existing guard that returns unsupport multiple recursive table expr in recursive CTE. So MO does have a "multiple recursive table references" check — but it only covers some shapes (e.g. JOIN) and misses the UNION [ALL] double-reference path, which then falls into the unguarded bindRecursiveCte recursion and overflows the stack. Extending that existing single-reference check to the UNION/UNION ALL recursive-member path (before descending into bindRecursiveCte) should close the whole class.

  5. added a commit that references this issue on Nov 17, 2026
    27bb33d
  6. XuPeng-SH commented on Nov 17, 2026

    @XuPeng-SH
    Contributor

    QA 交接(不是验收通过)

    #32831 已于 2026-11-17 05:14 UTC 合入 main,merge SHA 27bb33d97b35c581b11775cb1ffbcbd41de35139。修复按 CTE declaration identity 拒绝 anchor 绑定期间对同一声明的重入,避免无限重复绑定;不是简单禁止所有多递归成员。合法递归、同名内层 CTE/别名、带 schema 的真实表和原有递归成员诊断保持各自语义。已核对完整 issue/PR 讨论、最终 approve 和五文件补丁,未见当前适用的已验证反例或未完成开发 follow-up。保持 open 交 QA,不作验收或自动 backport。

    证据与限制:本轮仅远端核对,未运行本地测试。作者在 f491aaab 加修复上报告 17/17 focused subtests、完整 planner 包(5045 顶层、17949 direct subtests)通过;真实服务将原语句拒绝为 1064,同连接后续查询与有限递归正常,公共 BVT 的 nometa/严格 metadata 各 3/3。这些是历史 source-bound 结果,不是最终 merge SHA 新实测。随后 rebase 到 e765c5fd 时五文件内容及 diff 不变,作者报告 111 包 incremental SCA 通过,以及另一个 prepared-time 目标 normal/race 各 19 RUN/PASS;该目标不替代 CTE 回归。最终评审复用冻结 head 的 UT/SCA/coverage/双 multi-CN BVT 成功状态,无新本地运行或原始逐测试 CI 日志;merge queue 最终记录 CI Required 成功。此前 DROP DATABASE/heartbeat timeout 没有被独立重现或宣称彻底修复,不当作本 CTE 修复的新反例。

    建议 QA 在此 SHA 或后继 main 上复测原语句及三臂 UNION ALL、UNION DISTINCT、多 CTE、derived/outer UNION、INSERT SELECT 等 anchor 自引用变体,确认返回错误且服务不崩溃;同时覆盖同连接与 compiler context 拒绝后复用、合法单/多递归成员、词法遮蔽、schema-qualified 表,以及 self-join/子查询/列数不匹配的既有错误。完整修复后的生产环境可用性、跨版本行为仍需验证;不将历史诊断文字中的“多次引用”笼统扩展为禁止合法递归。

  7. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    4.2-dev (e8fd84b, 2026-11-17 tip) is still affected by this crash.

    Verification setup:

    • Built mo-service from a fresh shallow clone of 4.2-dev at e8fd84b331f168eafd0ec28149b043eaebc7e39d (branch 4.2-dev, self-built with go1.26.5, macOS arm64).
    • Single-node launch (LOG/TN/CN on isolated ports), clean data dir, fresh bootstrap.
    • Confirmed the listening process is the built binary (lsof PID/binary path/cwd triple-checked) before running the repro.

    Minimal repro (same as the original report):

    WITH RECURSIVE qn AS (SELECT 1 FROM qn UNION ALL SELECT 1 FROM qn) SELECT * FROM qn;

    Result on 4.2-dev:

    github.com/matrixorigin/matrixone/pkg/sql/plan.seedNumericTableProjectionTypes  query_builder.go:4960
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildFrom       query_builder.go:4541
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable      query_builder.go:4249
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).bindCte         query_builder.go:4487
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).bindSelect      query_builder.go:9275
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).bindSelectClause query_builder.go:9695
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).getSelectCtx    query_builder.go:9644
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildFrom       query_builder.go:8739
    github.com/matrixorigin/matrixone/pkg/sql/plan.(*QueryBuilder).buildTable      query_builder.go:6689
    github.com/matrixone/pkg/sql/plan.(*QueryBuilder).seedNumericTableProjectionTypes query_builder.go:4767
    (buildFrom 4249 -> bindCte 4487 -> bindSelect 9275 ... repeating)
    

    So on 4.2-dev the anchor self-reference goes through the seedNumericTableProjectionTypes path added for grouped ENUM/SET numeric handling, which recurses into buildFrom -> buildTable -> bindCte -> bindSelect -> ... until the goroutine stack is exhausted.

    The fix in #32831 (reject recursive CTE anchor self-references, merged to main as 27bb33d) does not appear to have been backported to 4.2-dev: I don't see a backport PR, and the repro above still kills the process on the current 4.2-dev tip.

    Suggested follow-up: backport the anchor self-reference rejection from #32831 to 4.2-dev, or add the equivalent re-entrancy guard on the declaration identity in the 4.2 codebase (note the recursion path there includes seedNumericTableProjectionTypes, so the guard should cover bindCte re-entry during that seeding path too).

  8. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    Verification on main tip: fix confirmed effective (follow-up to the QA handoff plan).

    Verified on a self-built mo-service from main at 919c9fc32f (>= fix merge 27bb33d97b35c581b11775cb1ffbcbd41de35139, go1.27.1, macOS arm64, single-node launch, isolated ports, fresh bootstrap; listener binary/cwd/git_version triple-checked).

    Crash variants from the original report and the QA handoff matrix — all now rejected cleanly with 1064 SQL parser error: In the initial statement of Recursive Common Table Expression <name>, the recursive table must not ..., server stays up, and the same connection remains usable afterwards:

    • A0 original: WITH RECURSIVE qn AS (SELECT 1 FROM qn UNION ALL SELECT 1 FROM qn) SELECT * FROM qn
    • A1 three-arm UNION ALL anchor self-reference
    • A2 UNION DISTINCT anchor self-reference
    • A3 two CTEs each self-referencing in their own anchors
    • A4 anchor self-reference inside a nested subquery (WHERE 1 IN (SELECT 1 FROM qn))
    • A5 INSERT INTO sink WITH RECURSIVE qn AS (...) SELECT * FROM qn

    Negative controls (must keep working) — all pass:

    • B1 legal single-reference recursion with column list: WITH RECURSIVE seq(n) AS (...) → 10 rows, correct
    • B2 two independent legal CTEs referenced via scalar subqueries → both max values correct
    • B3 inner CTE with a distinct name nested inside another CTE → correct shadowing semantics (outer max 3, inner max 12)
    • B4 schema-qualified real table as anchor (cte_fix_verify.real_t) → recursion produces correct max
    • B5 recursive-member self-join keeps the existing diagnostic (unsupport multiple recursive table expr)
    • B6 bounded two-column recursion → max(gen) correct

    No hangs, no crashes, zero process restarts during the whole run. The rejection message and same-connection recoverability match what the QA handoff asked to verify.

    (Cross-reference: the same repro still kills 4.2-dev at e8fd84b331 via the seedNumericTableProjectionTypes path — see my previous comment; that remains a backport gap, not a fix failure.)

  9. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    Verified fixed on main tip — closing.

    Fix #32831 (merged as 27bb33d) verified effective on a self-built main@919c9fc32f:

    • All 6 anchor self-reference crash variants (original SQL, three-arm UNION ALL, UNION DISTINCT, two CTEs, nested-subquery anchor, INSERT ... SELECT) now return ERROR 1064 rejecting the anchor reference, with the server staying up and the same connection remaining usable.
    • All 6 legal-recursion negative controls (single-reference recursion, multiple CTEs, name shadowing, schema-qualified real table, recursive-member self-join diagnostic, bounded recursion) keep working — no over-blocking.
    • A regression case (issue_32795_recursive_cte_anchor_selfref) has been added to matrixorigin/motr (target-branch: main) covering all 12 scenarios with a recorded baseline.

    One open follow-up kept visible (not a fix defect): the fix has not been backported to 4.2-dev — the repro still kills 4.2-dev@e8fd84b3 via the seedNumericTableProjectionTypes path (see earlier comment with the full stack). Backport tracking continues in the comments above and can be referenced by the release team.

  10. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    Fix #32831 verified effective on main tip (919c9fc32f): all crash variants rejected with a clean 1064 error, legal recursion unaffected, regression case added to motr (target-branch: main). Closing as fixed on main; 4.2-dev backport gap documented in comments.

  11. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    Regression case landed in motr via matrixorigin/motr#355 (target-branch: main) — closes the loop on this issue's verification.

  12. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    重新打开:本 issue 存在“先关闭、后补 motr PR”的顺序问题。对应的 motr #355 于 2026-11-17 10:09 UTC 创建,晚于本 issue 的关闭时间,不符合“关闭前必须完成回归 PR”的要求。现恢复 Open。当前 #355 已包含本 issue 的用例,后续需核对该 PR 的完整验证与交付状态后,再统一给出关闭结论。

  13. Ariznawlll commented on Nov 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    QA 验收结论:main 通过;4.2-dev 原始崩溃仍可复现,保持 OPEN 转回研发

    1. 实际验证版本

    • main:7fc45a2be2424d887199c5949362855cbacfe30f,SQL 确认 git_version() 为该完整 SHA,version() = 8.0.30-MatrixOne-v1.3.0。祖先链包含 planner 修复 #32831(27bb33d97b35c581b11775cb1ffbcbd41de35139)和后续多成员递归执行修复 #32828(43addc16ba30c3e5a0feb11447078092a5fc3953)。
    • 4.2-dev:7400cae392e90fa94b8cf54dc8520c3c13647884,SQL 确认 git_version() 为该完整 SHA,version() = 8.0.30-MatrixOne-v4.2.9。该分支不包含 fix(plan): reject recursive CTE anchor self-references #32831 的修复 commit。
    • 两个实例均为本机隔离的单 LOG/TN/CN 部署,使用独立端口与数据目录;没有以 worktree HEAD 代替运行实例版本确认。

    2. main 实测:通过

    • 原始 anchor 重复引用,以及三臂 UNION ALL、UNION DISTINCT、多 CTE、derived、outer UNION、INSERT SELECT 等变体均返回 1064 错误,不再触发 stack overflow;同一连接可继续执行 SQL,测试后服务仍存活。
    • 合法单递归成员、多递归成员、词法遮蔽、schema-qualified 真实表、self-join/子查询/列数不匹配诊断及 SQL PREPARE/EXECUTE/DEALLOCATE 均符合预期。被拒绝的 INSERT SELECT 目标表行数为 0,合法 prepared 递归返回 sum(n)=6。
    • 在较早的 main 基线 e1160015bb5895c1677d5fc1496c4bee440592b3(含 fix(plan): reject recursive CTE anchor self-references #32831、不含 [Bug] Fix multi-member recursive CTE frontier handling #32828)上,原始 crash 语句已被拒绝,但以下合法双递归成员超过 120 秒未完成,服务未崩溃:
      WITH RECURSIVE seq(n) AS (
        SELECT 1
        UNION ALL SELECT n + 1 FROM seq WHERE n < 5
        UNION ALL SELECT n + 1 FROM seq WHERE n < 3
      ) SELECT sum(n) FROM seq;
      在新 main(包含 [Bug] Fix multi-member recursive CTE frontier handling #32828)上该语句返回 sum(n)=53。因此这是后续递归 frontier 执行问题的版本边界,不能误报为原始 stack overflow 未修复。

    3. 4.2-dev 实测:失败

    在最新 4.2-dev 上重新执行原始语句:

    WITH RECURSIVE qn AS (
      SELECT 1 FROM qn UNION ALL SELECT 1 FROM qn
    ) SELECT * FROM qn;

    结果:客户端返回 ERROR 2013 (Lost connection to MySQL server during query);随后 SQL 无法继续连接,mo-service 以 exit 2 退出。日志明确包含:

    runtime: goroutine stack exceeds 1000000000-byte limit
    fatal error: stack overflow
    

    递归路径仍包含 seedNumericTableProjectionTypes、bindCte 和 bindRecursiveCte。这不是脚本错误或旧实例误判,而是 4.2-dev 上可重复的产品反例。请研发将 #32831 的 declaration-identity 重入防护适配/backport 到 4.2-dev,并覆盖 seeding 路径;在该分支通过前不应按全分支验收关闭。

    4. 回归与白盒证据

    未验证:多 CN、race、完整 binary prepared 协议、长稳以及 4.2-dev 修复后的全矩阵。当前保持 OPEN 的唯一阻塞是上述 4.2-dev 原始崩溃;main 的 planner 修复及后续合法递归执行修复已有实测证据。

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

Metadata

Metadata

Labels

kind/bug

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions