Skip to content

Test the read-in-order prefix guard from SQL - #119682

Merged
alexey-milovidov merged 3 commits into
masterfrom
test-read-in-order-prefix-guard
Sep 19, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
test-read-in-order-prefix-guard

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

Related: #116364

#116364 made ReadFromMergeTree::requestReadingInOrder refuse a prefix wider than the read's own
sorting key, but shipped with a preservation arm only: no SQL input was known to reach the guard, so
the test there passes on master by design and would not fail if the guard were reverted. This adds a
test that does fail.

What reaches the guard

spreadMarkRangesAmongStreamsWithOrder cuts the sorting key down to the announced prefix with
order_key_prefix_ast->children.resize(prefix_size), which grows the expression list with null
ASTPtrs when the prefix is longer than the key. TreeRewriter::normalize then walks them until one
of the Customize* visitors dereferences a node, and the server segfaults.

The channel 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):

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 is the query from the master stress report below, and EXPLAIN indexes = 1 over that fixture
confirms the child read is the projection (PrimaryKey Keys: session_id), not the table.

What the test uses instead

Which projection the optimizer picks is not something a test should depend on, so the test takes the
second channel, 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, and the test asserts the order
the children were planned in so the choreography cannot silently stop covering the bug.

With the guard reverted, the server dies mid-query, frame for frame the reported stack:

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 consumes the prefix; without them need_preliminary_merge is false and
the vulnerable block does not run.

The test is no-parallel because it waits on a process-global PAUSEABLE failpoint, so a concurrent
instance pausing or resuming the same channel would break the synchronisation.

The crash on public CI

Between 2026-09-05 and 2026-09-12 it was reported 12 times, on master and on 10 pull requests
(STID: 2076-288c, 2076-3a72, 2447-4aac):

SELECT pull_request_number, check_name, check_start_time, test_name
FROM default.checks
WHERE check_start_time > now() - INTERVAL 30 DAY
  AND test_status IN ('FAIL', 'ERROR')
  AND position(test_context_raw, 'spreadMarkRangesAmongStreamsWithOrder') > 0
  AND position(test_context_raw, 'InDepthNodeVisitor') > 0
ORDER BY check_start_time

Master report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3476b12ea2ce2ab61713714166e91b4712105c74&name_0=MasterCI&name_1=Stress%20test%20%28arm_msan%29

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Added a regression test for a read-in-order prefix wider than the sorting key of the read that has to honor it, reached through an Alias child of a Merge table.


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

Version info

  • Merged into: 26.10.1.190 (included in 26.10 and later)

`ReadFromMergeTree::requestReadingInOrder` refuses a prefix wider than the read's own sorting key
since #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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a21d5f2]

Summary: ✅


AI Review

Summary

This PR adds a deterministic stateless regression test for the widened read-in-order prefix guard on Merge children by racing an Alias target swap against child-plan creation, then checking both the query result and the system.text_log spread-mode witness from the same query. I did not find any remaining correctness, coverage, or metadata issues in the current diff.

Final Verdict

✅ Approve. No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Sep 12, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 12, 2026
alexey-milovidov and others added 2 commits September 19, 2026 03:29
The `planned:` lines only proved the child-planning choreography: a plain `Sorting` fallback returns
the same five rows and the same two lines, so the test would keep passing if the planner stopped
calling `requestReadingInOrder` for this shape. Measured on the unraced shape, that is not
hypothetical - it spreads both children with `Spreading mark ranges among streams (default reading)`
and never reaches the read-in-order path.

Each `ReadFromMergeTree` logs which way it spread its mark ranges, so the raced query leaves a
direct witness in `system.text_log`: `z_plain`, whose sorting key is as wide as the announced
prefix, logs `Spreading ranges among streams with order`, while the alias child - one column short
of the prefix - is the one the guard sends back to the default path. Assert that pair of counts;
if the shape ever stops reading in order both counts move and the test fails instead of passing
vacuously.

Also pin `enable_parallel_replicas = 0` and `automatic_parallel_replicas_mode = 0` on the query
under test: the harness randomizes them on, and re-planning the children through `ClusterProxy`
changes both the `planned:` lines and the new spreading counts.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119682&sha=42757a345dbb20e868e799595de982d5e5b355d3&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is unrelated to this PR, which only adds a stateless test - the failure is a logical error in PatchJoinCache::Entry::addBlock:

Logical error: 'Block structure mismatch in patch join cache stream: different names of columns:
_row_exists UInt8 UInt8(size = 168)
_part_data_version UInt64 UInt64(size = 356)'

CIDB shows it is a rare pre-existing stress flake rather than something this branch introduced - STID: 0993-30f7 has fired twice in 90 days, once here on 2026-09-12 and once on the unrelated #115627 on 2026-08-21. I could not find an open issue tracking it; one is probably worth filing.

@groeneai

Copy link
Copy Markdown
Collaborator

No fix is in progress, so there is nothing to link yet. #115979 is the only other open PR in the patch-parts area and it does not touch PatchJoinCache (it changes DataPartStorageOnDiskPacked, IMergeTreeDataPart and MergeTreeData), so I am deliberately not linking it as the fix. I will open a separate PR and link it here.

Root cause

PatchJoinCache is created once per read pool (MergeTreeReadPoolBase.cpp:67) and shared by every read task, and getEntries keys an entry by the patch part name alone (MergeTreePatchReader.cpp:261). The cached block, however, is produced from each read task's own task_columns.patch_columns[i] (MergeTreeReadTask.cpp:287), and that column set is built in addPatchPartsColumns, where _row_exists is conditional:

/// MergeTreeBlockReadUtils.cpp:430
if (has_lightweight_delete && patch_part_columns.has(RowExistsColumn::name))
    patch_columns_to_read_set.insert(RowExistsColumn::name);

has_lightweight_delete is a property of the main part, not of the patch part:

/// MergeTreeReadPoolBase.cpp:235
bool has_lightweight_delete = data_part->hasLightweightDelete() || read_task_info.alter_conversions->hasLightweightDelete();

So when one Join-mode patch part is shared by two main parts and only one of them carries a lightweight delete, the two read tasks build different headers for the same cache entry, and addBlock compares them positionally at PatchJoinCache.cpp:269. That produces exactly the reported pair: _row_exists is present in one block and absent in the other, so the comparison lands _row_exists against _part_data_version at the same position.

There is a second, independent source of divergence: patch_columns_to_read_names is materialized from a NameSet, which is std::unordered_set, so the column order is not stable across tasks even when the set is equal.

I read the assertion as correct and the divergent header as the defect, so I plan to make the patch read header a function of the patch part alone rather than relax the check. The same positional comparison at the sibling site was already normalized in getUpdatedHeader by 6af4d39 (headers.push_back(header.sortColumns()), plus failpoint patch_parts_reverse_column_order and test 04034_patch_parts_column_order_mismatch) for clickhouse-core-incidents#1021; PatchJoinCache::Entry::addBlock kept the unnormalized compare from 44954c9.

On the frequency

The family is larger than a single STID suggests: the assertion message embeds the column names, so each column pair hashes to its own STID. Querying on the message text instead gives 4 hits in 180 days across 4 unrelated PRs:

SELECT check_start_time, pull_request_number, check_name FROM checks
WHERE check_start_time > now() - INTERVAL 180 DAY
  AND test_context_raw ILIKE '%patch join cache stream%'
date PR check STID
2026-09-13 #119785 Stress test (amd_tsan) 0993-2bfd
2026-09-12 #119682 Stress test (arm_msan) 0993-30f7
2026-08-21 #115627 Stress test (arm_debug) 0993-30f7
2026-03-30 #100366 Stress test (amd_msan) 0993-329c (different number of columns)

All four are debug or sanitizer builds, which matches the check sitting under #ifdef DEBUG_OR_SANITIZER_BUILD. In a release build it is compiled out and the divergent blocks are cached together silently, so on the PR I will also check whether an entry can serve a block without _row_exists to a task that needs it.

I would rather have the fix PR be the tracking artifact than open an issue next to it, but say the word and I will file one.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@groeneai

Copy link
Copy Markdown
Collaborator

Opened #121044.

Two corrections to my comment above, both measured:

  • The has_lightweight_delete && gate is not the defect and cannot diverge between two tasks that share a patch part: AlterConversions::addPatchPart puts _row_exists into all_updated_columns and hasLightweightDelete() reads exactly that, so a task reading a patch part that carries _row_exists always has the flag set. The defect is the second source I listed: the block structure is a property of the reading task (order from a NameSet, set from that part's read set, types from its own perform_alter_conversions), while the cache entry was keyed by the patch part name alone.
  • On a release build the divergent blocks are not served silently. getUpdatedHeader re-checks the same divergence unconditionally, so the query fails with Code: 49, Block structure mismatch in patch parts stream (measured on the official amd_release master build), server unaffected.

So the fix makes the structure part of the entry key rather than relaxing the check, and addBlock becomes a true invariant check. 04991_patch_join_cache_structure_mismatch is red on unfixed master with the reported signature and green with the fix.

Merged via the queue into master with commit 5cca0a8 Sep 19, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the test-read-in-order-prefix-guard branch September 19, 2026 17:23
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-testing Test content only (no production code). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-build Pull request with build/testing/packaging improvement 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.

3 participants