Skip to content

Fix wrong ORDER BY and LIMIT BY results over Merge tables whose underlying table is read from a projection - #122520

Merged
PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-merge-read-in-order-projection
Oct 19, 2026
Merged

PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-merge-read-in-order-projection

Conversation

@groeneai

@groeneai groeneai commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116364
Related: #119682
Related: #105867
Closes: #125950

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results of ORDER BY and LIMIT BY over a Merge table or the merge table function when an underlying table is read from a normal projection with a different ORDER BY.

Description

Found by AST fuzzer (amd_debug, targeted) on #122486, not caused by it (job, report): SELECT DISTINCT b, a, _part_offset FROM merge(...) WHERE b < 5000 LIMIT 3 over a table ORDER BY a with a projection ORDER BY b failed with Logical error: 'Equal values are not contiguous within the range assumed to be sorted'.

On 26.6 and later (and on 25.3 and later with an explicit PREWHERE), ORDER BY and LIMIT BY over merge() or a Merge table return wrong rows when an underlying table is read from a normal projection with another ORDER BY; an in-order DISTINCT over such a read raises the logical error above in debug and sanitizer builds. On the official 26.6.8 image, with the new test's fixture, ORDER BY a LIMIT 12 over merge() returns 1,2,3,4,5,6,7,8,9,1,0,0 instead of twelve zeros, and ORDER BY a LIMIT 1 BY a returns 5000 rows instead of 10.

A Merge child plan is optimized when it is created, so a projection read may already have replaced the table read. ReadFromMerge::requestReadingInOrder then forwards a prefix counted against the child table's sorting key, and the projection read applies it to its own key. Now ReadFromMerge::canReadInOrder, which the topKThroughJoin probe also asks (#125383), checks every child read before any is switched and refuses if a read's key disagrees with its table's key within the prefix. requestReadingInOrder still leaves a read key shorter than the prefix to the read itself (#116364), so 05210_merge_read_in_order_prefix_wider_than_key from #119682 is unchanged.

The new test fails on master (wrong rows, then the server aborts in LIMIT BY) and passes with the fix, 50 of 50 randomized runs.


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

Version info

  • Merged into: 26.11.1.218-master (included in 26.11 and later)

groeneai and others added 5 commits September 27, 2026 06:32
…th another key

`ReadFromMerge::requestReadingInOrder` counts the read-in-order prefix against each
child table's sorting key and forwards only its length to every child
`ReadFromMergeTree`. A child plan that selected a normal projection interprets that
length against the projection's key, so it reads in the projection's order while the
outer `ORDER BY`, `LIMIT BY`, `DISTINCT` or aggregation relies on the table's order.
Through `merge()` and `Merge` tables this returned wrong rows, and debug builds aborted
with "Equal values are not contiguous within the range assumed to be sorted".

Check every child read before switching any of them: accept the request only when each
read's sorting key starts with the same columns, in the same directions, as the sorting
key of its table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…own check

The pre-check refused a request as soon as one child read's sorting key was shorter than the prefix,
before any read was switched. `ReadFromMergeTree::requestReadingInOrder` already refuses that read
itself, after the other children are switched, which is what
`05210_merge_read_in_order_prefix_wider_than_key` asserts. Compare only the columns the read's key has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each result query over one table is followed by the EXPLAIN of the same
query. It fails unless the plan reads projection `p`
(`force_optimize_projection_name`), and it must show a read that is not
in order. The setting cannot go on the queries themselves: a Merge child
plan is optimized again when its pipeline is built, and that pass applies
no projection, so the check fails on every build. EXPLAIN builds no
pipeline. A projection whose ORDER BY starts with the table's sorting key
is checked to be still read in order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A table sorted by `a DESC` with a projection sorted by `(a, b)` has
the same leading column name in both keys but opposite directions.
Through `merge()` the projection read must not be read in order
for `ORDER BY a DESC`. Master reads it ascending while the query
relies on descending order. This is the only case that covers the
direction comparison of the pre-check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the Merge read-in-order pre-check comment to two lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 27, 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; 3 findings over three runs, none on the final head) plus my own cold reviews (3 nits).

# Sev Finding Verdict Evidence / action
1 ❌ An Alias target retargeted A, then B, then back to A between the order builder's metadata lookup and the pre-check's lets the pre-check pass against the wrong key DISAGREE The pre-check can only return false, so that schedule gives master's result, and a single retarget (wrong on master) is now refused; the window comes from Alias resolving its target on every call (StorageAlias.h:140-147, as 05210 documents) and involves no projection.
2 ⚠️ No line proves the projection is read, so the result lines could go vacuous AGREE, fixed @ 47c5d52 Each single-table result query is followed by its EXPLAIN with force_optimize_projection_name = 'p', which must show a read that is not in order (on the SELECT through merge() the setting throws: the child plan is optimized again when its pipeline is built).
3 ⚠️ The test does not exercise the direction comparison of the key check AGREE, fixed @ 9d78eba t_desc (table ORDER BY a DESC, projection ORDER BY (a, b)) must not be read in order for ORDER BY a DESC; master reads it ascending, and a build whose check ignores directions fails only this case.
4 💡 No positive control for a projection whose ORDER BY starts with the table's key AGREE, fixed @ 47c5d52 t_agree control: still read in order
5 💡 Half of the helper's size check cannot fire from its clamped caller DISAGREE The helper stays a symmetric two-key predicate; its other half refuses a table key re-resolved shorter than the prefix
6 💡 The check also refuses a read whose key differs only in a column the WHERE clause fixes (table (a, b), projection (c, b), WHERE a = 1 AND c = 2 ORDER BY b) AGREE, no change Results stay correct because the query sorts instead; keeping that read in order needs matching against each read's own key, a plan change for existing queries.

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

Session id: cron:clickhouse-review-slot-8:20260927-101700

@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [60c67ae]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) FAIL
03821_drop_workload_during_query_race FAIL cidb IGNORED
01168_mutations_isolation_3 NOT_FAILED cidb IGNORED

AI Review

Summary

Reviewed #122520 at 60c67ae6cad32a5736eaf29386227f6128259074. The change prevents ordered-read optimizations over Merge from trusting a projection whose sorting-key prefix differs from its source table's, preserving correct ORDER BY, LIMIT BY, and other order-dependent results. No unresolved findings remain. The previous topKThroughJoin capability-probe finding is fixed and covered by the added plan assertions. Existing CI evidence records 50 successful regression-test runs; no local build or tests were run during this review.

Final Verdict

Status: ✅ Approve. No new inline findings.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-storage-merge Merge table engine (logical union over tables) and related mechanics. labels Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 60c67ae6c with master 54c2b7d7b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 76cb67e41; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 82827c0

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
Stateless tests (arm_asan_ubsan, azure, parallel) / 04344_server_ast_fuzzer_insert_limit flaky timeout, not caused by this diff: the test's own block-forming INSERT ... SELECT into a MergeTree table ran past the test's max_execution_time = 20 (Code: 159, elapsed 20573 ms, maximum 20000 ms), and 0 of 3 reruns failed. This diff changes only the in-order read of merge()/Merge tables. In the last 30 days this test failed on 2 PRs, both on this lane, and on 0 of 14,993 true-master runs a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
PR rollup, red only because of the row above a fix task is moved to pending (the same one as for the row above)

All 172 check runs completed (131 pass, 39 not selected, 2 red: the row above and its rollup),
Finish Workflow and Mergeable Check are green, and CH Inc sync passed. CIDB has one FAIL
test row on this head, the row above.

Session id: cron:our-pr-ci-monitor:20260927-153205

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stateless tests (arm_asan_ubsan, azure, parallel) / 04344_server_ast_fuzzer_insert_limit row of the CI finish ledger above (and so for its PR rollup row): #122567

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 29, 2026
… lock wait)

On the `Stateless tests (arm_asan_ubsan, azure, parallel)` lane MergeTree
tables default to the `azure_cache` policy, whose disk `cached_azure` is a
write-through filesystem cache (cache_on_write_operations = 1). Every file a
part writes is registered in the cache priority queue by
LRUFileCachePriority::add, which takes the queue lock exclusively. Debug and
sanitizer builds run FileCache::assertCacheCorrectness from
FileCache::getOrSet/get with probability check_cache_probability (0.001), and
its second pass walks the whole queue under that lock shared, checking the
file of every entry on disk. With ~42k entries on that IO-saturated host a
pass takes ~2.3 s (1,086 passes, 2,517 s of checking and 7,673 s of priority
write-lock wait server-wide in one job), so each of the ~11 files of a 100-row
part can wait seconds. The test bounds its seed statements with the session
max_execution_time = 20, and the seed INSERTs failed with Code 159:

- 2026-09-27, PR ClickHouse#122520: block-forming INSERT, elapsed 20,575 ms, of which
  20,454 ms was FilesystemCachePriorityWriteLockMicroseconds
- 2026-09-17, PR ClickHouse#104076: plain INSERT, elapsed 28,097 ms, 28,011 ms waiting

The trace_log of the 2026-09-27 query shows its writer thread in
SharedMutex::lock <- LRUFileCachePriority::add <- FileCache::doTryReserve <-
FileSegment::reserve <- CachedOnDiskWriteBufferFromFile::cacheData in 21 of 21
samples, and the part's 11 blob uploads took 1.6-2.9 ms each, so the time is
the cache lock, not object storage latency. In the same jobs, parts on the
local `default` disk took at most 104 ms / 54 ms, versus 20.6 s / 33.5 s on
cached_azure.

Pin t_04344 to the implicit local `default` storage policy. Where its parts
live is incidental to what the test verifies (stripping of seed SETTINGS on
the INSERT, block-forming, CREATE storage and BACKUP carriers), so its
INSERTs, their fuzzed clones, the BACKUP and the teardown DROP no longer touch
the cache, and no time bound is widened: the session max_execution_time = 20
still bounds the fuzz loop. t_04344_storage keeps the lane's default policy,
because its SETTINGS clause must hold only max_rows_to_read for the
empty-SETTINGS pruning carrier.

Reproduced locally on a debug build with the CI test configs, the
write-through local_cache as the MergeTree default, check_cache_probability =
1, ~335k cache entries and 8 concurrent readers of a cached table: the
unmodified test failed 4 of 5 runs with Code 159 on a seed INSERT (elapsed
31.8-50.4 s, 98.9-99.3% of it priority write-lock wait, same stack as CI).
With this change it passed 3 of 3 under the same load, while 8 of 9
seed-shaped INSERTs into a cached table in the same windows waited 24-47 s.
With check_cache_probability = 0 and the same cache and readers, the
unmodified test passed 3 of 3 with seed INSERT lock waits under 0.4 s.

ClickHouse#114077 raised the INSERTs' bound instead, reading this wait as Azure
latency; it was closed after two quiet months and the test failed twice since.

Related: ClickHouse#114077

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim PedroTadim self-assigned this Oct 15, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️

The fix is right, and the new test still fails on current master. One request: could the key check go into ReadFromMerge::canReadInOrder rather than only into requestReadingInOrder?

canReadInOrder was added in #125383, after this PR was opened. It is documented as "whether requestReadingInOrder accepts", and the topKThroughJoin probe depends on that (topKThroughJoin.cpp:490). When it returns true, the probe doesn't push Sort + Limit below the LEFT JOIN and leaves the work to read-in-order in pass 2. With this PR, a Merge child that reads a projection whose key differs from its table's still passes canReadInOrder, so the probe skips the push, and pass 2's requestReadingInOrder then refuses. The result is correct, but both optimizations are lost.

Passing the InputOrderInfo (or just used_prefix_of_sorting_key_size) into canReadInOrder would keep the two in sync. canReadInOrder would do the key check next to the direction check, and the probe would pass the order it already got from getInputOrderIfReadInOrderIsUseful.

Comment thread src/Storages/StorageMerge.cpp Resolved
`canReadInOrder` is what the `topKThroughJoin` probe asks before it leaves
the top-N below a `LEFT JOIN` to read-in-order. The sorting-key check ran only
in `requestReadingInOrder`, so for a child that reads a projection with another
key the probe deferred, pass 2 then refused, and both optimizations were lost.

`canReadInOrder` now takes the `InputOrderInfo` and does the key check next to
the direction check. For the probe it also refuses a read key shorter than the
prefix, which `ReadFromMergeTree::requestReadingInOrder` refuses later anyway.
`requestReadingInOrder` keeps leaving that case to the read itself, so the
other children are still switched first, as `05210` expects.

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

Copy link
Copy Markdown
Collaborator Author

Done in 699c32f. canReadInOrder now takes the InputOrderInfo and does the key check next to the direction check. requestReadingInOrder calls it, and the topKThroughJoin probe passes the order it got from getInputOrderIfReadInOrderIsUseful.

For the probe, canReadInOrder also refuses a read key that is shorter than the prefix (a projection ORDER BY a on a table ORDER BY (a, b), queried with ORDER BY a, b), because pass 2 refuses that read too. requestReadingInOrder still leaves that case to ReadFromMergeTree::requestReadingInOrder, so 05210 still sees the other child switched first.

05264 has three new plan lines for the LEFT JOIN probe. The projection child and the shorter-key child now get the inner Sort + Limit (2 2; it was 1 1 on 273448c), and the same query without the projection still defers (1 1).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 699c32f

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
Performance Comparison (arm_release, master_head, 1/6) / sparse_column_index_runs #5 not from this PR (it changes ordered reads over Merge, this query is an ARRAY JOIN over lazily replicated columns): a master regression that arrived with master 06a0224 (#124727). Master's own run of that commit shows 37 ms -> 53 ms (this PR: 38 ms -> 51 ms), as do 6 other PRs whose CI started in the same 30 minutes a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (same as above)

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

Session id: cron:our-pr-ci-monitor:20261015-200013

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 1/6) / sparse_column_index_runs #5 row of the CI finish ledger above (and so for its Mergeable Check, PR rollup row): #126160. It restores the per-output-block cut of lazily replicated ARRAY JOIN passengers that #124727 removed.

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov give the final review

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️ canReadInOrder takes each table's sorting key from getInMemoryMetadataPtr(context, false), the table's current metadata. The child plan was built earlier, in createChildrenPlans, from the metadata snapshot of that moment. If an ALTER TABLE ... MODIFY ORDER BY lands in between, the check compares the read's key against a newer table key than the one the plan was built with.

I don't think this can produce wrong results. MODIFY ORDER BY can only append newly added columns, so the prefix of existing columns stays the same, and a read key shorter than the prefix is refused. Still, it would be cleaner if the check and the plan used the same metadata, for example by keeping the snapshot used for each child in ChildPlan and comparing against that. Then the result no longer depends on when the metadata is read.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I measured it and kept the check on the current metadata, because comparing against the ChildPlan snapshot alone returns unsorted rows.

The prefix that requestReadingInOrder gets is computed from each table's current metadata too: buildInputOrderFromSortDescription(ReadFromMerge *) and buildInputOrderFromUnorderedKeys(ReadFromMerge *) (optimizeReadInOrder.cpp:1221 and :1300). So the check has to use the metadata the prefix came from. For a MergeTree child that is the plan's snapshot anyway: with enable_shared_storage_snapshot_in_query = 1 (the default) both lookups return the per-query cached snapshot. They differ for an Alias child, which resolves its target by name on every call.

Repro with the failpoint of 05210 (script below): the Alias child plan is built over a table ORDER BY a, then EXCHANGE TABLES makes the alias name a table ORDER BY b; the other child is ORDER BY b; the query is ORDER BY b.

build result 05210
this PR (60c67ae) sorted, the request is refused OK
check against the ChildPlan snapshot not sorted by b (both reads in order, the alias one by a) OK
prefix builders and check both on the snapshot sorted FAIL: spread default: 2, spread with order: 0

The third row makes everything use one metadata, but then the widened prefix in 05210 never reaches the alias child, so its witness has to change. If you prefer that version, I'll push it with 05210 updated.

Repro (3/3 runs per build)
C=clickhouse-client; FP=storage_merge_create_children_plans_pause
$C -n -q "
CREATE TABLE target (a UInt32, b UInt32) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 4;
CREATE TABLE target_b (a UInt32, b UInt32) ENGINE = MergeTree ORDER BY b SETTINGS index_granularity = 4;
CREATE TABLE z_plain (a UInt32, b UInt32) ENGINE = MergeTree ORDER BY b SETTINGS index_granularity = 4;
INSERT INTO target SELECT number, 1000 - number FROM numbers(0, 20);
INSERT INTO target SELECT number, 1000 - number FROM numbers(20, 20);
INSERT INTO target SELECT number, 1000 - number FROM numbers(40, 20);
INSERT INTO target_b SELECT number, 1000 - number FROM numbers(0, 60);
INSERT INTO z_plain SELECT number, 1000 - number FROM numbers(60, 40);
CREATE TABLE a_alias ENGINE = Alias(currentDatabase(), 'target');
CREATE TABLE m (a UInt32, b UInt32) ENGINE = Merge(currentDatabase(), '^(a_alias|z_plain)\$');"
$C -q "SYSTEM ENABLE FAILPOINT $FP"
$C -q "SELECT b, a FROM m ORDER BY b SETTINGS max_threads = 4, max_block_size = 8,
    read_in_order_two_level_merge_threshold = 0, read_in_order_use_virtual_row_per_block = 0" > out.txt &
$C -q "SYSTEM WAIT FAILPOINT $FP PAUSE"; $C -q "SYSTEM NOTIFY FAILPOINT $FP"
$C -q "SYSTEM WAIT FAILPOINT $FP PAUSE"; $C -q "EXCHANGE TABLES target AND target_b"
$C -q "SYSTEM DISABLE FAILPOINT $FP"; wait
cut -f1 out.txt | sort -n -c && echo sorted

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 60c67ae

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
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) / 03821_drop_workload_during_query_race flaky, not from this PR (it changes ordered reads over Merge): a racing query fails with the expected INVALID_SCHEDULER_NODE after DROP WORKLOAD, and the test's line filter lets the server's stack trace through to stdout (3/61 reruns failed) #126345 (mine, open)
Mergeable Check, PR praktika rollups of the row above #126345 (mine, open)

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

Session id: cron:our-pr-ci-monitor:20261018-070007

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 19, 2026
Merged via the queue into ClickHouse:master with commit fce8462 Oct 19, 2026
176 of 178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
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-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ORDER BY/GROUP BY over Merge wrong when the child reads a projection

3 participants