Skip to content

[Bug]: correlated subquery LIMIT is applied globally across outer groups #26816

Closed

Description

@Ariznawlll

Description

A correlated subquery with LIMIT 1 is decorrelated into a join while the limit remains global on the inner relation. The bug affects scalar, EXISTS, and NOT EXISTS forms, including correlated subqueries used by UPDATE and DELETE. With multiple correlated groups, only one group reaches the join: scalar queries silently return NULL for other non-empty groups, EXISTS drops them, NOT EXISTS incorrectly treats them as empty, and DML can persist wrong values or delete the wrong rows. Adding ORDER BY ... DESC selects the single global maximum instead of the maximum per correlated group.

Environment

  • Branch: main
  • Commit: 08770e1beeb23239c91165492f2fe85243a3c66a
  • Deployment: local standalone mo-service, 1 CN / 1 TN / 1 Log service, MySQL text protocol
  • Test date: 2026-08-09

Steps to reproduce

DROP DATABASE IF EXISTS correlated_global_limit;
CREATE DATABASE correlated_global_limit;
USE correlated_global_limit;

CREATE TABLE parent_t(id INT PRIMARY KEY);
CREATE TABLE child_t(id INT PRIMARY KEY, parent_id INT, amount INT);
INSERT INTO parent_t VALUES(1),(2),(3);
INSERT INTO child_t VALUES
  (1,1,10),(2,1,20),
  (3,2,30),(4,2,40),
  (5,3,50),(6,3,60);

SELECT p.id,
       (SELECT c.amount
        FROM child_t c
        WHERE c.parent_id = p.id
        ORDER BY c.amount DESC
        LIMIT 1) AS ordered_limit
FROM parent_t p
ORDER BY p.id;

-- The same global LIMIT bug affects existential forms.
INSERT INTO parent_t VALUES (4); -- empty control group
SELECT p.id
FROM parent_t p
WHERE EXISTS (
  SELECT 1 FROM child_t c WHERE c.parent_id = p.id LIMIT 1
)
ORDER BY p.id;

SELECT p.id
FROM parent_t p
WHERE NOT EXISTS (
  SELECT 1 FROM child_t c WHERE c.parent_id = p.id LIMIT 1
)
ORDER BY p.id;

Actual behavior

Only the group containing the global maximum receives a value:

id  ordered_limit
1   NULL
2   NULL
3   60

The same failure exists without ORDER BY: only the first global inner row is retained, so the result is 1|10, 2|NULL, 3|NULL.

For EXISTS ... LIMIT 1, the actual result contains only parent 1 instead of 1,2,3. With an additional empty parent 4, NOT EXISTS ... LIMIT 1 incorrectly returns 2,3,4 instead of only 4.

Using the ordered scalar subquery in UPDATE parent_t SET top_amount=(...) persists NULL,NULL,60 instead of 20,40,60. This DML result was also stable in 3/3 fresh databases.

The error is destructive in DELETE: DELETE ... WHERE EXISTS (... LIMIT 1) deletes only parent 1 instead of all non-empty parents 1,2,3; DELETE ... WHERE NOT EXISTS (... LIMIT 1) deletes 2,3,4 instead of only the empty parent 4. Both variants reproduced 3/3.

EXPLAIN confirms that Sort Limit: 1 is executed on the complete child_t input before the correlation join:

Join
  Join Type: LEFT
  Join Cond: (p.id = c.parent_id)
  -> Table Scan on parent_t
  -> Sort
       Sort Key: c.amount DESC
       Limit: 1
       -> Table Scan on child_t

Expected behavior

LIMIT 1 must be applied independently for every correlated parent_id. The deterministic query above must return:

id  ordered_limit
1   20
2   40
3   60

EXISTS ... LIMIT 1 must return all three non-empty parent groups, and NOT EXISTS ... LIMIT 1 must return only genuinely empty groups.

Stability and controls

  • Reproducer: 3/3 runs returned 1|NULL, 2|NULL, 3|60.
  • EXISTS/NOT EXISTS: 3/3 runs returned only 1 for EXISTS and incorrectly returned 2,3,4 for NOT EXISTS; expected 1,2,3 and 4 respectively.
  • Correlated UPDATE: 3/3 autocommit runs persisted NULL,NULL,60 instead of 20,40,60.
  • Correlated DELETE: 3/3 EXISTS runs left 2,3,4 instead of only 4; 3/3 NOT EXISTS runs left only 1 instead of 1,2,3.
  • Transaction control: executing the same incorrect UPDATE inside an explicit transaction and rolling back restored all three target values to NULL in 3/3 runs; transaction rollback itself remains atomic.
  • Aggregate control: replacing the scalar body with MAX(c.amount) returned 20, 40, 60 in every run.
  • Window control: an explicit ROW_NUMBER() OVER (PARTITION BY parent_id ORDER BY amount DESC) rewrite returned 20, 40, 60 in every run.
  • Uncorrelated control: SELECT (SELECT amount FROM child_t WHERE parent_id=1 ORDER BY amount DESC LIMIT 1) returned 20.
  • Data check: this is read-only; after every run child_t remained at 6 rows with SUM(amount)=210.
  • Session/service check: subsequent statements completed normally; no panic, restart, or hang was observed.

Evidence

The minimal reproducer, controls, and EXPLAIN were executed against the exact commit above. The wrong result and the global right-side Limit: 1 plan were stable across three complete runs.

Code analysis

Confirmed planner path: pkg/sql/plan/flatten_subquery.go pulls the correlated predicate out of the scalar subquery, treats the limited subquery as hasSingleRow, and builds a LEFT join using the original right subtree. The EXPLAIN output proves that the right subtree still contains the global Sort/Limit below the join.

Hypothesis: after predicate pull-up, a correlated LIMIT cannot remain a global right-side limit. Scalar, SEMI, and ANTI joins all need per-correlation-key limiting semantics or dependent evaluation that preserves the subquery result independently for every outer key.

Regression coverage

After the product fix, add a distributed BVT under test/distributed/cases/subquery/ covering:

  • three non-empty correlated groups with ORDER BY ... DESC LIMIT 1;
  • plain LIMIT 1 and an empty outer group;
  • EXISTS and NOT EXISTS with multiple non-empty groups plus one empty group;
  • correlated scalar UPDATE, with both autocommit result correctness and explicit rollback state;
  • correlated DELETE with both EXISTS and NOT EXISTS predicates;
  • NULL inner values and deterministic tie-breaking;
  • aggregate/window equivalents as result controls.

A focused planner unit test should also assert that the decorrelated plan does not leave a global LIMIT 1 below the correlation join.

Related

测试版本

  • 分支:main
  • commit:08770e1beeb23239c91165492f2fe85243a3c66a
  • 部署方式:本地单机 mo-service,1 CN / 1 TN / 1 Log service,MySQL text protocol
  • 测试日期:2026-08-09

原问题验证

最小复现连续执行 3 次。相关 ORDER BY amount DESC LIMIT 1 每次均只为全局最大值所在的第三组返回 60,前两组错误返回 NULL;预期是 20、40、60。同根因的 EXISTS/NOT EXISTS 也连续 3 次返回错行。

Happy Path 覆盖

  1. 非相关 ORDER BY ... LIMIT 1 连续返回正确值 20。
  2. 相关 MAX(amount) 和显式按 parent_id 分区的窗口改写均连续返回 20、40、60。
  3. 单个相关组正常返回一行。

Unhappy Path 覆盖

  1. 多个非空相关组:普通 LIMIT 1 只保留第一组,其余非空组错误返回 NULL。
  2. 多个非空相关组加排序:只保留全局 Top-1 所在组,而不是每组 Top-1。
  3. 空相关组:正常返回 NULL,用于区分合法空集与本问题的非空组丢失。
  4. 内层含 NULL:不影响普通排序对照,但相关路径仍受全局 LIMIT 错误影响。
  5. EXISTS/NOT EXISTS:3 个非空父组和 1 个空父组时,EXISTS 错误只返回第 1 组,NOT EXISTS 错误返回第 2、3、4 组。
  6. 相关 UPDATE:连续 3 次把目标列写成 NULL,NULL,60,预期为 20,40,60;说明该错误可持久化错数据。
  7. 回滚边界:同一 UPDATE 放入显式事务后执行 ROLLBACK,连续 3 次均恢复为 NULL,NULL,NULL,事务回滚本身保持原子性。
  8. 相关 DELETE:EXISTS 连续 3 次只删除第 1 组,NOT EXISTS 连续 3 次错误删除第 2、3、4 组,均会持久化误删结果。
  9. 失败后状态:只读复现中源表始终为 6 行、SUM(amount)=210,连接和服务可继续使用。

白盒验证

EXPLAIN 稳定显示相关谓词已变成 LEFT/SEMI/ANTI JOIN 条件,但 Limit 1 仍位于整个右侧 child_t 扫描之上、JOIN 之下,直接证明 LIMIT 被全局执行。未做故障注入;该错误可由公开 SQL 黑盒稳定触发。

回归测试

当前产品仍返回错误数据,因此未把失败结果固化为回归基线。修复后应在 test/distributed/cases/subquery/ 增加 BVT,并补 planner plan-shape UT。

测试证据

保留了最小 SQL、3 轮完整输出、无 LIMIT 的聚合/窗口对照,以及显示全局 Limit: 1 的 EXPLAIN 计划。

测试结论

测试不通过。

Activity

  1. added this to the MO-202608 milestone on Aug 9, 2026
  2. added
    kind/bug
    on Aug 9, 2026
  3. added theissue type on Aug 9, 2026
  4. changed the title [-][Bug]: correlated scalar LIMIT is applied globally across outer groups[/-] [+][Bug]: correlated subquery LIMIT is applied globally across outer groups[/+] on Aug 9, 2026
  5. added
    severity/s0
    and removed on Aug 9, 2026
  6. assigned and unassigned on Aug 11, 2026
  7. Ariznawlll commented on Aug 12, 2026

    @Ariznawlll
    CollaboratorAuthor

    测试版本

    • 分支:main
    • commit:ca845354162ca2b01feb391d7b5b6e029c609420
    • 部署方式:本地单机 mo-service,1 CN / 1 TN / 1 Log service,MySQL text protocol
    • 测试日期:2026-08-12

    原问题验证

    在最新 main 上对多个非空 outer group 执行相关 ORDER BY ... LIMIT 1。每个 group 分别返回自己的 Top-1(20、40、60),不再只保留全局最大值所在组;EXISTS/NOT EXISTS 和相关 DML 结果也正确,连续 3 轮一致。

    Happy Path 覆盖

    1. ordered scalar、OFFSET 1、NULL-safe <=>、LIMIT 0 均返回精确结果。
    2. EXISTS 返回 1/2/3,NOT EXISTS 仅返回空组 4。
    3. MAX、显式 ROW_NUMBER() OVER(PARTITION BY ...) 和非相关 LIMIT 对照与相关结果一致。
    4. UPDATE 持久化每组 Top-1;DELETE EXISTS/NOT EXISTS 仅删除正确集合。

    Unhappy Path 覆盖

    本问题由合法相关子查询触发,不涉及应拒绝的非法 SQL。高风险边界已覆盖空相关组、NULL inner value、并列 amount 的确定性 tie-break、LIMIT 0、OFFSET、显式事务 ROLLBACK;回滚后值恢复,child 源表仍为 9 行、SUM(amount)=320,会话可继续执行。

    白盒验证

    未做故障注入;公开 SQL 已覆盖 scalar、SEMI/ANTI 和 DML decorrelation 路径。本轮以结果正确性、持久化和回滚原子性为准。

    回归测试

    已加入 motr PR #106 的 correlated LIMIT 用例,连续 3 轮稳定通过。

    测试证据

    motr PR #106;result 包含 scalar/EXISTS/NOT EXISTS、UPDATE/ROLLBACK、两类 DELETE 和源数据完整性。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions