Skip to content

Stop reading early for ORDER BY a sorting key prefix with LIMIT from 1500 to max_block_size - #125415

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:read-in-order-prefix-limit-threshold
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:read-in-order-prefix-limit-threshold

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125296

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

ORDER BY over a prefix of the table's sorting key with a LIMIT between 1500 and max_block_size (for example ORDER BY l_orderkey, l_extendedprice LIMIT 10000 on a table sorted by l_orderkey) now stops reading as early as it does for other limits, instead of reading the whole table. Closes #125296.

Description

With optimize_read_in_order on a prefix of the sorting key the sort runs as PartialSortingTransform -> FinishSortingTransform -> Limit. FinishSortingTransform outputs a group of rows with an equal prefix only when it receives a row of the next group. PartialSortingTransform has its own top-K threshold filter, armed when 1500 <= limit <= block rows. After the first block it drops every row that is not below the threshold, which under read-in-order is every row of every later prefix group, so FinishSortingTransform never saw a group end and the query read the whole table. This explains both boundaries in the issue: below 1500 the filter is off, above max_block_size no block reaches limit rows.

PartialSortingTransform now gets the sorted prefix size from SortingStep::finishSorting, and when the last row of a chunk has a prefix greater than the threshold's, it keeps that one row. It is never part of the result (at least limit rows not above the threshold were already passed on), but it marks the end of the group, so FinishSortingTransform emits it and Limit stops the read. Later rows are still dropped, so the filter keeps its memory benefit, and the read still stops in Limit, so exact_rows_before_limit is unchanged. Same defect class as #100235, one layer up.

Validation (debug build, 6M rows with 4 rows per prefix value, max_threads = 1): ORDER BY a, b LIMIT 1500 read 6,000,000 rows before and 24,576 after; with max_block_size = 8192 every limit from 1500 to 8192 read 6,000,000 rows before and 16,384 after. Results are identical to a full sort. The new test fails on master and passes with the fix (84/84 randomized runs). The new perf test reads 20M rows before and 57K after.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/125415]

With read-in-order on a prefix of the sorting key, the pipeline is
PartialSortingTransform -> FinishSortingTransform -> LimitTransform.
FinishSortingTransform emits a group of rows with an equal prefix only
when it receives a row of the next group.

PartialSortingTransform has its own top-K threshold filter, armed when
1500 <= limit <= block rows. After the first block it drops every row that
is not below the threshold. Under read-in-order every row of a later
prefix group is above it, so all of them were dropped, the transform
output only empty chunks, FinishSortingTransform never saw a group end and
the query read the whole table (issue ClickHouse#125296: LIMIT 1500..65409 read all
6M rows of TPC-H lineitem, LIMIT 1499 and 65410 stopped early).

PartialSortingTransform now knows the sorted prefix size (passed from
SortingStep::finishSorting) and keeps the last row of a chunk when its
prefix is greater than the threshold's prefix. That row can never be in
the result (at least `limit` rows not above the threshold were already
passed downstream), but it marks the group end, so FinishSortingTransform
emits the group and LimitTransform stops the read. Later rows are still
dropped, so the filter keeps its memory benefit, and read termination
stays in LimitTransform, so exact_rows_before_limit is unchanged.

Same defect class as ClickHouse#100235 one layer up (reader-side __topKFilter).

Closes ClickHouse#125296

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (2 nits, not blocking).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test runs only an effective limit of 2000 (not 1500 or 8192) and accepts read_rows < 500000 DISAGREE The diff does not change the arming condition, and the new branch does not read limit, so every armed limit runs the same code. Measured on the fix: 16,384 rows at both 1500 and 8192 with max_block_size = 8192 (master: 6,000,000). Tighter bounds failed 8/50 randomized runs on the fix (Compact parts with index_granularity >= 50755 read whole granules, worst case 148,032), while master reads 1,000,000 under every randomization.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-11:20261012-122700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A MergeTree ORDER BY a table with 4 rows per a value (6M rows, one part), SELECT a FROM r ORDER BY a, b LIMIT 1500 SETTINGS max_threads = 1 reads 6,000,000 rows on master every run; LIMIT 1499 reads 24,576. With max_block_size = 8192 the boundaries are exactly 1499/1500 and 8192/8193.
b Root cause explained? PartialSortingTransform's own threshold filter (armed when 1500 <= limit <= block rows) keeps only rows below the limit-th row. Under read-in-order every row of a later prefix group is above it, so later chunks become empty, FinishSortingTransform never receives a row of the next group, never outputs, and Limit cannot stop the read.
c Fix matches root cause? Yes. The filter now keeps the chunk's last row when its sorted prefix is greater than the threshold's prefix: exactly the information FinishSortingTransform needs, restored at the place that removed it. No bound widened, no setting pinned, filter kept.
d Test intent preserved / new tests added? New stateless test 05366_read_in_order_prefix_limit_threshold (read amount per query, ASC, DESC, multi-block groups, content vs full sort, exact_rows_before_limit) and perf test read_in_order_prefix_limit.xml.
e Both directions demonstrated? Master: the three read-amount lines are 0 (1,000,000 rows each), 0/43 randomized runs pass. Fix: 84/84 randomized runs pass. Disabling only the new if turns the three lines red again.
f Fix is general across code paths? SortingStep::finishSorting covers both FinishSorting and PartitionedFinishSorting. The other constructions (full sort, StorageBuffer, ExternalDistinctTransform) have unsorted input or no limit and keep the old behaviour. The threshold-tracker branch drops no rows itself; the reader-side __topKFilter is already disabled under read-in-order (#100235).
g Fix generalizes across inputs (params/datatypes/wrappers)? ASC and reverse (DESC) in-order reads, small and large prefix groups, LIMIT ... OFFSET, random index_granularity up to 65536 on Wide and Compact parts. The prefix comparison uses the same columns, direction and nulls_direction as the existing filter; a collated column never enters the read-in-order prefix.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change. Without exact_rows_before_limit, rows_before_limit_at_least now reports the rows actually read, as it already does for LIMIT < 1500; with it the value is unchanged (tested).
i Invariants and contracts preserved? Every row that can be in the result still reaches FinishSortingTransform; only one row above the threshold per chunk is added, and its prefix is greater, so the prefix order across chunks that FinishSortingTransform relies on holds. Output size per chunk stays bounded by limit (sortBlock); read termination stays in Limit.

Session id: cron:clickhouse-impl-slot-40:20261012-105900

@groeneai
groeneai requested review from davenger and vdimir October 12, 2026 12:52
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db09a15]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR preserves a row from the next sorted-prefix group so FinishSortingTransform can emit buffered rows and let LIMIT stop reading early. One pre-existing correctness defect remains in the touched threshold-filtering path: a collated suffix can cause winning rows to be discarded. It needs a fix or explicit tracking before approval.

Missing context / blind spots
  • ⚠️ No ClickHouse binary or build directory is available locally. The runtime reproduction below was executed against the public ClickHouse 26.10.3.7 endpoint, not PR head db09a156b6cdcdad4269f2ff16c14b85ebc6dd81. The current source retains the failing comparisons; running the focused case on a head build would close the runtime verification gap.
Findings

❌ Blockers

  • src/Processors/Transforms/PartialSortingTransform.cpp:92: Threshold comparisons must use the same ordering as the sort. sortBlock honors COLLATE, but getFilterMask and compareWithThreshold compare bytes. An uncollated prefix a does not protect a collated suffix in ORDER BY a, b COLLATE 'en'. If an a = 0 group starts with enough 'b' rows to establish the threshold, later 'ä' rows are filtered out despite sorting before 'b'. The new next-prefix marker cannot recover them. This defect predates the PR, remains reachable in its prefix-sorting path, and has no identified tracking issue. Honor collation in both threshold operations or disable this filter for collated descriptions; alternatively, explicitly link a separate tracking issue.

    Read-only reproduction, using default settings:

    SELECT b, count()
    FROM
    (
        SELECT intDiv(number, 100000) AS a,
               if(number < 70000, 'b', 'ä') AS b
        FROM numbers(200000)
        ORDER BY a, b COLLATE 'en'
        LIMIT 1500
    )
    GROUP BY b;

    Observed on 26.10.3.7: b\t1500. Changing only the limit to 1499 returns the correctly ranked ä\t1499. Current-code tracing gives the same failure with a MergeTree table ordered by (a, c): 70,000 'b' rows followed by 30,000 'ä' rows within a = 0, then an a = 1 group, using max_threads = 1, max_block_size = 8192, and use_top_k_dynamic_filtering = 0.

Tests
  • ⚠️ Add a focused case with a collated suffix and a prefix group spanning multiple blocks, with the best collated values arriving after the threshold is established. Compare the result at LIMIT 1500 with an unfiltered reference; also exercise descending order. The new numeric-only regression does not cover this ordering mismatch.
Final Verdict

Status: ❌ Block

Correct the collated threshold comparisons and add focused coverage, or explicitly link a tracking issue for this pre-existing defect.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 12, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 12, 2026
The flaky check failed it with "Test runs too long (> 180s)" on
amd_debug (216 s, p50 25 s; amd_binary max 155 s). Its CI query_log
shows the two OPTIMIZE FINAL merges of 1M rows dominate (up to 106 s
each under contention), followed by the 1M-row inserts and full sorts.

Shrink both tables from 1,000,000 to 100,000 rows (large groups from
100,000 to 10,000 rows, still more than one 8192-row block) and the
read bound from 500,000 to 50,000. The bound needed half of a 1M table
only because a Compact part with a random index_granularity up to 65536
is read in whole granules; clamp index_granularity to at most 8192 with
a Random settings limits line instead.

Measured locally, debug build, randomized settings:
- fixed build, 141 runs: read_rows max 21,522 (bound 50,000), all OK
  except the local-only session_timezone 'zoneinfo/UTC' artifact;
- base build (6425af9a), 49 runs: read_rows 100,000 in every run, the
  three read lines fail in every run;
- old vs new test, 32 runs each, -j 16 on a server pinned to 8 CPUs:
  p50 1.35 s -> 0.37 s, max 2.06 s -> 0.48 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR only changes PartialSortingTransform when it is built by SortingStep::finishSorting, which is the ORDER BY-a-key-prefix-with-LIMIT read-in-order path. It keeps the last row of each block so FinishSortingTransform can still stop reading early. None of the flagged queries (ClickBench Q14, Q30, Q33, Q34 and TPC-H Q1, Q7) run that path: they are GROUP BY aggregations or joins with top-N or no LIMIT, and the edit to the regular threshold comparison keeps the same behaviour. The improvements of -10.5% to -21.0% are therefore marked not_sure: they are uniform across unrelated query shapes, both benchmarks ran on the same machine for the source build, and Q33/Q34 sit inside master's current range. The PR's own effect would only show in the new read_in_order_prefix_limit perf test.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 14 not_sure 321 283 -11.8% <0.0001 aggregation: This is a GROUP BY plus ORDER BY count LIMIT query, and the PR only changes the read-in-order prefix sort path. The -11.8% cannot come from this diff.
⚠️ 30 not_sure 228 192 -15.8% <0.0001 aggregation: This is a hash aggregation with a top-N over the result, which never builds the prefix-sorted PartialSortingTransform the PR changes. The -15.8% is not attributable to this diff.
⚠️ 33 not_sure 1134 1013 -10.7% <0.0001 aggregation: This is a GROUP BY URL aggregation, not a read-in-order sort, and the source median sits inside master's current range. The -10.7% and its CPU drop do not trace to the changed code.
⚠️ 34 not_sure 1140 1020 -10.5% <0.0001 aggregation: This is the same URL aggregation shape as Q33 and inside master's current range. The -10.5% does not involve the prefix-sorted LIMIT path this PR changes.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 55 -15.4% <0.0001 aggregation: TPC-H Q1 is a lineitem aggregation with a small final ORDER BY and no LIMIT, so the changed threshold logic never runs. Measurements are very noisy and the delta is only 10 ms.
⚠️ 7 not_sure 81 64 -21.0% <0.0001 join_operator: TPC-H Q7 is a multi-join aggregation with no read-in-order LIMIT, so the -21.0% is not explained by this diff. The query also shifts often on master.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: db7fb675-8b0f-4d02-903c-0343d6a1e605
  • MIRAI run: 98c9d8f2-d936-4f10-bfac-47cb81ee3afa
  • PR check IDs:
    • clickbench_1095719_1791827042
    • clickbench_1095725_1791827042
    • clickbench_1095731_1791827042
    • tpch_adapted_1_official_1095740_1791827042
    • tpch_adapted_1_official_1095753_1791827042
    • tpch_adapted_1_official_1095789_1791827042

@shankar-iyer shankar-iyer self-assigned this Oct 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db09a156b with master 463f45f5f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

13 translation units recompiled, 59 s compile time in total, 13 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8e087e9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / OOM in dmesg host-OOM, not from this PR: the server was killed at 46 GB during a top-K read (use_skip_indexes_for_top_k = 1) of a minmax index with GRANULARITY 4096 over 250000 one-mark ranges. That is the quadratic index read present on master, not the sorted-prefix path this PR changes #116528 (mine, open)
Integration tests (arm_binary, 1/4) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested not from this PR: the Spark 4.0 runner image of #117198 broke this test on master, and the tested tree predates both fixes #125455 (external, merged), #125456 (mine, merged)
Integration tests (arm_binary, 1/4) / test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected same cause as the row above #125455 (external, merged), #125456 (mine, merged)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05350_comparison_tuple_elimination_shared_alias flaky, not from this PR: NOT_FOUND_COLUMN_IN_BLOCK for a tuple comparison with a false constant element through remote() and parallel replicas, also on master and 10 other PRs #125195 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #116528, #125455, #125456, #125195 (per row above)

CIDB has no other FAIL or ERROR row on this head. The earlier Stateless tests (amd_debug, flaky check) red on 05366_read_in_order_prefix_limit_threshold (head c3d2b758) came from this PR's test and is fixed at this head, where all five flaky checks pass.

Session id: cron:our-pr-ci-monitor:20261012-223016

@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai Refresh branch to latest master

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged the latest master (5ba211c) into the branch, new head d9707ef. No conflicts, and the PR's own diff is unchanged; 05366_read_in_order_prefix_limit_threshold passes on a local debug build of the merged tree.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d9707ef

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test / 05345_feature_tier_settings_profile_to_all flaky, not from this PR (it changes only the read-in-order sort path): after CREATE SETTINGS PROFILE ... TO ALL the first clickhouse-local hung for 61 s at shutdown in DiskAccessStorage::stopListsWritingThread (lost wakeup of the lists-writing thread), past the 60 s Fast test limit. The same timeout hit 4 other PRs in the last 7 days #118099 (mine, open)
Mergeable Check, PR praktika rollups of the row above #118099 (mine, open)
Sync pending CH Inc sync (private, not actionable by me)

The Fast test failure dropped the rest of the matrix (167 jobs skipped), so this head has no other test results.

Session id: cron:our-pr-ci-monitor:20261020-130014

…x-limit-threshold

Resolve conflicts with ClickHouse#124829: the PartialSortingTransform constructor now takes
threshold_collector_ before sorted_prefix_size_, and finishSorting passes both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4aa53c1

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Cannot start clickhouse-server, Check failed not from this PR (it changes only the sort path): after the restart the server cannot attach a fuzzed AzureBlobStorage table whose engine arguments end with partition_strategy = 'none' (Code: 47 UNKNOWN_IDENTIFIER). The fix was merged at 18:34Z, after this run's tree was built #122707 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #122707 (mine, merged)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261103-200006

@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Dear @shankar-iyer, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai Refresh to latest master

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged the latest master (e3a18a72646) into the branch, no conflicts. New head: db09a156b6cdcdad4269f2ff16c14b85ebc6dd81.

Checked on it: 05366_read_in_order_prefix_limit_threshold passes 30/30 randomized runs, and the change is still needed: a master build (ec475edd5e3) still reads all 1,000,000 rows for ORDER BY a, b LIMIT 2 OFFSET 1998 on a table sorted by a (max_threads = 1, max_block_size = 8192), while this head reads 16,384.

for (size_t i = 0; i < num_columns; ++i)
{
int res = sort_description[i].direction * raw_block_columns[i]->compareAt(min_block_index, 0, *threshold_columns[i], sort_description[i].nulls_direction);
int res = sort_description[i].direction * raw_block_columns[i]->compareAt(row, 0, *threshold_columns[i], sort_description[i].nulls_direction);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Preserve collated ordering in the threshold filter

SortingStep::finishSorting can receive ORDER BY a, b COLLATE 'en' with an uncollated sorted prefix a. However, getFilterMask uses bytewise compareColumn, and this helper uses bytewise compareAt even for the full-description comparison at line 308. Those comparisons disagree with sortBlock, which honors the collator, so the filter can discard rows belonging in the result.

For example, on a table ordered by (a, c), let the first a = 0 group contain 70,000 rows with b = 'b', followed by 30,000 with b = 'ä', then an a = 1 group. With LIMIT 1500 and 8192-row blocks, the first block establishes (0, 'b') as the threshold. All subsequent (0, 'ä') rows are discarded, although 'ä' sorts before 'b' under 'en'. Keeping an a = 1 boundary row cannot restore those winners.

This is pre-existing in the touched path. A smaller read-only reproduction on ClickHouse 26.10.3.7 returns b\t1500; changing only the limit to 1499 correctly returns ä\t1499:

SELECT b, count()
FROM
(
    SELECT intDiv(number, 100000) AS a,
           if(number < 70000, 'b', 'ä') AS b
    FROM numbers(200000)
    ORDER BY a, b COLLATE 'en'
    LIMIT 1500
)
GROUP BY b;

Please honor collation in both threshold operations, or disable this filter for collated sort descriptions, and cover a group spanning multiple blocks. If this pre-existing defect is handled separately, link its tracking issue explicitly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is pre-existing and not reached by this change: the query above returns b 1500 on a current master build too, and the new comparison only covers the sorted prefix, which never holds a collated column (optimizeReadInOrder stops at a collator). Collation in both getFilterMask and compareWithThreshold is fixed separately in #125421.

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ORDER BY on MergeTree sort-key prefix scans entire table for smaller LIMIT

2 participants