Skip to content

[Performance]: DESC ORDER BY with LIMIT misses the top-N fast path #31803

Closed

Description

@Ariznawlll

Description

ORDER BY <pk columns> DESC LIMIT n pays a 16× penalty over the identical ASC query on current main — a pure-planner/executor performance gap in the single most common pagination pattern, with identical EXPLAIN plans for both directions (correctness is intact; this is a performance defect proven by timing + plan analysis).

Measured on a 200k-row table with composite PK (a,b,c) (main c6683bd2f5, 2026-10-30, dual-CN launch), median of 3 runs each:

query median
SELECT a,b,c,v FROM bigfact ORDER BY a,b,c LIMIT 5 3 ms
SELECT a,b,c,v FROM bigfact ORDER BY a DESC,b DESC,c DESC LIMIT 5 48 ms
same two queries without LIMIT (full sort) 357 vs 359 ms (identical)
no ORDER BY, LIMIT 5 1 ms

Key observations isolating the defect:

  1. EXPLAIN shows the same plan shape for both directions — Sort (Sort Key: … [INTERNAL|DESC]) → Limit 5 → Table Scan. The 16× gap is not from plan selection.
  2. The no-LIMIT row proves the sort itself handles both directions at identical cost — the divergence appears only when Limit composes with a DESC sort key.
  3. Natural inference: the ASC+Limit path is being executed as an early-terminating top-N (stop after 5 index-ordered rows / bounded heap), while the DESC key defeats that fast path and falls back to a much more expensive strategy (full materialization or in-memory heap of a wider buffer). Since both plans print identically, the asymmetry hides from plan inspection entirely — users profiling with EXPLAIN will see "the same plan" and conclude the slowness is elsewhere.
  4. A real-table shape where this bites: "latest N records" pages (ORDER BY created_at DESC LIMIT 20) over any moderately sized table — with a DESC index defined or with a composite PK whose leading column is scanned in reverse.

Impact

  • Every DESC-side pagination/latest-N query inherits an ~16× CPU/latency tax invisible in EXPLAIN. At 200k rows the absolute numbers are small, but the penalty is structural — it scales with data size up to the full-sort floor (357 ms here), while ASC-side stays top-N-bounded.
  • Interactive dashboards whose default view is "newest first" are exactly the pattern that hits this.

Expected behavior

DESC sort keys with LIMIT should run the same bounded top-N execution as ASC (a max-heap instead of min-heap suffices; no planner change needed — the execution path for Sort(Limit) should pick its heap orientation from the sort-key direction).

Reproduction

CREATE TABLE bigfact(a INT, b INT, c INT, v INT, PRIMARY KEY(a,b,c));  -- 200k rows via loop
-- time both:
SELECT a,b,c,v FROM bigfact ORDER BY a,b,c LIMIT 5;        -- 3 ms
SELECT a,b,c,v FROM bigfact ORDER BY a DESC,b DESC,c DESC LIMIT 5;  -- 48 ms

main @ c6683bd (2026-10-30), pymysql, medians of 3 runs, table rows 200,000.

Activity

  1. added
    kind/bug
    on Oct 30, 2026
  2. added theissue type on Oct 30, 2026
  3. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    Cache-controlled refinement of the timing in this report (same build/table, full-table warm-up pass before each measurement — eliminates block-cache noise from the earlier cold-run 105→12 ms spread):

    query (composite PK a,b,c; 200k rows, table fully warm) median of 3
    ORDER BY a,b,c LIMIT 5 3 ms
    ORDER BY a DESC,b DESC,c DESC LIMIT 5 46 ms
    ORDER BY a,b,c LIMIT 5 OFFSET 100 6 ms
    ORDER BY a DESC,… LIMIT 5 OFFSET 100 114 ms
    ORDER BY a,b,c LIMIT 5 OFFSET 199000 8 ms
    ORDER BY a DESC,… LIMIT 5 OFFSET 199000 9 ms

    Two sharpenings for the fix owner:

    1. The OFFSET variant is even worse than plain top-N (114 ms vs 46 ms, ~19× the ASC equivalent): the DESC path under Limit: 5, Offset: 100 keeps paying well past the point where a bounded top-(offset+limit) heap should have early-terminated — consistent with the DESC key missing the bounded-heap path entirely and materializing far more (or all) of the scan before applying offset+limit.
    2. The deep-OFFSET rows converge (8 vs 9 ms) because at OFFSET 199000 the "work" is dominated by the same tail blocks either way — the absolute timer there is misleading; shallow OFFSET is the discriminating case.

    EXPLAIN for all six shows the same Sort → Limit/Offset → Table Scan shape — plan-invisible, execution-only divergence. Fix expectation unchanged: honor the sort-key direction when choosing/executing the top-N (max-heap) strategy so DESC composes with Limit/Offset at the same cost as ASC.

  4. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    Layer-separation cross-link from a fresh finding: #31856 (filed just now) is the planner-side twin of this executor-side issue. Combined picture for triage:

    Note the interaction: even after this issue's executor fix, an ORDER BY indexed_col DESC LIMIT n still scans the whole table per #31856; and after #31856's planner rules land (index-order delivery incl. DESC via reverse scan), the DESC-specific top-N heap defect in this issue may become mostly unreachable through the common shapes (delivery already ordered → no Sort→Limit composition at all). Suggest coordinating both fixes; either one alone leaves the other's tax visible.

  5. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试不通过。当前 main 上,三列复合主键的倒序 Top-N 仍明显慢于正序;本轮结果正确。

    关键证据

    • 版本:main@d39d8a40343ccd40bf665036388df7a40ee867f8,隔离双 CN / 单 TN;三个新建库各 200,000 行,使用 issue 的三列复合主键及原始两条 LIMIT 5 查询,各交替运行 10 次。正序中位数 3.07–3.39 ms,倒序 44.76–48.55 ms;返回值均与独立生成的数据排序一致。
    • 可复现数据:对 issue 中的 bigfact 建表后执行 INSERT INTO bigfact SELECT MOD(result,53),MOD(result,71),result,MOD(result,13) FROM generate_series(200000) g;,再运行 issue 中的两条查询及 EXPLAIN ANALYZE。
    • 一次分析中两方向的 Table Scan 与 Sort 均输入 200,000 行;Sort 累积时间正序约 2 ms、倒序约 45 ms。此数据不支持将差异简单归因于正序提前停止扫描,具体执行原因仍需排查。另一组两列复合键数据中,两个方向的结果分别与 MySQL 8.3 一致;不同拓扑的耗时不能直接作为生产性能结论。

    待解决点

    • 排查倒序 Sort/Top-N 的额外工作,并补充相同数据量下的偏移、并列排序键和不同数据布局;本轮未覆盖实际 spill 或长稳。
  6. added a commit that references this issue on Oct 30, 2026
    a548509
  7. XuPeng-SH commented on Oct 30, 2026

    @XuPeng-SH
    Contributor

    QA handoff for merged #31847 at a54850983d9cddaacc97e38a84515ec724c937b7. This round reviewed the issue and change but did not build or run functional or performance tests at the merge SHA: available memory is beyond the existing guard. The independent d39d8a QA failure predates this merge; the PR author's benchmark and tests are separate evidence, not results from this round.

    Please compare ASC/DESC LIMIT and shallow OFFSET under matched warm conditions, and verify results against a full-sort oracle across ties, NULL, mixed keys, multiple batches, spill/cancellation and cleanup. This optimization still consumes the input; index-order planning is separately tracked by #31856. Handoff does not claim a pass or a measured performance improvement.

  8. Ariznawlll commented on Oct 31, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试通过。原 20 万行倒序 Top-N 性能问题显著改善;真实 SQL 的 spill 结果和执行中取消后的清理均通过本轮验证。

    关键证据

    • 官方 main@ae40f12a647880a63466de32a9f507c2c72dca0b,本地隔离 2 CN / 1 TN / 1 LogService;实际服务二进制完整 SHA 一致且 vcs.modified=false,修复 perf(top): prune dominated rows in verified reverse-ordered batches #31847 的合并提交 a54850983d9cddaacc97e38a84515ec724c937b7 在祖先链。
    • 原三列复合主键、20 万行、4 次预热及每项 10 个有效样本:两 CN 的 ASC/DESC LIMIT 5 中位数分别约 3.2–3.3 / 7.9–8.3 ms,OFFSET 100 约 3.3–3.4 / 9.1–9.3 ms。此前同机、同数据生成方式和拓扑的修复前 d39d8a40343ccd40bf665036388df7a40ee867f8 分别约 3.0 / 45.5 ms 和 3.0–3.1 / 92.7–93.0 ms。前后是独立 A/B 而非交错采样,不能当作生产 SLA;正倒序仍有差距,研发在 perf(top): prune dominated rows in verified reverse-ordered batches #31847 中明确不承诺方向耗时完全一致。
    • 真实 SQL LIMIT 16385 超过 Top spill 门槛,双 CN 正序和倒序各 3 轮完整结果与独立全表排序一致;每轮 EXPLAIN ANALYZE 显示非零 spill:正序 24,576 行、约 384.53 KiB,倒序 200,000 行、约 3.06 MiB。原 LIMIT 5、OFFSET 100 及 OFFSET 16385 也按独立结果逐行比较;后者没有观察到 spill,不计为 spill 通过。
    • 对实际运行的 Top 查询,先通过 CN 进程文件句柄确认已打开 top_ spill 文件,再从独立连接执行 KILL QUERY;双 CN 各 20 轮,共 40/40 返回 1317 context canceled,线程结束、Top spill 句柄回到基线、原连接可执行 SELECT 1,每轮源表仍为 200,000 行。连续一组取消前 RSS 约 143/137 MiB,结束后约 186/230 MiB、后续采样约 96/84 MiB;这不是峰值或长期泄漏证明。
    • 当前源码的 Top 包完整普通测试重复 3 次成功;spill 和取消相关定向 -race 测试重复 3 次成功。NULL、并列键、混合方向和 OFFSET 的 MOTR 回归 在两 CN 各 3 轮通过;真实 spill/取消脚本及环境限制见 MOTR #298 验证记录,该 PR 的 Go 和 Python 离线 CI 均成功。

    待解决点

    • 本次为本地隔离拓扑和指定规模,不覆盖生产拓扑、长期稳定性或普遍性能阈值;MOTR 常规用例只覆盖功能,真实 spill/取消脚本是独立验证资料,并非日常 CI 自动执行项。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triageperformance

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions