Skip to content

Do not read in order with a prefix longer than the table's sorting key - #116364

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-read-in-order-prefix-within-sorting-key
Sep 12, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-read-in-order-prefix-within-sorting-key

Conversation

@groeneai

@groeneai groeneai commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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 Merge table over MergeTree tables 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

spreadMarkRangesAmongStreamsWithOrder clones the sorting-key expression list and calls children.resize(prefix_size). That truncates while the prefix fits, but resize grows the vector when the prefix is longer, appending null ASTPtr children. TreeRewriter::normalize then walks that AST with the Customize* 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 by requestReadingInOrder with no check against the key it indexes. ReadFromMerge::requestReadingInOrder forwards 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 in intrusive_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 Merge query. 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

  • Merged into: 26.9.1.1309 (included in 26.9 and later)
  • Backported to: 26.8.4.12, 26.7.8.19, 26.6.7.6, 26.3.33.78

groeneai and others added 3 commits August 25, 2026 13:26
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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
the guard is reverted, so the rejection contract was unverified in the PR text. A focused test is not
constructible: no SQL input is known to reach the guard (four channels probed negative), and
ReadFromMergeTree.cpp carries no failpoint to force the state from a .sql file. I instead put the
forced-state measurement in the description: 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. The description also says plainly that
the test does not exercise the new rejection.

❌ Changelog category (fixed) - the original Bug Fix category would have failed the
merge-blocking New tests check, because a preservation-arm test passes on master by design and so no
architecture can validate it. Verified by running the hook's own code: the category now yields
pr-not-for-changelog, which short-circuits it. Negative control: the old string yields pr-bugfix
and arms the check.

❌ A false mechanism claim (fixed) - an earlier draft blamed a missing per-query metadata cache on
the fuzzer's context. That is wrong: executeQuery.cpp:3044-3047 installs the cache gated only on
enable_shared_storage_snapshot_in_query, which defaults to true and which the fuzzer never changes.
The claim is gone; the description now states that the trigger is not identified.

⚠️ Test determinism (fixed) - added SYSTEM STOP MERGES so a background merge cannot collapse the
two parts and silently skip the preliminary-merge path, and pinned explain_query_plan_default in both
EXPLAIN arms. The pin is load-bearing: under a legacy profile the assertion returns 0 without it.

💡 Two proposed additional guards (declined, with evidence) - one asked for a second guard on the
legacy ReadInOrderOptimizer channel. That channel exists but the scenario needs a sorting key to get
shorter between two reads of the same snapshot, and MergeTreeData::checkProperties:1086-1098 only
ever extends a key; 60 concurrent key-extending ALTERs against 400 readers produced no
over-request. The other asked to narrow the bound to the primary key, as an adjacent open PR does; the
crash site reads the sorting key in all three of its uses, and the primary key is a prefix of it, so
narrowing would refuse legitimate requests.

💡 Link format (declined) - the description uses Related: #114058, #111457 rather than two
full-URL lines. The template's full-URL instruction governs its own placeholder block, which is
unchanged above; a bare #NNNNN auto-links within this repository, and no CI check parses either form.

Session id: cron:clickhouse-review-slot-10:20260825-163300

@clickhouse-gh clickhouse-gh Bot closed this Aug 25, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Yes, via a forced over-long prefix at the Merge push-down site (100% reproducible). No SQL input at default settings reaches it; probed four candidate channels, all negative with positive controls. The trigger behind the reported crash is not identified.
b Root cause explained children.resize(prefix_size) on a cloned sorting-key expression list grows the vector when the prefix exceeds the key, appending null ASTPtr elements that TreeRewriter::normalize's visitors then dereference.
c Fix matches root cause Refuses the request where the unvalidated prefix would become durable state, rather than guarding the dereference site.
d Test intent preserved / tests added No test weakened or removed. The new test is a preservation arm: it pins that read-in-order is still chosen for a well-formed Merge query, with a control that returns 0 when the optimization is off. 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.
e Both directions demonstrated Same query and fixture: aborts without the change (stack matches the reported one frame for frame), returns rows identical to the optimize_read_in_order = 0 baseline with it.
f General across code paths The receiving step refuses, covering the unbounded producer and any future one. All six callers verified to handle a refusal. ReadFromObjectStorageStep keeps its own prefix bounded by its own key. The two further out-of-bounds reads in the same block are covered once the prefix cannot exceed the key.
g General across inputs Sorting-key shapes probed: plain tuple, tuple(...), expression, function, single column. Key-name count equals expression-list child count wherever the reader is reached. Empty key is refused upstream and by the guard alike.
h Backward compatible No setting, default, format or serialization change, so no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved The check runs before any mutation of input_order_info, query_task_size_limit, reader_settings.read_in_order or enable_vertical_final, so a refusal leaves the step untouched, matching the reverse-order-with-FINAL refusal above it.

Validation: new test 50/50 runs with randomized settings, plus 25/25 after the review round's test
changes, with both new elements negative-controlled (the explain_query_plan_default pin asserts
nothing without it under a legacy profile; SYSTEM STOP MERGES is confirmed to pin two parts, and
to emit no output). read_in_order (64 tests) and
storage_merge (20 tests) suites run against both a pristine and a patched binary, build IDs
asserted per arm: identical pass and failure sets on both, so no behaviour change. The failures in
those sets are pre-existing environment gaps on this host (missing stateful dataset, absent
parallel-replicas cluster) and are present without this change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @azat, could you review this? ReadFromMerge::requestReadingInOrder forwards the parent Merge prefix to every child reader unchecked, and a prefix longer than a child's sorting key makes children.resize(prefix_size) grow the cloned key expression list with null ASTPtr elements that TreeRewriter::normalize then dereferences, so this refuses the request before it becomes durable state.

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [69fb1a3]

Summary: ✅


AI Review

Summary

This PR rejects ReadFromMergeTree read-in-order requests whose prefix is longer than the receiving table's sorting key, preventing the downstream key-prefix slicing from growing the cloned AST with null children. I reviewed the current diff, the StorageMerge pushdown path, the ReadFromMergeTree consumers of used_prefix_of_sorting_key_size, and the prior PR discussion, and I did not find any remaining correctness or safety issues in the current code.

Missing context / blind spots
  • ⚠️ I did not reproduce the forced-state failure locally. The rejection path is still evidenced by the manual forced-prefix validation described in the PR, because no SQL-level reproducer is currently known.
Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 3/4 (75.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 69fb1a35b with master 583fc5270 (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
Binary Master PR Δ
programs/clickhouse-stripped 710.09 MiB 707.05 MiB -3.04 MiB (-0.43%)

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 units

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

Job report

Comment on lines +3773 to +3777
/// 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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Show me the link to CIDB, maybe I can reach the url.

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.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

It is very much real.

@alexey-milovidov

Copy link
Copy Markdown
Member

And of course it is a severe bug - segmentation fault is not a joke.

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit eea50a0 Sep 12, 2026
359 of 360 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both sites are unguarded in every currently supported release branch, so this is not master-only: ReadFromMerge::requestReadingInOrder forwards the parent prefix, and order_key_prefix_ast->children.resize(prefix_size) grows on it with no bound against the child reader's own sorting key, in 26.8, 26.7, 26.6 and 26.3.

It also reached trunk a few hours before the merge: Segmentation fault (STID: 2076-288c) on Stress test (arm_msan) at master 3476b12ea2ce, 2026-09-12 13:11:06Z (job). That is the first true-master row of the 9 recorded since 2026-09-06; the other 8 sit on 7 distinct PR heads, across arm and amd, msan/tsan/asan_ubsan/debug.

Would you apply vX.Y-must-backport for the branches you want covered?

Separately, I set the changelog category back to Bug Fix in the description. It was Not for changelog only because the merge-blocking New tests check rejects a preservation-arm test, and that no longer applies.

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
PedroTadim added a commit that referenced this pull request Sep 14, 2026
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]>
PedroTadim added a commit that referenced this pull request Sep 14, 2026
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]>
PedroTadim added a commit that referenced this pull request Sep 14, 2026
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]>
PedroTadim added a commit that referenced this pull request Sep 14, 2026
Cherry pick #116364 to 26.6: Do not read in order with a prefix longer than the table's sorting key
PedroTadim added a commit that referenced this pull request Sep 14, 2026
Cherry pick #116364 to 26.7: Do not read in order with a prefix longer than the table's sorting key
PedroTadim added a commit that referenced this pull request Sep 14, 2026
Cherry pick #116364 to 26.3: Do not read in order with a prefix longer than the table's sorting key
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #116364 to 26.8: Do not read in order with a prefix longer than the table's sorting key
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #116364 to 26.6: Do not read in order with a prefix longer than the table's sorting key
PedroTadim added a commit that referenced this pull request Sep 14, 2026
Backport #116364 to 26.3: Do not read in order with a prefix longer than the table's sorting key
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #116364 to 26.7: Do not read in order with a prefix longer than the table's sorting key
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Sep 15, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 19, 2026
`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]>
alexey-milovidov added a commit that referenced this pull request Sep 23, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Oct 4, 2026
…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]>
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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog 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.

7 participants