Skip to content

[Optimizer] TPCH Q15 executes the same multi-reference CTE twice #26131

Closed

Description

@XuPeng-SH

Problem

The canonical TPCH Q15 shape defines q15_revenue0 once but references it both in the supplier join and in the scalar MAX(total_revenue) subquery. MatrixOne inlines and fully executes the CTE twice, including two full scans and two identical grouped aggregates over lineitem.

Reproduction

Environment: local standalone MatrixOne at commit 9c2e84ad5c, TPCH SF10.

with q15_revenue0 as (
  select l_suppkey as supplier_no,
         sum(l_extendedprice * (1 - l_discount)) as total_revenue
  from lineitem
  where l_shipdate >= date '1995-12-01'
    and l_shipdate < date '1995-12-01' + interval '3' month
  group by l_suppkey
)
select s_suppkey, s_name, s_address, s_phone, total_revenue
from supplier, q15_revenue0
where s_suppkey = supplier_no
  and total_revenue = (select max(total_revenue) from q15_revenue0)
order by s_suppkey;

EXPLAIN ANALYZE contains two independent copies of the same subtree. Each copy:

  • scans all 59,986,052 lineitem rows / 7,323 blocks
  • applies the same three-month date filter and outputs 2,265,119 rows
  • groups by l_suppkey and outputs the same 100,000 groups
  • consumes about 1.34 GiB input and 83.81 MiB scan memory

Measured cumulative operator data:

  • first scan: 670 ms; grouped aggregate: 1,143 ms; aggregate memory: 71.34 MiB
  • second scan: 678 ms; grouped aggregate: 558 ms; aggregate memory: 71.34 MiB

The second copy exists only to calculate MAX(total_revenue) from the same CTE result.

Expected behavior

For a deterministic CTE referenced multiple times, the optimizer should cost alternatives and reuse/materialize the result when that is cheaper than recomputation. Q15 should calculate the 100,000-row revenue relation once and feed both consumers from it.

Possible implementations include shared CTE materialization, common-subplan reuse, or a Q15-equivalent rewrite that computes the maximum from the already-produced revenue stream.

Please add a plan-shape regression test that verifies the base lineitem aggregate is not duplicated for this multi-reference CTE.

Activity

  1. added theissue type on Jul 24, 2026
  2. added this to the MO-202607 milestone on Jul 24, 2026
  3. VioletQwQ-0 commented on Jul 31, 2026

    @VioletQwQ-0
    Collaborator

    PR #26426 merged as b2aec782dc16717ee38c53d2c5961481781b2882 from final PR head 24f17f687e78e2a0b765cfca462b90fe9f442bdd.

    QA Decision

    • required: yes
    • reason: this changes user-visible multi-reference CTE planning and distributed execution, including multi-CN remote producer topology, query cancellation/cleanup, and bounded materialized spill resources.
    • production_entrypoint: TPCH SF10 Q15 on a multi-CN deployment, where one eligible CTE producer is consumed by the supplier join and the scalar MAX(total_revenue) subquery.
    • automated_terminal_coverage: final-head MatrixOne CI passed UT, SCA, coverage, Proxy/Pessimistic BVT, and the exact-head TKE check-in run passed TPCH10G, SSB, SYSBENCH, and TPCC. Focused planner/compile/materialized tests cover one producer, two readers, per-CN producer grouping, cancellation, spill admission, resource cleanup, and reuse.
    • remaining_validation: verify the final merged main build through both CN entry points, including plan shape, cancellation/reuse, spill limits, and stable-host performance.

    Existing local evidence on the earlier PR head d782957e37a5b46af957609b7edce03640c2379a:

    • stock 1 Log + 1 TN + 2 CN topology, tested independently through both CN ports
    • both entries returned supplier 33987, revenue 2296670.4443
    • cardinalities: lineitem 59,986,052, date filter 2,265,119, grouped suppliers 100,000
    • EXPLAIN ANALYZE showed one scan (59,986,052 -> 2,265,119), one grouped SUM (2,265,119 -> 100,000), and two Sink Scan consumers of the same producer
    • 120 ms client cancellation disappeared from the other CN's process list within 1 second; the immediate rerun succeeded
    • all clusters exited cleanly and released their ports

    The final head additionally includes f26b7629d74211ce916206d23af34bc1536d5ee0, which bounds materialized CTE spill memory, disk, and file-descriptor resources. The earlier local A/B/A therefore does not replace final-head QA.

    QA scenarios on merged main:

    1. Run TPCH SF10 Q15 through CN1 and CN2 independently; both must return supplier 33987 and revenue 2296670.4443.
    2. Confirm EXPLAIN/EXPLAIN ANALYZE has exactly one lineitem scan/filter/grouped-SUM producer and two Sink Scan consumers of that producer; the second consumer must feed MAX(total_revenue).
    3. Cancel Q15 while running, inspect it from the other CN, and verify it disappears promptly with no residual pipeline; rerun immediately and verify the correct result.
    4. Exercise a constrained spill limit so materialized overflow either succeeds within the admitted budget or fails cleanly before unbounded allocation/file growth; after completion or failure, memory, spill bytes, and file-descriptor charges must be released.
    5. On a stable or dedicated host, compare the merged implementation against the inline-CTE baseline. Report correctness and plan shape regardless of timing; publish a performance percentage only when the clean A1/A2 stability gate is within 10%.

    Pass: both CN entries are correct, only one producer executes, cancellation/reuse leaves no residual query, spill resources remain bounded and are released, and no material performance regression is observed on a stable host.

    Fail: wrong result, duplicate producer execution, remote-pipeline error, cleanup timeout/residual query, spill budget/resource leak, or a stable-host performance regression.

    Final-head CI: https://github.com/matrixorigin/matrixone/actions/runs/30544294369

    Final-head TKE check-in: https://github.com/matrixorigin/matrixone/actions/runs/30546239273

  4. Ariznawlll commented on Aug 6, 2026

    @Ariznawlll
    Collaborator

    TPCH 多 CN 回归验证证据

    针对 issue #26131,本次先补充 TPCH 多 CN 维度的验证证据。该评论只覆盖 TPCH 正确性、Q15 多引用 CTE 计划形态和 TPCH 性能门禁;取消清理与受限 spill 资源边界仍需单独补测。

    测试版本

    测试环境

    • Namespace:mo-main-commit-ab28d1b4a-20260805
    • 部署方式:TKE distributed multi-CN
    • CN:3 个 TP CN,启动时均为 Running,RESTARTS=0
    • DN:1 个,启动时 Running,RESTARTS=0
    • LOG:3 个,启动时均为 Running,RESTARTS=0
    • Proxy:2 个,启动时均为 Running,RESTARTS=0
    • CN 配置:cn_count=3,cn_limits_memory=55Gi,cn_memory_cache_size=12Gi,cn_gomemlimit=25000MiB

    启动时 pod 摘要:

    nightly-regression-dis-dn-0          1/1 Running 0
    nightly-regression-dis-log-0         1/1 Running 0
    nightly-regression-dis-log-1         1/1 Running 0
    nightly-regression-dis-log-2         1/1 Running 0
    nightly-regression-dis-proxy-9cg5f   1/1 Running 0
    nightly-regression-dis-proxy-b85nt   1/1 Running 0
    nightly-regression-dis-tp-cn-fxssk   1/1 Running 0
    nightly-regression-dis-tp-cn-xnr8c   1/1 Running 0
    nightly-regression-dis-tp-cn-zss9p   1/1 Running 0
    

    原问题 SQL

    mo-tpch/queries/q15.sql 使用的是原问题的多引用 CTE 形态:q15_revenue0 先聚合 lineitem,随后同时被 supplier join 和 select max(total_revenue) from q15_revenue0 标量子查询消费。

    with q15_revenue0 as (
        select
            l_suppkey as supplier_no,
            sum(l_extendedprice * (1 - l_discount)) as total_revenue
        from
            lineitem
        where
            l_shipdate >= date '1995-12-01'
            and l_shipdate < date '1995-12-01' + interval '3' month
        group by
            l_suppkey
        )
    select
        s_suppkey,
        s_name,
        s_address,
        s_phone,
        total_revenue
    from
        supplier,
        q15_revenue0
    where
        s_suppkey = supplier_no
        and total_revenue = (
            select
                max(total_revenue)
            from
                q15_revenue0
        )
    order by
        s_suppkey;

    正确性验证

    TPCH job 中 TPCH_1、TPCH_10、TPCH_100、TPCH_1000 均为 PASS。

    SF10 的 Q15 结果与 golden 对比通过,golden 为:

    S_SUPPKEY  S_NAME              S_ADDRESS             S_PHONE          TOTAL_REVENUE
    33987      Supplier#000033987  oHFS5orEHtYMgOS3RGWR  13-117-218-7219  2296670.4443
    

    Q15 执行记录:

    TPCH_10:
      18:32:37 q15 cost=464, result compare PASS
      18:32:52 q15 cost=419, result compare PASS
      18:33:06 q15 cost=425, result compare PASS
      18:33:18 q15 cost=430, result compare PASS
    
    TPCH_100:
      18:34:31 q15 cost=4079, result compare PASS
      18:36:17 q15 cost=4101, result compare PASS
      18:38:03 q15 cost=4463, result compare PASS
      18:39:51 q15 cost=4077, result compare PASS
    
    TPCH_1000:
      18:49:20 q15 cost=32825, result compare PASS
      19:06:48 q15 cost=32800, result compare PASS
      19:24:14 q15 cost=33011, result compare PASS
    

    Q15 计划形态

    SF10 EXPLAIN 显示 Q15 使用 AP QUERY PLAN ON MULTICN(14 core)。计划中只有一个 lineitem scan/filter/group producer,即 Plan 0;supplier join 和 MAX(total_revenue) 两个 consumer 都通过 Sink Scan 读取同一个 DataSource: Plan 0。

    AP QUERY PLAN ON MULTICN(14 core)
    
    Plan 0:
    Sink
      ->  Project
            ->  Aggregate
                  Group Key: lineitem.l_suppkey shuffle: range(lineitem.l_suppkey)
                  Aggregate Functions:
                    sum((cast(lineitem.l_extendedprice AS DECIMAL128(38, 2)) *
                        (1 - cast(lineitem.l_discount AS DECIMAL128(38, 2)))))
                  ->  Table Scan on tpch_10g.lineitem
                        Filter Cond:
                          (lineitem.l_shipdate >= 1995-12-01),
                          (lineitem.l_shipdate < 1996-03-01)
    
    Plan 1:
    Project
      ->  Sort
            Sort Key: supplier.s_suppkey INTERNAL
            ->  Filter
                  Filter Cond:
                    (q15_revenue0.total_revenue = max(q15_revenue0.total_revenue))
                  ->  Join
                        Join Type: LEFT
                        ->  Join
                              Join Type: INNER hashOnPK
                              Join Cond: (q15_revenue0.supplier_no = supplier.s_suppkey)
                              ->  Sink Scan
                                    DataSource: Plan 0
                              ->  Table Scan on tpch_10g.supplier
                        ->  Aggregate
                              Aggregate Functions: max(q15_revenue0.total_revenue)
                              ->  Sink Scan
                                    DataSource: Plan 0
    

    SF100 和 SF1000 的 Q15 explain 也显示相同复用形态:一个 Plan 0 producer,两个 Sink Scan consumer,且两个 consumer 均为 DataSource: Plan 0。

    SF100 关键片段:

    Plan 0:
      Group Key: lineitem.l_suppkey shuffle: range(lineitem.l_suppkey)
      -> Table Scan on tpch_100g.lineitem
    
    Plan 1:
      -> Sink Scan
           DataSource: Plan 0
      -> Aggregate
           Aggregate Functions: max(q15_revenue0.total_revenue)
           -> Sink Scan
                DataSource: Plan 0
    

    SF1000 关键片段:

    Plan 0:
      Group Key: lineitem.l_suppkey shuffle: range(lineitem.l_suppkey)
      -> Table Scan on tpch_1000g.lineitem
    
    Plan 1:
      Join Cond: (q15_revenue0.supplier_no = supplier.s_suppkey) shuffle: hash(q15_revenue0.supplier_no)
      -> Sink Scan
           DataSource: Plan 0
      -> Aggregate
           Aggregate Functions: max(q15_revenue0.total_revenue)
           -> Sink Scan
                DataSource: Plan 0
    

    该计划形态覆盖了 issue 中要求的核心 TPCH 检查点:lineitem revenue relation 只生产一次,join consumer 和 scalar MAX(total_revenue) consumer 复用同一个 materialized CTE producer。

    TPCH 性能门禁

    TPCH 汇总结果:

    TPCH_1     PASS
    TPCH_10    PASS
    TPCH_100   PASS
    TPCH_1000  PASS
    

    性能阈值检查:

    TPCH_10:
      This time: sum(cost) = 12094
      Last two times: 11610, 13101
      Result: not 25.0% higher than the last one
    
    TPCH_100:
      This time: sum(cost) = 104849
      Last two times: 94841, 98131
      Result: not 25.0% higher than the last one
    
    TPCH_1000:
      This time: sum(cost) = 1041933
      Last two times: 1042567
      Result: not 25.0% higher than the last one
    

    当前覆盖范围

    本次证据可以支持:

    1. 多 CN TKE 环境下 TPCH Q15 返回正确结果。
    2. Q15 原始多引用 CTE SQL 被实际执行。
    3. EXPLAIN 中 lineitem revenue 聚合只作为一个 Plan 0 producer 出现。
    4. supplier join 和 scalar MAX(total_revenue) 两个消费者均通过 Sink Scan 读取 DataSource: Plan 0。
    5. TPCH_10、TPCH_100、TPCH_1000 未触发 25% 性能回归门禁。

    仍未由本 run 覆盖:

    1. 客户端取消 Q15 后,跨 CN SHOW PROCESSLIST 观察无残留 query/pipeline,并且立即重跑成功。
    2. 受限 spill memory/disk/fd budget 下,materialized CTE 溢写成功或失败均有界,并在成功/失败后释放资源。

    因此,该 run 可作为 #26131 的 TPCH 多 CN 正确性、计划形态和性能门禁证据;最终完整验证仍需要补充取消清理与 spill 资源边界两项证据。

  5. Ariznawlll commented on Aug 13, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:main
    • commit:1c292cf20e113b296a3db2cb6a65e00af2ea2327
    • 部署方式:本地 1 Log + 1 TN + 2 CN;spill 扩展场景使用固定 32 MiB 限额
    • 测试日期:2026-08-13

    原问题验证

    重新验证 TPCH Q15 的多引用 CTE 形态:同一个 revenue CTE 同时供 supplier join 和标量 MAX(total_revenue) 消费。最新 main 的计划只有一个 CTE producer,两个消费者均通过 Sink Scan 读取该 producer;查询返回唯一预期供应商及正确 revenue,没有重复行或漏行。

    同时在修复前对照版本 9c0f901c2 执行相同计划检查,计划中出现两个独立的 lineitem Table Scan,Sink Scan=0;最新 main 不再出现该重复执行形态。

    Happy Path 覆盖

    1. 现有 Q15 集成回归使用 100 个 supplier、100,000 行 lineitem,断言计划至少包含两个 Sink Scan,并精确校验唯一供应商 42、名称 supplier-42、非空 revenue 和无额外结果行。
    2. 受限 spill 场景使用 500,000 行、19 个 BIGINT 列并降低统计估算,计划保持一个 producer 和两个 Sink Scan;结果精确正确。
    3. spill reserve/release 均为 13,162,036 bytes,查询完成后资源计费归零;从两个 CN 入口执行及恢复查询均正常。

    Unhappy Path 覆盖

    1. 将物化输入扩大到 800,000 行并超过 32 MiB 限额,查询被有界拒绝;拒绝后未返回部分结果,两个 CN 均保持健康。
    2. 拒绝后立即从另一个 CN 执行较小的 500,000 行场景,结果正确,证明失败未污染后续 materialized CTE 执行与复用状态。
    3. 扩展取消测试发现:客户端 context 已返回错误后,目标 conn_id/statement 仍可保持 COM_QUERY 超过 5 秒。该现象是“取消传播/后台查询清理”缺陷,与本 issue 的“同一多引用 CTE 被重复执行”具有不同触发条件和验收标准,不作为 [Optimizer] TPCH Q15 executes the same multi-reference CTE twice #26131 的成功基线;应独立立项并在修复后增加 multi-CN 回归。
    4. 资源拒绝在不同执行中可能映射为 3015 resource exhausted 或 20101 internal error;资源释放和后续恢复均正常,但错误分类一致性应作为独立问题处理。

    白盒验证

    • materialized CTE source、merge、compile 和 plan 的 focused Go 测试连续 count=10 通过。
    • materialized source/compile 的 focused -race 测试通过。
    • 白盒结果仅用于补充 ownership、复用和清理路径;原问题结论仍由公开 SQL 的结果与计划形态验证。

    回归测试

    • 原问题已有 MatrixOne Go 集成回归:issue_26131_test.go,覆盖原始 Q15 形态、一个 producer、两个 Sink Scan consumer 及精确结果。
    • 不再向 motr 重复添加同一 SQL 回归。
    • spill/阈值场景需要非默认配置和大规模输入,适合 configured integration/nightly;取消传播失败必须等待独立问题修复后再建立成功回归,不能记录当前失败行为为 expected。

    测试证据

    • 修复 PR:matrixone#26426,merge commit b2aec782dc16717ee38c53d2c5961481781b2882。
    • 修复 final-head CI:Actions run 30544294369。
    • 多 CN TPCH nightly 证据:Actions run 31027932135。
    • 本轮关键结果:修复前 2 Table Scan / 0 Sink Scan;最新 main 1 producer / 2 Sink Scan;spill reserve=release=13,162,036 bytes;超限拒绝后跨 CN 立即恢复成功。

    测试结论

    测试通过。

  6. Ariznawlll commented on Aug 13, 2026

    @Ariznawlll
    Collaborator

    补充验证中确认的两个派生问题已分别建 Bug,避免与 #26131 原始 CTE 复用/取消问题混在一起:

    两项均已在最新 main 1d7b6311ce91df0968da435bb405f3d68137c595 的 2-CN 隔离环境复现,并包含 Happy/Unhappy、无部分结果及恢复性对照。

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

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions