Skip to content

[Bug]: optimizer: correlated scalar MAX scans unrelated task rows after decorrelation #28158

Closed

Description

@LeftHandCold

Is there an existing issue for the same bug?

  • I searched open and closed issues for correlated aggregate, scalar subquery, decorrelation and full-scan symptoms; no issue describes this plan regression.

Branch Name

v4.2.1 / 4.2-dev

Commit ID

d2393868a7aaa6343518d80849fe4696aa3577e9 (v4.2.1)

Other Environment Information

  • Workload: MOI Catalog Agent Runtime stream read
  • Environment: IDC QA, distributed MatrixOne
  • Observation date: 2026-09-04
  • Event table cardinality: approximately 3.16 million rows
  • Investigation was read-only; no production data was modified.

Actual Behavior

A scalar correlated MAX(event.seq) subquery is logically restricted by the outer task's (workspace_id, id), and the event table has the corresponding task key/index. On MatrixOne 4.2.1, EXPLAIN ANALYZE decorrelates the aggregate into a scan/aggregation across events belonging to unrelated tasks.

Query shape:

SELECT task.id,
       CASE WHEN task.state IN (...) THEN
         (SELECT MAX(final_event.seq)
            FROM agent_runtime_events AS final_event
           WHERE final_event.workspace_id = task.workspace_id
             AND final_event.task_id = task.id
             AND final_event.visible = TRUE
             AND final_event.a2a_state IN (...))
       ELSE NULL END AS latest_stream_final_seq
  FROM agent_runtime_tasks AS task
  LEFT JOIN agent_runtime_events AS next_event
    ON next_event.workspace_id = task.workspace_id
   AND next_event.task_id = task.id
   AND next_event.seq > ?
 WHERE task.workspace_id = ?
   AND task.id = ?
 ORDER BY next_event.seq;

Observed plan/runtime evidence:

  • Event table: approximately 3,156,626 rows.
  • Original correlated aggregate branch scanned 3,156,308 rows.
  • A semantically equivalent rewrite that first locates the target task and joins its events scanned 79 event rows and 79 index rows.
  • Same CN and same REPEATABLE READ transaction:
    • afterSeq=79: original 0.937390s, rewrite 0.372474s.
    • afterSeq=0: original 0.848336s, rewrite 0.486697s.
  • Both variants returned the same row counts and SHA-256 result digests.

This makes a point lookup's aggregate cost proportional to the global event table rather than the selected task.

Expected Behavior

After decorrelation, the optimizer must preserve the correlation predicates on (workspace_id, task_id) and choose a plan whose event scan is proportional to rows for the selected task. It must not aggregate unrelated tasks before applying the outer key.

Steps to Reproduce

  1. Create a task table keyed by (workspace_id, id).
  2. Create an event table containing (workspace_id, task_id, seq, visible, state) with an index beginning with (workspace_id, task_id).
  3. Insert millions of events across many tasks; leave approximately 79 events for the selected task.
  4. Execute the correlated query above with WHERE task.workspace_id=? AND task.id=?.
  5. Inspect EXPLAIN ANALYZE scan rows for the scalar MAX branch.
  6. Compare with this equivalent aggregate shape:
SELECT MAX(e.seq)
  FROM agent_runtime_tasks AS target
  JOIN agent_runtime_events AS e
    ON e.workspace_id = target.workspace_id
   AND e.task_id = target.id
 WHERE target.workspace_id = ?
   AND target.id = ?
   AND e.visible = TRUE
   AND e.a2a_state IN (...);

The original plan scans approximately the entire event table; the rewrite uses the target task key and scans only matching events.

Additional information

Confirmed code/evidence source

MOI applied an application-side equivalent SQL rewrite in:

The MOI unit test fixes the SQL shape and result mapping, but does not execute the MatrixOne optimizer and therefore is not a MatrixOne regression test.

Suggested MatrixOne validation

  • Add an optimizer/execution regression with high cross-task cardinality and a small selected task.
  • Assert result equivalence and inspect scan rows/plan shape so a global aggregate cannot silently return.
  • Cover both the scalar aggregate alone and the surrounding LEFT JOIN/CASE form.
  • Check current 4.2-dev and main; the production observation only proves the defect on v4.2.1 commit above.

Impact

MOI polls this query on the runtime stream path. A full event-table scan turns a point task read into repeated database work, increasing Catalog latency and MatrixOne CPU/I/O as event history grows. MOI has deployed the JOIN workaround, but other correlated aggregates can still trigger the optimizer defect.

Activity

  1. added
    kind/bug
    on Sep 4, 2026
  2. added
    severity/s0
    and removed
    severity/s0
    on Sep 4, 2026
  3. XuPeng-SH commented on Sep 7, 2026

    @XuPeng-SH
    Contributor

    已提交修复 PR:#28353,目标分支为 4.2-dev。

    Root cause

    相关 scalar aggregate 在 decorrelation 后会把关联列加入内层 aggregate 的 GROUP BY,但 aggregate 的输入仍可能独立于外层已经筛选出的 task。对于 workspace_id + task_id 点查,这会先扫描并分组大量无关 workspace/task 的事件,再把结果关联回目标 task;结果通常相同,但扫描量和延迟明显放大。

    修复

    • 仅对单个基表、完整主键等值点域启用优化;OR、范围、IN、部分主键、非键、派生/多表和无过滤场景保持原有计划。
    • 使用 duplicate-safe 的 SEMI key-domain join,避免普通 inner join 放大 COUNT/SUM/MAX 的输入。
    • 将已证明安全的外层主键点过滤复制到内层直接基表 scan,使常规索引选择能限制物理读取。
    • 只复制确定性谓词;计算型内层关联键、volatile/未知函数和 subquery 不触发对应复制,避免重复求值或改变语义。
    • 深拷贝表达式和 snapshot,并使用新 binding tag,避免修改原始计划或读视图。

    证据与验证

    在 100,000 条事件、目标任务仅 100 条相关记录的本地复现中,最终 aggregate 分支的事件表 scan 读取 100 行,task_event_key 索引域读取 100 行,进入 aggregate 的行数为 50;未复制 scan-level 点过滤时,aggregate 分支读取 100,000 行。

    最终提交已通过:

    CI 未等待,GitHub CI 负责最终平台矩阵验证。PR 合入后该 issue 可随 Fixes #28158 自动关闭。

  4. XuPeng-SH commented on Sep 7, 2026

    @XuPeng-SH
    Contributor

    补充 main 分支进展:已提交 #28355,目标分支为 main;此前的 #28353 目标为 4.2-dev。

    不能直接 cherry-pick #28353 到 main:两分支的 planner 已发生结构演进,实际在 flatten_subquery.go 和 query_builder.go 产生冲突。#28355 按 main 当前已有的 #26152 逻辑重新适配,保留已有的宽域 duplicate-safe SEMI rewrite,并只在完整主键点域时把已证明安全的过滤复制到 aggregate 输入 scan。

    main 版本已完成本地验证:pkg/sql/plan 全量测试、focused regression、go vet、构建,以及 mo-tester 分布式回归 11/11 通过;未等待远端 CI。

  5. added 2 commits that reference this issue on Sep 7, 2026
    588295f
    0b195e4
  6. Ariznawlll commented on Sep 8, 2026

    @Ariznawlll
    Collaborator

    测试环境:MatrixOne 最新 main f72ca9efbeb3a7c673701e4a135cc6670c33cfde,本地单机服务(MySQL 协议 6001)。

    测试步骤:

    1. 在本地单机环境创建带复合主键的 task 表和带 task 复合索引的 event 表。
    2. 写入多个 workspace/task 的事件,其中目标 task 只有 seq 1、7,其他 task 使用不同 workspace/task。
    3. 执行相关标量子查询 MAX(seq),确认结果只取目标 task 的事件。
    4. 在当前 main 执行专项测试 TestIssue28158|TestCorrelatedScalarAggregatePushdown。

    测试结果:目标 task 返回 seq=7,未混入其他 task 的 seq;优化器专项测试通过,执行耗时约 1.38s。

    结论:问题已修复。修复提交 #28355(0b195e4f5a23)已包含在当前 main;对应 MOTR 正确性用例已加入 PR #147(https://github.com/matrixorigin/motr/pull/147),MOTR 定向运行通过。

  7. added 3 commits that reference this issue on Sep 17, 2026
    4629b79
    c56d253
    b8257a3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s-1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions