Skip to content

[Bug]: ORDER BY with a repeated column and LIMIT uses the last sort direction #32396

Open

Description

@XuPeng-SH

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Branch Name

4.2-dev; also reproduced on released versions v4.2.0, v4.2.7, and v4.2.8.

Commit ID

  • 4.2-dev: 6d4dc2f0fb11799a871f3c72e54e943c4eb2090f
  • v4.2.0: 01ae8eca88110dc29d2f51e421570bb3d850d328
  • v4.2.7: 260678bace0177678255089a23d0fe7d54cfc745
  • v4.2.8: 10d204b8763f19b2b37ba2147d1d4c1a7828d6d4

Other Environment Information

Linux x86-64, isolated single-node instances. The v4.2.0 and v4.2.7 checks used the official release binaries; v4.2.8 used the image for its release commit, and 4.2-dev used a locally built binary at the commit above. MySQL 8.0.44 was used as a behavior control.

Actual Behavior

When the same column occurs multiple times in ORDER BY with different directions and the query uses LIMIT, the Top path uses the last occurrence's direction. All four MatrixOne versions listed above produced the same results in the minimal reproduction:

Query MatrixOne Expected / MySQL
ORDER BY b DESC, b ASC LIMIT 2 1, 2 4, 3
ORDER BY b ASC, b DESC LIMIT 2 4, 3 1, 2
ORDER BY b DESC, b ASC (no LIMIT) 4, 3, 2, 1 4, 3, 2, 1

The error also affects OFFSET: ORDER BY b DESC, b ASC LIMIT 2 OFFSET 1 returned 2, 3 instead of 3, 2. This issue predates v4.2.8; the earliest affected release has not been established.

Expected Behavior

A later ordering key only breaks ties left by earlier keys. When the same column appears twice, the first occurrence determines the ordering of distinct values, regardless of the second occurrence's direction. LIMIT and OFFSET should select the corresponding prefix/slice of that order.

Steps to Reproduce

CREATE DATABASE repeated_order_key_repro;
USE repeated_order_key_repro;
CREATE TABLE t (a INT, b INT);
INSERT INTO t VALUES (10, 1), (20, 2), (30, 3), (40, 4);

-- Actual: 1, 2. Expected: 4, 3.
SELECT b FROM t ORDER BY b DESC, b ASC LIMIT 2;

-- Actual: 4, 3. Expected: 1, 2.
SELECT b FROM t ORDER BY b ASC, b DESC LIMIT 2;

-- Controls: both return 4, 3 (or 4, 3, 2, 1 without LIMIT).
SELECT b FROM t ORDER BY b DESC LIMIT 2;
SELECT b FROM t ORDER BY b DESC, b ASC;

Additional information

Root cause: In Top.build, the map from physical vector position to ORDER BY key index overwrites earlier entries when positions repeat. Comparator construction then takes direction and NULL ordering from the last occurrence, even though comparisons traverse keys in their original order. The same map is consulted by both the normal and spill-mode comparator construction. This identifies the reproduced failure; it does not by itself establish actual on-disk spill behavior.

Interaction with Top-to-scan pruning: At 6d4dc2f, the following independent setup produces different wrong answers with the pruning message enabled and disabled:

CREATE DATABASE repeated_order_key_pruning;
USE repeated_order_key_pruning;
CREATE TABLE t (id INT NOT NULL, b INT NOT NULL) CLUSTER BY (b);
INSERT INTO t VALUES (101, 101), (102, 102), (103, 103);
SELECT mo_ctl('dn', 'flush', 'repeated_order_key_pruning.t');
INSERT INTO t VALUES (1, 1), (2, 2), (3, 3);
SELECT mo_ctl('dn', 'flush', 'repeated_order_key_pruning.t');

SET SESSION optimizer_hints = 'execType=1';
-- Actual: 101, 102. Expected: 103, 102.
SELECT b FROM t ORDER BY b DESC, b ASC LIMIT 2;

SET SESSION optimizer_hints = 'execType=1,sendMessageFromTopToScan=1';
-- Actual: 1, 2. Expected: 103, 102.
SELECT b FROM t ORDER BY b DESC, b ASC LIMIT 2;

EXPLAIN ANALYZE showed the enabled case sending/receiving MsgTopValue and reading one block, versus two blocks with the message disabled. Both answers are wrong; this observation does not show that the pruning change turned a previously correct answer into a wrong one. A fix should keep the Top comparator and scan-pruning order semantics consistent.

Please cover both sort directions, NULL ordering, offsets, distinct intervening sort keys, and normal and actual spill execution. Repeated expressions should only be treated as interchangeable when their evaluation semantics justify it (in particular, do not deduplicate volatile expressions solely by text).

Activity

  1. self-assigned this
    on Nov 9, 2026
  2. added
    kind/bug
    on Nov 9, 2026
  3. added a commit that references this issue on Nov 9, 2026
    fa6bc2b
  4. Ariznawlll commented on Nov 10, 2026

    @Ariznawlll
    Collaborator

    结论

    这是本 issue 的同类复现,补充了 NULL、实际 TopN 落盘、GROUP BY 后排序、SQL PREPARE 和原生二进制 prepared 重用、远端 CN 执行 的边界,不是新增独立 bug。

    关键证据

    • 版本:官方 main@0c8bd5e5f3be4ce5582201513161181ddca37d6d 原版源码本地构建;两本地 CN,对照 MySQL 8.3.0。三套独立表均复现。后续补充实际远端执行证据,详见下文;不是多机物理网络测试。
    • 每表 40001 行;相同数据,无 LIMIT 或删除第二个重复排序键时,完整结果均符合独立 oracle/MySQL。加入重复键后,LIMIT 31、16384、16385 都取错方向,并把应在末尾的 NULL 放到前面。

    可单独运行的 MO 构造:

    CREATE DATABASE order32396_ext;
    USE order32396_ext;
    CREATE TABLE t (id INT PRIMARY KEY, k INT, p VARCHAR(150));
    INSERT INTO t
    SELECT result,
           IF(MOD(result,13)=0,NULL,MOD(result*179,1009)),
           REPEAT('x',128)
    FROM generate_series(0,40000) AS s;
    
    SELECT mo_ctl('dn','flush','order32396_ext.t');
    SET SESSION sort_spill_mem=65536;
    
    -- 同类复现:前三行 (0,NULL),(13,NULL),(26,NULL)
    SELECT id,k FROM t ORDER BY k DESC,k ASC,id LIMIT 16385;
    
    -- 正常对照:前三行 (62,1008),(1071,1008),(3089,1008)
    SELECT id,k FROM t ORDER BY k DESC,id LIMIT 16385;
    
    -- 正常对照:无 LIMIT 时按第一项 DESC 正确排序
    SELECT id,k FROM t ORDER BY k DESC,k ASC,id;
    
    EXPLAIN ANALYZE
    SELECT id,k FROM t ORDER BY k DESC,k ASC,id LIMIT 16385;

    实际计划摘录(三轮两个入口均有非零落盘量):

    inputRows=40001 outputRows=16385
    SpillRows=40001 SpillSize=318.13 KiB
    Sort Key: repeated0.k DESC, repeated0.k ASC, repeated0.id INTERNAL
    

    聚合后排序也命中同一机制:

    PREPARE p FROM
     'SELECT k,COUNT(*) n FROM t
      GROUP BY k ORDER BY n DESC,n ASC,k LIMIT ?';
    SET @n=7;
    EXECUTE p USING @n;
    SET @n=16385;
    EXECUTE p USING @n;
    SET @n=7;
    EXECUTE p USING @n;
    DEALLOCATE PREPARE p;
    
    -- 正常对照
    SELECT k,COUNT(*) n FROM t GROUP BY k ORDER BY n DESC,k LIMIT 7;

    三次 EXECUTE 都从 (0,36),(1,36),(2,36) 开始;正确前三行为 (NULL,3077),(7,37),(8,37),MySQL 与去掉第二个 n ASC 的对照一致。

    后续原生二进制 prepared 扩展:mysql-connector-python 26.10.0,use_pure=True、cursor(prepared=True),实际发送 COM_STMT_PREPARE/EXECUTE。三套表 × 两入口 × 参数序列 31→16384→16385→31,共 24/24 次同类复现;去掉第二个重复键及无 LIMIT 的 30/30 项正常对照一致。

    对前述 t,在原生连接 cn 上执行:

    with cn.cursor() as c:
        c.execute("SET optimizer_hints='execType=3'")
        c.execute("SET query_max_workers=2")
        c.execute("SET max_dop=1")
        c.execute("SET sort_spill_mem=65536")
    
    with cn.cursor(prepared=True) as c:
        for n in (31, 16384, 16385, 31):
            c.execute("SELECT id,k FROM order32396_ext.t "
                      "ORDER BY k DESC,k ASC,id LIMIT %s", (n,))
            rows = c.fetchall()
            print(n, rows[:3])

    同样用原生 prepared 执行 EXPLAIN PHYPLAN ANALYZE ... LIMIT %s:CN1 为协调节点,CN1 本地 TableScan 实际 OutRows=0,远端 scope 指向 CN2,根 Top 收到 40001 行;逻辑 EXPLAIN ANALYZE 的 TableScan/Top 输入也均为 40001,Top SpillRows=40001、SpillSize=318.13 KiB。这证明该变体包含远端取数,不只是分别连两入口;文本 PHYPLAN 没有展开远端逐算子实际计数,未据此声称已取得完整逐 CN 计数。

    白盒位置仍是本 issue 所述同一处:Top 构造比较器。物理列位置映射覆盖前一个排序项,后续普通/落盘分支都使用最后一个排序项的方向及 NULL 策略;LIMIT > 16384 的分支见 Prepare。

    待解决点

    修复后需要一起覆盖普通 TopN、实际落盘 TopN、NULL 位置和聚合别名的重复排序;SQL PREPARE 与原生 prepared 的参数序列应重复执行而不是只首次执行,并保留远端执行覆盖。未验证多机、旧新版本混部;未新增仓库测试或 PR。

  5. added a commit that references this issue on Nov 21, 2026
    6d45e4b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions