Repository navigation
Do not read in order with a prefix longer than the table's sorting key - #116364
alexey-milovidov merged 3 commits into
Conversation
spreadMarkRangesAmongStreamsWithOrder clones the sorting-key expression list and calls children.resize(prefix_size) on it. That is written as a truncation to the leading key columns and behaves as one while the prefix fits, but resize grows the vector when the prefix is longer, and the element type is ASTPtr, so the appended children are null. TreeRewriter::normalize then walks that AST with the Customize* visitors, which dereference every child unconditionally. The same block also indexes the sorting-key column names and reverse flags over the same range, so an over-long prefix is two further out-of-bounds reads. The prefix arrives verbatim from InputOrderInfo::used_prefix_of_sorting_key_size, which requestReadingInOrder stored without checking it against the sorting key it will later be applied to. ReadFromMerge::requestReadingInOrder forwards the parent's prefix to every reader recursivelyApplyToReadingSteps finds, and is the only caller not already bounded by the receiving reader's own key. Refuse such a request before any state is mutated, so the caller falls back to an explicit sort. Refusal is already this function's idiom for a request it cannot serve (reverse order with FINAL), and all six callers handle it. The guard newly refuses only requests whose prefix the table's own sorting key cannot provide. Of those, the ones that reach preliminary merge or per-partition output dereference a null AST node today; the remainder lose the read-in-order optimization and fall back to an explicit sort, which is correct but may be slower. No SQL input is currently known to produce such a request at default settings, so the causal chain is demonstrated by forcing an over-long prefix at the push-down site: the resulting stack matches the reported one frame for frame, including the CustomizeFunctionsData visitor and the ReadFromMerge frames, and the same query returns rows identical to the optimize_read_in_order = 0 baseline with this change. Debug builds abort inside intrusive_ptr::operator->; release and sanitizer builds report the dereference as a segmentation fault. Found by the AST fuzzer. Its fuzzed queries execute on a context built by Context::createCopy plus makeQueryContext, which does not install the per-query metadata cache that otherwise keeps the optimizer's and the reader's sorting-key reads consistent. The added test pins that read-in-order is still chosen for a well-formed Merge query, with a control asserting the check is not vacuous. It does not reach the guard, since no SQL does.
…erts The EXPLAIN predicate matches the "Read type:" spelling, which is produced only when explain_query_plan_default is 'pretty'. Under a 'legacy' profile the predicate matched nothing and the assertion silently passed on an empty match, so both EXPLAIN arms now pin the setting. Stopping merges keeps the two inserted parts distinct, so the preliminary merge path that consumes the sorting-key prefix stays covered rather than depending on whether a background merge has run. The per-setting random-settings clamp line was dead: the no-random-merge-tree-settings tag already disables merge-tree randomization and the CREATE pins index_granularity explicitly. Such clamps fail silently when they do not apply, so it is removed rather than left as decoration. Co-Authored-By: Claude Fable 5 <[email protected]>
The repository rulebook (AGENTS.md, a symlink to .claude/CLAUDE.md) requires literal class and function names to be wrapped in inline code blocks. The comment added with the guard wrote prefix_size and ASTPtr as bare words; the surrounding file already follows the rule. Comment-only. Verified by stripping comments from both revisions and comparing the resulting token streams, which are identical at 194572 bytes; a control mutating one code token in the guard does change them.
Internal second-model review (3 rounds, all findings resolved)An independent model reviewed this change cold in three rounds. Findings and how I resolved them: ❌ Test liveness (raised twice, fixed) - the added test is a preservation arm and cannot fail if ❌ Changelog category (fixed) - the original ❌ A false mechanism claim (fixed) - an earlier draft blamed a missing per-query metadata cache on
💡 Two proposed additional guards (declined, with evidence) - one asked for a second guard on the 💡 Link format (declined) - the description uses Session id: cron:clickhouse-review-slot-10:20260825-163300 |
Pre-PR validation gate
Validation: new test 50/50 runs with randomized settings, plus 25/25 after the review round's test |
|
cc @antaljanosbenjamin @azat, could you review this? |
|
Workflow [PR], commit [69fb1a3] Summary: ✅
AI ReviewSummaryThis PR rejects Missing context / blind spots
Final Verdict✅ No findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 3/4 (75.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 34 s compile time in total, 7 of them have a recent master baseline. |
| /// The prefix indexes this snapshot's sorting key, and a clone of its expression list is resized | ||
| /// to `prefix_size`, which appends null `ASTPtr` children when the prefix is longer than the key. | ||
| if (prefix_size > storage_snapshot->metadata->getSortingKey().column_names.size()) | ||
| return false; | ||
|
|
There was a problem hiding this comment.
I have doubt about this being a real issue without a reproduction. It seems like a super big bug that went unnoticed for a long time.
There was a problem hiding this comment.
It is an observed segmentation fault, not an inference. It came from a Stress test (amd_tsan, meta in keeper) run on master on 2026-08-25, in a CI instance whose reports are not public, so I have no report URL to give you. I also checked the public CI database: 0 rows in 90 days for this signature, with a control on the same frames returning rows, so that zero is real rather than a broken probe. Symbolized stack:
vector<intrusive_ptr<DB::IAST>>::begin()
InDepthNodeVisitor<OneTypeMatcher<CustomizeFunctionsData<countdistinct>, ...>>::visitChildren<false>() InDepthNodeVisitor.h:83
DB::TreeRewriter::normalize(...) TreeRewriter.cpp:1669
DB::TreeRewriter::analyze(...) TreeRewriter.cpp:1614
ReadFromMergeTree::spreadMarkRangesAmongStreamsWithOrder(...) ReadFromMergeTree.cpp:2107
ReadFromMergeTree::spreadMarkRanges(...) ReadFromMergeTree.cpp:4249
ReadFromMergeTree::initializePipeline(...) ReadFromMergeTree.cpp:5182
ReadFromMerge::buildPipeline(...) StorageMerge.cpp:1599
ReadFromMerge::initializePipeline(...) StorageMerge.cpp:758
DB::executeASTFuzzerQueries(...) executeQuery.cpp:3557
You can check the fault itself without waiting for the fuzzer. Three lines in ReadFromMerge::requestReadingInOrder emulate the channel:
size_t forced_prefix = order_info_->used_prefix_of_sorting_key_size;
if (const char * env = getenv("CH_PROBE_FORCE_PREFIX"))
forced_prefix = static_cast<size_t>(atoi(env));With CH_PROBE_FORCE_PREFIX=4 against a 3-column key, an unpatched build reproduces the stack above frame for frame, CustomizeFunctionsData<countdistinct> template argument included. A debug build aborts one frame deeper, in intrusive_ptr::operator->, instead of faulting. The patched build returns the same rows as the same query with optimize_read_in_order = 0.
On the age. children.resize(prefix_size) has been able to grow since a51a6ea0b78f (2021), but the only caller that can hand it an over-long prefix arrived in 8d19566c7da6 (2023-09): ReadFromMerge::requestReadingInOrder forwards the parent's prefix to every reader below it, and of the six call sites it is the only one that does not pass a prefix computed from the reader it pushes into. Reaching the fault also needs preliminary merge or per-partition output, and buildInputOrderFromSortDescription bails out unless every member agrees and bounds the prefix by that member's own key. The remaining way to get a mismatch is the key growing between the child snapshot and that check, and both reads pass bypass_metadata_cache = false (StorageMerge.cpp:1016, optimizeReadInOrder.cpp:1071), so at the default enable_shared_storage_snapshot_in_query they return the same handle.
So I could not construct a SQL trigger and I am not claiming one: four candidate channels probed negative, each with a control. My reading is a latent defect that the server-side fuzzer reached, which is consistent with nobody hitting it in the nearly three years since.
That makes it your call. If you would rather not carry a refusal for a path with no known SQL input, say so and I will close this, and reopen if it fires again with the query captured. One thing worth knowing if you are weighing something smaller: clamping the prefix instead of refusing is worse, because a genuine member would then read in order with a shorter prefix than the plan promised, turning a fault into wrong results.
There was a problem hiding this comment.
Show me the link to CIDB, maybe I can reach the url.
There was a problem hiding this comment.
Two different instances, and only one of them has a URL I can give you.
Public CI database, play.clickhouse.com. These you can open directly. The signature, both frames together, 90 days:
SELECT count() FROM default.checks
WHERE check_start_time > now() - INTERVAL 90 DAY
AND test_context_raw LIKE '%spreadMarkRangesAmongStreamsWithOrder%'
AND test_context_raw LIKE '%TreeRewriter%'Run it -> 0
Control, same window, crash-site frame on its own:
SELECT count() FROM default.checks
WHERE check_start_time > now() - INTERVAL 90 DAY
AND test_context_raw LIKE '%spreadMarkRangesAmongStreamsWithOrder%'Run it -> 35
Both re-run today, 2026-08-26. The 35 control rows spread over 10 checks between 2026-07-04 and 2026-08-24 (Bugfix validation amd64 and aarch64, 12 each; Stateless asan_ubsan 3; Fast test 2; AST fuzzer amd_debug, amd_tsan, arm_asan_ubsan; Stress amd_tsan, arm_asan_ubsan), and not one of them carries TreeRewriter or InDepthNodeVisitor. So the frame is searchable there and this pairing has genuinely not appeared, rather than the probe being broken or the column being empty.
The sighting itself is on a CI instance whose reports are not public, which is why I gave you no URL for it: I do not have one. If you can reach that instance, this is the row:
SELECT * FROM default.checks
WHERE check_name = 'Stress test (amd_tsan, meta in keeper)'
AND test_name = 'Segmentation fault (STID: 2076-288c)'
AND check_start_time BETWEEN '2026-08-25 07:00:00' AND '2026-08-25 09:00:00'head_ref = master, 2026-08-25 08:02:15 UTC, one row, no PR attached. The handoff I got did not carry the commit sha, so that predicate is the most precise key I can hand you.
For completeness, the STID is not in the public instance either: Run it -> 0.
|
It is very much real. |
|
And of course it is a severe bug - segmentation fault is not a joke. |
eea50a0
|
Both sites are unguarded in every currently supported release branch, so this is not master-only: It also reached trunk a few hours before the merge: Would you apply Separately, I set the changelog category back to |
Keep only the sorting-key prefix guard from #116364. The master-only `widened_over_previous_request` block came along with it, but its consumer (`resetVirtualRowConversions`) does not exist on 26.3, so it would be an unused variable. Adapt the test: `explain_query_plan_default` is new in 26.7, and 26.3 prints `ReadType: ` unconditionally rather than `Read type: `. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Keep only the sorting-key prefix guard from #116364. The master-only `widened_over_previous_request` block came along with it, but its consumer (`resetVirtualRowConversions`) does not exist on 26.7, so it would be an unused variable. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Keep only the sorting-key prefix guard from #116364. The master-only `widened_over_previous_request` block came along with it, but its consumer (`resetVirtualRowConversions`) does not exist on 26.6, so it would be an unused variable. Adapt the test: `explain_query_plan_default` is new in 26.7, and with `pretty` off by default 26.6 prints `ReadType: ` rather than `Read type: `. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Cherry pick #116364 to 26.6: Do not read in order with a prefix longer than the table's sorting key
Cherry pick #116364 to 26.7: Do not read in order with a prefix longer than the table's sorting key
Cherry pick #116364 to 26.3: Do not read in order with a prefix longer than the table's sorting key
…han the table's sorting key
…han the table's sorting key
…han the table's sorting key
Backport #116364 to 26.8: Do not read in order with a prefix longer than the table's sorting key
Backport #116364 to 26.6: Do not read in order with a prefix longer than the table's sorting key
Backport #116364 to 26.3: Do not read in order with a prefix longer than the table's sorting key
Backport #116364 to 26.7: Do not read in order with a prefix longer than the table's sorting key
…x longer than the table's sorting key
`ReadFromMergeTree::requestReadingInOrder` refuses a prefix wider than the read's own sorting key since ClickHouse#116364. That guard went in with a preservation arm only, because no SQL input was known to reach it: `spreadMarkRangesAmongStreamsWithOrder` does ```cpp size_t prefix_size = input_order_info->used_prefix_of_sorting_key_size; auto order_key_prefix_ast = storage_snapshot->metadata->getSortingKey().expression_list_ast->clone(); order_key_prefix_ast->children.resize(prefix_size); ``` and `resize` grows the list with null `ASTPtr`s when the prefix exceeds the key, which `TreeRewriter::normalize` then walks until one of the `Customize*` visitors dereferences a node. There are two such inputs. The one the server-side fuzzer reached is projections: `ReadFromMerge` optimizes a child plan when it creates it, so `optimizeUseNormalProjections` can already have replaced the read of the table with a read of a projection by the time `ReadFromMerge::requestReadingInOrder` walks the plan, and nothing relates the two sorting keys. In the `02784_projections_read_in_order_bug` fixture the table is ordered by `(organisation_id, session_id, timestamp)`, so the prefix is 3, while the child plan reads the `events_by_session` projection, ordered by `(session_id, timestamp)`: ```sql SELECT id, timestamp, payload FROM merge(currentDatabase(), '^events$') WHERE organisation_id = reinterpretAsUUID(1) AND session_id = reinterpretAsUUID(0) ORDER BY timestamp ASC, payload ASC, id ASC NULLS LAST -- read_in_order_two_level_merge_threshold = 1 ``` That input depends on which projection the optimizer picks, so the test uses the other one, which is deterministic. An `Alias` child resolves its target by name twice - once when `createChildrenPlans` builds its child plan, once when `buildInputOrderFromSortDescription` reads `getInMemoryMetadataPtr` to compute the prefix - so an `EXCHANGE TABLES` between the two leaves a read with a one-column sorting key holding a two-column prefix. The already-present `storage_merge_create_children_plans_pause` failpoint pins the moment. Reverting the guard makes the test fail: the server dies mid-query, frame for frame the stack the stress tests reported. ``` Address: 0x10. Access: <not available>. Address not mapped to object. boost::container::vector<boost::intrusive_ptr<DB::IAST>>::end() DB::InDepthNodeVisitor<...CustomizeFunctionsData<countdistinct>...>::visitChildren<false> DB::TreeRewriter::normalize DB::ReadFromMergeTree::spreadMarkRangesAmongStreamsWithOrder DB::ReadFromMerge::buildPipeline ``` `read_in_order_two_level_merge_threshold = 0` and `read_in_order_use_virtual_row_per_block = 0` pin the preliminary merge that cuts the sorting key down to the announced prefix; without them `need_preliminary_merge` is false and the vulnerable block does not run. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Conflict resolution: - `MergingSortedAlgorithm.cpp`: master only fixed the message whitespace of `checkVirtualRowCoversSortDescription`; this branch removes that check, keep it removed. - `ReadFromMergeTree::requestReadingInOrder`: keep this branch's handling of a re-request (keep the conversion on widening, reject a re-request that would revoke it), drop master's output/input-count based reset from #119195, and keep master's new early return for a prefix longer than the sorting key (#116364). - `04549_virtual_row_distinct_in_order_boundary`: take master's smaller data (#117742), keep this branch's cases, and keep master's EXPLAIN pair but assert that the widened read keeps its virtual row conversion, as this branch intends. - `05153_virtual_row_widened_prefix_constant_order_by` (new on master): the widened read now keeps the one-column conversion, and the results still match the unoptimized read. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ReadInOrder` preflight The preflight only mirrored the reverse-order-with-`FINAL` rejection. After the `master` merge, `ReadFromMergeTree::requestReadingInOrder` also refuses a sorting key prefix longer than the table's own key (#116364), so the preflight accepted, a child then refused, and the `chassert(ok)` in `ReadFromMerge::requestReadingInOrder` fired (`Logical error: 'ok'`), e.g. in `Stateless tests (amd_debug, sequential)`: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100394&sha=c55009350c685384a20eb6af2c2700cee385d4de&name_0=PR Factor the conditions into `ReadFromMergeTree::canReadInOrder` and let the preflight ask each reader, so the two can no longer drift apart. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a segmentation fault when reading in order from a
Mergetable overMergeTreetables whose sorting key is shorter than the key prefix chosen for the query: the prefix was forwarded to the underlying reader unchecked, which grew its cloned sorting-key expression list to that length and appended null AST nodes that were then dereferenced.Description
Related: #114058, #111457
spreadMarkRangesAmongStreamsWithOrderclones the sorting-key expression list and callschildren.resize(prefix_size). That truncates while the prefix fits, butresizegrows the vector when the prefix is longer, appending nullASTPtrchildren.TreeRewriter::normalizethen walks that AST with theCustomize*visitors, which dereference every child. The same block also indexes the key column names and reverse flags over that range, so an over-long prefix is two further out-of-bounds reads.The prefix comes from
InputOrderInfo::used_prefix_of_sorting_key_size, stored byrequestReadingInOrderwith no check against the key it indexes.ReadFromMerge::requestReadingInOrderforwards the parent's prefix to every reader below it, and is the only caller not bounded by that reader's own key.This refuses such a request before it mutates state; refusal is already this function's idiom, and all six callers handle it. Of the requests refused, those reaching preliminary merge or per-partition output dereference a null AST node today; the remainder work correctly now and will fall back to an explicit sort, which may be slower.
The fuzzed query text was not captured, so the trigger is not identified, and I could not construct one from SQL at default settings. The crash is therefore shown by forcing an over-long prefix at the push-down site: with a prefix of 4 against a 3-column key, the unpatched build aborts with a stack matching the reported one frame for frame, and the patched build returns the same rows as the same query with
optimize_read_in_order = 0. Debug builds abort inintrusive_ptr::operator->; release and sanitizer builds report a segmentation fault.The added test is a preservation arm: it pins that read-in-order is still chosen, and results unchanged, for a well-formed
Mergequery. It does not exercise the new rejection, since no SQL input is known to reach it, so it would not fail if this change were reverted.Workflow [PR]
Sync PR [sync-upstream/pr/116364]
Version info
26.9.1.1309(included in26.9and later)26.8.4.12,26.7.8.19,26.6.7.6,26.3.33.78