Skip to content

[Performance]: Avoid full probe-table scans for right SINGLE joins without breaking multi-CN execution #25862

Closed

Description

@XuPeng-SH

Is there an existing issue for performance?

  • I have checked the existing issues.

Environment

  • Version or commit-id: main at 946427b877c1b12c497743eff264047e60a00be2
  • Deployment: two-CN make dev-up cluster
  • Hardware parameters: 24 CPU cores; 6 GiB file-service memory cache per CN
  • OS type: Linux

Details of Performance

A correlated scalar subquery can be flattened into a right SINGLE hash join when the preserved outer relation is much smaller than the inner table:

CREATE DATABASE rsingle_perf;
USE rsingle_perf;

CREATE TABLE big(id BIGINT PRIMARY KEY, v BIGINT);
INSERT INTO big
SELECT result, result * 10
FROM generate_series(1, 1000000, 1);

CREATE TABLE small(id BIGINT PRIMARY KEY);
INSERT INTO small VALUES (1), (5000000), (10000000);

ANALYZE TABLE big;
ANALYZE TABLE small;

SELECT s.id,
       (SELECT b.v FROM big b WHERE b.id = s.id) AS v
FROM small s
ORDER BY s.id;

The optimizer physically swaps the scalar SINGLE join so that the small preserved relation is the hash-build side and big is the probe table:

Join Type: RIGHT SINGLE
Join Cond: (b.id = s.id)
├── Table Scan: big    -- probe; unmatched rows are discarded
└── Table Scan: small  -- build and preserved side

On main, generateRuntimeFilters rejects every Node_SINGLE join. As a result, the query scans and probes all rows from big, even though the build side contains only three keys.

A one-CN prototype that generates a runtime filter only for right SINGLE reduced the work as follows:

Metric from EXPLAIN ANALYZE Main-equivalent path (RF disabled) Right-SINGLE RF prototype
big input blocks 123 1
big input rows 1,000,000 1
Join input rows 1,000,003 4
Scan read size 7.68 MiB 96.33 KiB
Warm-cache client latency 0.21 s 0.21 s

The warm-cache latency at this scale is dominated by fixed/client overhead, but the avoided scan, I/O, and hash-probe work is substantial and should matter for larger/wider tables, cold cache, and concurrent workloads.

Important multi-CN constraint

Simply allowing Node_SINGLE && IsRightJoin through the existing runtime-filter gate is not safe.

With the same one-million-row data set forced onto the multi-CN execution path:

Optimizer settings Result
runtimeFilter=1,execType=3 (RF disabled) Completed correctly in 0.23 s
execType=3 (naive right-SINGLE RF enabled) Did not finish after 37.10 s; canceled manually with context canceled

A natural ten-million-row AP multi-CN plan with the naive RF also failed to finish after more than 80 seconds. Therefore, this issue must not be fixed by only relaxing the join-type check. The right-SINGLE runtime-filter message/scheduling lifecycle must work across CNs, or the eligible plan must be safely constrained to one CN.

Expected behavior / acceptance criteria

  1. Eligible right SINGLE joins can filter a discardable table-scan probe using keys from the preserved build side.
  2. Left SINGLE joins remain excluded because unmatched probe rows must be preserved.
  3. Existing runtime-filter eligibility guards remain effective, including non-leading composite-primary-key checks and cardinality/selectivity limits.
  4. Scalar-subquery semantics remain correct for matching keys, missing keys (NULL), and duplicate inner matches (cardinality violation).
  5. Both one-CN and multi-CN executions finish without hangs and return identical results with the optimization enabled or disabled.
  6. A multi-CN BVT/regression test covers the runtime-filter message lifecycle, not only the presence of Build/Probe specs in the logical plan.
  7. EXPLAIN ANALYZE demonstrates reduced probe blocks/rows on a large-table/small-build case.

Additional information

The right-SINGLE output-cardinality calculation has a separate optimizer-phase concern: IsRightJoin is set before swapJoinChildren, while the physical child order changes later. A generic cardinality change based only on IsRightJoin can be correct after the swap but wrong during earlier join-ordering passes. That change should not be bundled into this performance fix without a phase-safe preserved-side model and a downstream-join plan regression test.

Activity

  1. XuPeng-SH commented on Jul 18, 2026

    @XuPeng-SH
    ContributorAuthor

    Latest-main SQL-shape verification

    I reproduced the issue directly with a clean image built from main commit 946427b877c1b12c497743eff264047e60a00be2. Both CNs in the two-CN make dev-up cluster were replaced with that image while keeping the same TN, LogService, and data. The test used:

    • customer: 1,000,000 rows, primary key id
    • product: 1,000,000 rows, primary key id
    • delta / DML target: 3 rows with sparse lookup keys

    No experimental runtime-filter code was present in the main image.

    Confirmed affected SQL shapes

    SQL shape Plan on latest main Actual large-table work from EXPLAIN ANALYZE
    Scalar lookup in the SELECT list 1 RIGHT SINGLE 123 blocks / 1,000,000 rows
    Scalar lookup used by a WHERE predicate 1 RIGHT SINGLE 123 blocks / 1,000,000 rows
    Two scalar lookups in one SELECT 2 nested RIGHT SINGLE joins 246 blocks / 2,000,000 rows
    Correlated scalar lookup in UPDATE ... SET 1 RIGHT SINGLE under Multi Update 123 blocks / 1,000,000 rows
    Correlated scalar lookup in INSERT ... SELECT 1 RIGHT SINGLE under Lock and DEDUP 123 blocks / 1,000,000 rows
    Correlated scalar lookup in a DELETE predicate 1 RIGHT SINGLE under Filter and Multi Update 123 blocks / 1,000,000 rows

    Representative SELECT:

    SELECT d.id,
           (SELECT c.val FROM customer c WHERE c.id = d.customer_id) AS v
    FROM delta d
    ORDER BY d.id;

    Latest-main runtime evidence:

    Join Type: RIGHT SINGLE
    Join Cond: (c.id = d.customer_id)
    Table Scan on customer:
      inputBlocks=123
      inputRows=1000000
      outputRows=1000000
      ReadSize=7.68 MiB
    Join:
      inputRows=1000003
      outputRows=3
    

    The multiple-lookup case independently scanned both million-row tables:

    SELECT d.id,
           (SELECT c.val FROM customer c WHERE c.id = d.customer_id),
           (SELECT p.val FROM product p WHERE p.id = d.product_id)
    FROM delta d;
    customer scan: 123 blocks / 1,000,000 rows
    product scan:  123 blocks / 1,000,000 rows
    final output:  3 rows
    

    DML correctness and scan amplification

    The DML statements completed correctly:

    UPDATE update_target t
    SET v = (SELECT c.val FROM customer c WHERE c.id = t.customer_id)
    WHERE t.id <= 3;
    
    INSERT INTO insert_dest
    SELECT d.id,
           (SELECT c.val FROM customer c WHERE c.id = d.customer_id)
    FROM delta d;
    
    DELETE FROM delete_target t
    WHERE (SELECT c.status FROM customer c WHERE c.id = t.customer_id) = 1;

    Verified results:

    UPDATE: (1,10), (2,5000000), (3,10000000)
    INSERT: (1,10), (2,5000000), (3,10000000)
    DELETE: removed ids 1 and 3; id 2 remained
    

    Each statement nevertheless fed 1,000,003 rows into the right-SINGLE join to produce only 3 rows. Thus this is a performance/resource-amplification issue, not a result-correctness failure.

    One-CN prototype comparison

    With the right-SINGLE runtime-filter prototype enabled on the same data and SQL shapes:

    SELECT projection: customer 123 blocks / 1,000,000 rows -> 3 blocks / 3 rows
    Two lookups:       each large table                    -> 3 blocks / 3 rows
    UPDATE:            customer                            -> 3 blocks / 3 rows
    INSERT SELECT:     customer                            -> 3 blocks / 3 rows
    DELETE:            customer 123 blocks / 1,000,000 rows -> 1 block / 3 rows
    

    All output/DML results remained identical in the one-CN tests. This confirms that the optimization opportunity is real across SELECT and DML shapes. It does not remove the multi-CN safety requirement documented in the issue: the naive prototype still stalls on the multi-CN execution path and is not mergeable as-is.

    Negative controls

    The following did not produce SINGLE and are outside this issue's specific scope:

    • correlated MAX(...) scalar subquery: RIGHT join with aggregate
    • correlated EXISTS: SEMI join

    The test database was removed after verification, optimizer hints were restored, both CNs were switched back to the local development image, and all five cluster services are healthy.

  2. added
    severity/s0
    on Jul 31, 2026
  3. Ariznawlll commented on Aug 26, 2026

    @Ariznawlll
    Collaborator

    测试环境

    • MatrixOne main,commit 946427b877c1b12c497743eff264047e60a00be2
    • 双 CN + TN + LogService
    • 使用同一份数据连续执行查询和 DML

    复现步骤

    1. 创建两张百万行 lookup 表和一个只有 3 行的稀疏输入表:

      CREATE TABLE customer (id INT PRIMARY KEY, val INT);
      INSERT INTO customer SELECT result, result FROM generate_series(1000000);
      
      CREATE TABLE product (id INT PRIMARY KEY, val INT);
      INSERT INTO product SELECT result, result FROM generate_series(1000000);
      
      CREATE TABLE delta (id INT PRIMARY KEY, customer_id INT, product_id INT);
      INSERT INTO delta VALUES (1, 10, 10), (2, 500000, 500000), (3, 1000000, 1000000);
    2. 执行代表性标量子查询并查看实际执行:

      EXPLAIN ANALYZE
      SELECT d.id,
             (SELECT c.val FROM customer c WHERE c.id = d.customer_id) AS v
      FROM delta d ORDER BY d.id;
    3. 继续执行以下 SQL,覆盖 SELECT、UPDATE、INSERT ... SELECT 和 DELETE:

      SELECT d.id,
             (SELECT c.val FROM customer c WHERE c.id = d.customer_id),
             (SELECT p.val FROM product p WHERE p.id = d.product_id)
      FROM delta d;
      
      UPDATE delta d
      SET customer_id = (SELECT c.id FROM customer c WHERE c.id = d.customer_id)
      WHERE d.id <= 3;
    4. 对每条语句检查 EXPLAIN ANALYZE 的 Right SINGLE 节点、输入行数、扫描 block 数和最终输出行数;同时核对 DML 结果。

    实际结果

    • 代表性 SELECT 生成 RIGHT SINGLE,customer 扫描约 123 blocks / 1,000,000 rows,最终只输出 3 行。
    • 双 scalar lookup 分别扫描 customer 和 product,各约 1,000,000 rows,合计约 2,000,000 rows。
    • correlated UPDATE、INSERT ... SELECT、DELETE 结果正确,但每条语句仍将约 1,000,000 行送入 Right SINGLE。
    • 说明当前 main 仍存在完整 probe-table 扫描,runtime filter 尚未生效;双 CN 安全执行路径也未完成。

    期望结果

    对于只有 3 个 lookup key 的输入,Right SINGLE 应通过 runtime filter 将 probe 扫描限制在命中 key 的少量行,并保持双 CN 执行安全;不应扫描整张百万行 probe 表。

    测试结论

    测试不通过。

  4. XuPeng-SH commented on Sep 22, 2026

    @XuPeng-SH
    ContributorAuthor

    Current-main reconciliation: this issue's implementation is already present through #25865 (merge 862d9d30c2) and follow-up #27626 (merge 1891117aed); both are ancestors of current main (3727c5c543).

    The merged behavior is intentionally conservative:

    • eligible physical right SINGLE joins can build an exact runtime filter for the discardable probe side;
    • left SINGLE, unsafe scan shapes, unsupported keys, and over-limit builds retain the fallback;
    • unavailable statistics can use bounded collection only when the query is already local;
    • naturally/forced multi-CN execution with unavailable statistics does not introduce the filter or downgrade placement;
    • topology validation prevents a local-only filter from leaving remote consumers waiting;
    • runtime cardinality overflow fails open with PASS while preserving the complete JoinMap.

    Fresh checks on the current main revision passed for the right-SINGLE planner contracts, bounded hashbuild fallback/cardinality, and compile topology/parallel-producer validation. #27626 also records the original isolated two-CN acceptance run and scan reduction (1,000,000 probe rows to 2 rows in the eligible local plan, with forced multi-CN completing on the no-filter fallback).

    I found no reachable current-main code gap and therefore did not create a duplicate PR. I have not rerun the live one-CN/two-CN BVT and EXPLAIN ANALYZE profile on 3727c5c543, so that historical live evidence should not be treated as a fresh execution on today's SHA. Subject to that validation distinction, this issue is code-complete via the two merged PRs.

  5. Ariznawlll commented on Oct 3, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:main
    • 实际复测 commit:529ee099e32ed8c38d2806043bf1516ab0345e45
    • 部署方式:本地单 CN 与 1 Log / 1 TN / 2 CN;双 CN 下分别从两个 CN 入口执行
    • 测试日期:2026-10-03

    原问题验证

    在 100 万行的 probe 表和 4 个稀疏查找键下,对 RIGHT SINGLE 标量子查询连续运行 3 轮,逐轮检查完整查询结果及 EXPLAIN ANALYZE:正常路径只扫描 3 行 / 3 blocks;关闭 Right SINGLE runtime filter 的对照路径扫描 1,000,000 行 / 128 blocks。两条路径返回的标量子查询结果一致。该差异直接证明命中的本地计划确实过滤了大表扫描,而不只是计划文本出现 Build/Probe 标记。

    正常路径覆盖

    1. SELECT、UPDATE、INSERT ... SELECT、DELETE 的结果正确,查找侧只读 3 行;缺失键保留预期的 NULL 语义。
    2. 双 CN 强制分布式退化路径,从两个 CN 入口各连续执行 3 次,均完成且结果正确、未卡住;该路径按设计回退全表扫描,而不错误地发送仅适用于本地计划的过滤器。

    边界与错误路径覆盖

    1. 关闭过滤器的对照路径稳定扫描 1,000,000 行 / 128 blocks,证明启用路径的扫描量下降来自过滤器。
    2. 标量子查询匹配重复值时返回预期的 1242 cardinality error,而不是选取任意一行或写出部分 DML 结果。
    3. 多 CN 退化未复现原问题中错误启用 runtime filter 导致的等待/挂起。

    白盒验证

    本轮以公开 SQL、EXPLAIN ANALYZE 和双 CN 完成性为主,未新增故障注入。实现及边界的 Go 测试来自已合入的 #25865 与 #27626。

    回归测试

    测试证据

    • 上述 big-data job 与已合入的 MOTR 用例;原 issue 的验收条件涵盖扫描量、结果、错误语义及多 CN 完成性。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

kind/performanceseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions