Skip to content

[Performance]: outer LIMIT not pushed into derived table with ORDER BY #32014

Closed

Description

@Ariznawlll

Summary

An outer LIMIT is not pushed into a derived table containing ORDER BY: the inner sort materializes the full million-row result before the limit applies, costing 5.6× more than the same query written without the derived table.

Environment: main@HEAD (c6683bd), etc/launch-multi-cn.

Reproduction

-- big1m: 1,000,000 rows, PK k
SELECT * FROM (SELECT * FROM big1m ORDER BY k DESC) t LIMIT 10;  -- 73.6 ms
SELECT * FROM big1m ORDER BY k DESC LIMIT 10;                     -- 13.2 ms

Both return the identical 10 rows. The derived-table form should be rewritten to the direct form (or LIMIT merged into the inner ORDER BY as a top-N), since the derived table has no DISTINCT/GROUP BY/window semantics that would make row count observable before the outer limit. Wrapping paginated queries in a subquery — a very common generated-SQL pattern — silently loses the top-N path.

Activity

  1. added
    kind/bug
    on Nov 2, 2026
  2. added this to the MO-202611 milestone on Nov 2, 2026
  3. added theissue type on Nov 2, 2026
  4. added
    severity/s0
    and removed on Nov 5, 2026
  5. added a commit that references this issue on Nov 5, 2026
    61e31d2
  6. assigned and unassigned on Nov 5, 2026
  7. slyunnn commented on Nov 6, 2026

    @slyunnn

    Regression and extended verification for #32014 (2026-11-06)

    Verification Environment

    • Frozen latest origin/main at test start, b6c57d315c8d1df2aca40ab19dee72136e6f2f81, fix(disttae): preserve optimistic RC write dependencies across snapshot advances (#32174). The clean verification worktree matched this commit. Rebuilt the native service; build log, binary version and runtime git_version() identified b6c57d315c.
    • macOS arm64, Go 1.27.1, fresh local disk deployment with 2 CN / 1 TN / 1 Log service / Proxy, service GOMAXPROCS=4.
    • Proxy 127.0.0.1:6001, CN1 127.0.0.1:16001 and CN2 127.0.0.1:16002 were connected and version-checked. Original SQL, direct extensions and the selected BVT below actually executed through each endpoint.
    • Clients used PyMySQL text protocol and mo-tester JDBC. Binary pagination checks used Go database/sql + go-sql-driver/mysql, interpolateParams=false, real COM_STMT_PREPARE / COM_STMT_EXECUTE.

    What Was Covered

    • OK — Created the original 1,000,000-row shape with unique primary key k and an additional k2=MOD(k,1000) column/index for the paired statistics issue. The table was flushed and analyzed. The exact derived SELECT * FROM (SELECT * FROM big1m ORDER BY k DESC) t LIMIT 10 and direct query returned the identical independent expected final 10 keys at every endpoint.
    • OK — Logical plans attached Limit: 10 to the inner sort. Executed physical plans used local top, global merge top and mcpu=4 worker pipelines. They avoided the unbounded sort producing the full million-row result. All three coordinators passed these mechanism assertions.
    • OK — Positive, zero, tail and beyond-end pagination composed correctly across inner/outer LIMIT and OFFSET. Filtering and computed-order controls retained their expected rows. Existing BVT covered additional nested and prepared windows.
    • OK — Real binary prepared recursive-CTE pagination reused limits 2 → 0 → 1 → 0 → 3 on the same statement at every endpoint, returning the expected rows and completing without a hang. A second prepared statement reused different LIMIT/OFFSET windows. The recursive zero-demand compiler regression passed 100 repetitions under -race.
    • OK — Deliberate missing-column error 1054 preserved connection health and source row count. Test databases were cleaned up.
    • Not covered — A historical-runtime speedup benchmark, production latency/QPS, TKE and a single query distributed across both CNs. Runtime evidence established actual parallel workers on the selected CN; both CNs were independently used as coordinators.

    Findings

    • PR fix(plan): push outer pagination into derived-table sorts #32230 merged as 61e31d219a2072bd11f4d0dcf8a619ca52a28a47, fix(plan): push outer pagination into derived-table sorts, included in the tested main. It composes pagination into eligible column-only derived sorts and preserves safety barriers and zero-demand producer cleanup. Fix PR
    • Local warm median observations from 3 runs after warm-up were approximately 0.48–0.60 ms for the derived form and 0.44–0.55 ms for the direct form across the endpoints. These shared-host diagnostic timings accompany the stronger physical TopN evidence; the historical 5.6× comparison is not treated as a same-machine benchmark.
    • Filters, aggregation/window boundaries, computed ordering and specialized vector-search candidate budgets were checked by the owning planner tests. The optimization applies within those eligibility guards.

    MOTR / BVT Coverage

    • Reused test/distributed/cases/dml/select/offset_without_limit.sql and its committed result. All 56/56 statements passed twice through each endpoint, totaling 336 successful comparisons, including metadata. No statements were ignored or abnormal.
    • Full pkg/sql/plan and pkg/sql/compile suites passed with -count=1. Relevant named tests covered public planning, rewrite boundaries, parameter reuse, physical consumers and interval-estimation domains. Two existing unrelated planner subtests were skipped for HNSW cosine similarity and interval-frame binding.
    • Existing maintained regressions were sufficient. No duplicate MOTR case/source commit or weekly PR update was added. MatrixOne tracked files remained clean.
    • Preparation and independent package checks used bounded parallelism. Scale queries ran sequentially. BVT ran sequentially because the runner performs global database cleanup. Actual engine worker evidence is reported separately from runner scheduling.

    Final Conclusion

    Fixed for the outer-pagination/derived-sort regression on b6c57d315c8d1df2aca40ab19dee72136e6f2f81, including the recursive zero-demand safety boundary.

    Large-data regression was required and completed at the original 1,000,000 rows because the reported cost depends on full-sort materialization. Actual parallel TopN and bounded sorted outputs were observed. Additional arbitrary enlargement or TKE performance testing is unnecessary for this scoped regression.

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

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions