Repository navigation
Fix wrong ORDER BY and LIMIT BY results over Merge tables whose underlying table is read from a projection - #122520
Conversation
…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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260927-101700 |
|
Workflow [PR], commit [60c67ae] Summary: ❌
AI ReviewSummaryReviewed #122520 at Final VerdictStatus: ✅ Approve. No new inline findings. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units17 translation units recompiled, 146 s compile time in total, 17 of them have a recent master baseline. |
CI finish ledger - 82827c0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 172 check runs completed (131 pass, 39 not selected, 2 red: the row above and its rollup), Session id: cron:our-pr-ci-monitor:20260927-153205 |
|
Fixing PR for the |
… 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]>
|
@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. |
`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]>
|
Done in 699c32f. For the probe,
|
CI finish ledger - 699c32fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261015-200013 |
|
@alexey-milovidov give the final review |
|
@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. |
|
I measured it and kept the check on the current metadata, because comparing against the The prefix that Repro with the failpoint of 05210 (script below): the
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 |
CI finish ledger - 60c67aeEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261018-070007 |
fce8462
Related: #116364
Related: #119682
Related: #105867
Closes: #125950
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results of
ORDER BYandLIMIT BYover aMergetable or themergetable function when an underlying table is read from a normal projection with a differentORDER 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 3over a tableORDER BY awith a projectionORDER BY bfailed withLogical 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 BYandLIMIT BYovermerge()or aMergetable return wrong rows when an underlying table is read from a normal projection with anotherORDER BY; an in-orderDISTINCTover 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 12overmerge()returns1,2,3,4,5,6,7,8,9,1,0,0instead of twelve zeros, andORDER BY a LIMIT 1 BY areturns 5000 rows instead of 10.A
Mergechild plan is optimized when it is created, so a projection read may already have replaced the table read.ReadFromMerge::requestReadingInOrderthen forwards a prefix counted against the child table's sorting key, and the projection read applies it to its own key. NowReadFromMerge::canReadInOrder, which thetopKThroughJoinprobe 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.requestReadingInOrderstill leaves a read key shorter than the prefix to the read itself (#116364), so05210_merge_read_in_order_prefix_wider_than_keyfrom #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
26.11.1.218-master(included in26.11and later)