Skip to content

Compare read-in-order virtual row on its covered sort-key prefix - #111457

Draft
vdimir wants to merge 38 commits into
masterfrom
vdimir/vrow-prefix-fix
Draft

vdimir wants to merge 38 commits into
masterfrom
vdimir/vrow-prefix-fix

Conversation

@vdimir

@vdimir vdimir commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

Closes: #106740
Closes: #106630
Closes: #116155
Related: #110725

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

Fix a wrong result (mis-ordered merge) for read-in-order queries with a virtual row when distinct-in-order or LIMIT BY widens the read to a longer sort-key prefix than ORDER BY set it up for, and when a key column fixed by the filter is skipped by ORDER BY (e.g. WHERE b = 1 ORDER BY a, c on key (a, b, c)). The virtual row announced a wrong merge boundary: in release builds the merge could be silently mis-ordered, in debug builds the boundary assertion fired, and a Nullable key column after the skipped one threw the Virtual row has different type exception. The virtual row optimization now stays enabled in these cases.

Description

Alternative to #110725: instead of dropping the virtual row conversion when the in-order read prefix changes (and disabling it for skipped key columns), keep the optimization enabled and compare the virtual row only on the sort-key prefix it validly covers.

Root cause. The read-in-order virtual row announced a wrong merge boundary in two ways:

  1. Widened prefix. optimizeReadInOrder builds the virtual row conversion for the prefix ORDER BY needs (e.g. CounterID). A later optimization (optimizeDistinctInOrder, optimizeLimitByInOrder) re-requests the read with a longer prefix (CounterID, EventDate), but the pk_block width was derived from the conversion's input count, so the extra sort column was default-filled with 0 in setVirtualRow. In reverse order 0 understates the real values, so a real row exceeded the announced boundary: Virtual row boundary violated in MergingSortedAlgorithm ... the virtual row announced UInt64_0 but the source then produced UInt64_1 in debug builds, a silently mis-ordered merge in release builds.
  2. Skipped fixed key. For key (a, b, c) and WHERE b = 1 ORDER BY a, c, the fixed key b is skipped without an ORDER BY counterpart, but the conversion DAG indexed key columns densely, mapping c onto key column b (visible in EXPLAIN actions=1: input b aliased to __table1.c). The wrong value tripped the boundary check; a wrong type (Nullable key) threw the Virtual row has different type logical error even in release builds. Moreover, index values of the columns after the skipped key are semantically unusable: the index describes pre-filter data, so the entry (5, 0, 9) does not bound the filtered row (5, 1, 3) projected to (a, c).

Fix.

  • The virtual row conversion outputs only the sort-description prefix it can announce exactly: index values while the key prefix is contiguous, plus constants for fixed columns from ORDER BY. A skipped fixed key column ends the index-backed part: the index entry at a mark boundary may hold a filtered-out value for it, so its later components bound nothing in the filtered stream. A column fixed by the filter that stays in ORDER BY keeps disabling the virtual row, as before this fix.
  • The merge compares a virtual row only on the covered prefix and places it first on a covered-prefix tie (equivalent to treating the uncovered columns as minus infinity in the merge order, without materializing any values). The covered prefix is derived from the pk block column names in MergingSortedAlgorithm and carried per cursor in SortCursorImpl::sort_prefix_limit, honored by the generic SortCursor::greaterAt. A truncated virtual row can only occur with a multi-column sort description (its coverage is at least the first column), which always uses the generic cursor, so the single-column specialized queues are unaffected; the JIT comparator is bypassed when a truncated cursor participates.
  • ReadFromMergeTree::readInOrder reads index values for the whole used sorting-key prefix instead of only the conversion inputs. The in-order merges inside the read step sort by the full prefix, and index values are exact bounds for it even after filtering (a filter only removes rows), so these merges always see fully covered virtual rows.
  • ReadFromMergeTree::requestReadingInOrder drops the conversion only when a re-request makes it unsound: a prefix narrower than the one it was built for (the conversion could lose its inputs), or one not fully backed by the primary index.
  • setVirtualRowConversions builds the conversion with project_inputs so a raw index column cannot shadow a same-named conversion output when the merge looks sort columns up by name (matters with the old analyzer).

This handles all key types uniformly — e.g. a descending String column after a skipped key keeps the optimization even though the type has no greatest value to pad with.

Verified on release and debug builds (the boundary assertion is compiled only into debug builds): the previously aborting repros now return correct results, and EXPLAIN keeps Virtual row conversions for the widened and skipped-key reads. The test is based on the one from #110725, extended with checks that the optimization stays enabled, a descending skipped-key case, a String case in both directions, and a fixed key kept in ORDER BY (still disabled, as before).


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

vdimir and others added 2 commits July 22, 2026 17:28
…keys

The read-in-order virtual row could announce a wrong merge boundary in
two cases: a later optimization (distinct-in-order, LIMIT BY) widening
the read to a longer sort-key prefix than the conversion was built for,
and a fixed key column skipped by ORDER BY (WHERE b = 1 ORDER BY a, c on
key (a, b, c)), which mapped later sort columns onto wrong key columns.
Both tripped "Virtual row boundary violated in MergingSortedAlgorithm"
in debug builds and could silently mis-order the merge in release
builds; a Nullable key threw "Virtual row has different type" even in
release builds.

Keep the optimization instead of disabling it: read index values for the
whole used key prefix (exact bounds for the in-order merges inside the
read step), announce sort columns after a skipped key as extreme
constants of their sort direction, and drop the conversion only when a
re-requested prefix makes it unsound. The virtual row is disabled
fail-close when no extreme is representable (e.g. no greatest String).

Alternative to: #110725

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7405685]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py FAIL

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
Replace the extreme-constant padding with covered-prefix semantics: the
virtual row conversion outputs only the sort-description prefix it can
announce exactly (index values while the key prefix is contiguous, and
the constant a filter fixes a column to - extracted from the equals
condition - for fixed columns), and the merge compares the virtual row
only on the covered prefix, placing it first on a tie. This handles any
key type uniformly (e.g. a descending String column after a skipped key
no longer disables the optimization) and avoids encoding comparator
semantics into padded values.

The covered prefix is derived at the merge from the pk block column
names, carried per cursor in SortCursorImpl::sort_prefix_limit and
honored by the generic SortCursor::greaterAt. Truncation can only occur
with a multi-column sort description, which always uses the generic
cursor, so the single-column specialized queues are unaffected; the JIT
comparator is bypassed when a truncated cursor participates.

Co-Authored-By: Claude Fable 5 <[email protected]>
@vdimir vdimir changed the title Keep read-in-order virtual row valid for widened prefixes and skipped fixed key columns Compare read-in-order virtual row on its covered sort-key prefix Jul 22, 2026
vdimir and others added 2 commits July 23, 2026 10:59
Restore the pre-existing behavior: a column fixed by the filter that
stays in ORDER BY disables the virtual row, as on master. Announcing it
with the constant extracted from the filter condition would be a new
feature, not part of this bug fix. Drop the FixedColumns value map and
the constant extraction; the covered-prefix truncation remains only for
the cases where the virtual row used to be applied and produced a wrong
boundary: the widened in-order prefix and the skipped fixed key.

Co-Authored-By: Claude Fable 5 <[email protected]>
…imit

Keep the sort cursor machinery untouched: instead of carrying a covered
sort prefix in SortCursorImpl and honoring it in the comparators, a
virtual row that covers only a prefix of the sort description does not
enter the sorting queue at all. MergingSortedAlgorithm remembers its
boundary per source and does not emit rows that are not strictly below
every announced boundary on its covered prefix; reaching a boundary
fetches the real data of that source (the boundary is cleared before
requesting, so an exhausted source cannot stall the merge). Virtual
rows covering the full sort description ride the queue as before.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.20% 78.30% +0.10%

Changed lines: Changed C/C++ lines covered: 126/146 (86.30%) · Uncovered code

Full report · Diff report

robot-clickhouse and others added 4 commits August 5, 2026 16:35
The merge of master (6b600a1) kept both the old #110725 block, which
references the deleted widened_over_previous_request variable, and its
replacement guard above, so every build of the PR failed with 'use of
undeclared identifier'. Keep only the replacement: the covered-prefix
comparison makes the old sample-block-width heuristic unnecessary.

Co-Authored-By: Claude Fable 5 <[email protected]>
…al row

The arm_debug stress test keeps hitting STID 2651-3359 through a fuzzed
variant of this test's own query: ORDER BY 1 ASC, CounterID DESC fuzzed
into ORDER BY toIntervalMinute(1) > toIntervalWeek(59) ASC, CounterID DESC.
The constant first key becomes an extra conversion output, so the merged
sample-block-width guard from #110725 miscounted the covered key prefix
and kept the conversion that announces nothing for EventDate. Reproduced
on the master arm_debug build of 38b6b20; fixed by the covered-prefix
comparison in this PR.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=38b6b2033bca801499eae3c06559c99a57be8328&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29

Co-Authored-By: Claude Fable 5 <[email protected]>
…ster merge

The 6b600a1 master merge resolved the fixed-key conflict in
buildInputOrderFromSortDescription to master's side (#110725's blanket
can_optimize_virtual_row = false from c87e2ed), dropping this branch's
key_index_values_usable = false. That silently reverted the PR's behavior:
the virtual row stayed disabled for skipped-middle-key reads and the
EXPLAIN assertions in 04549 expecting 'Virtual row conversions' failed.
Verified against a synthesized clean merge of the pre-merge tip with
current master: this was the last divergence in src.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Master keeps hitting the boundary assertion this PR fixes — near-daily in stress tests since 2026-07-20 (tracked by #106630, e.g. today's arm_debug stress report). The harness fuzzes the query ORDER BY 1 ASC, CounterID DESC from 04549_virtual_row_distinct_in_order_boundary into ORDER BY toIntervalMinute(1) > toIntervalWeek(59) ASC, CounterID DESC. The constant first ORDER BY key becomes an extra output of the virtual row conversion, so the getSampleBlock().columns() < prefix_size guard from #110725 miscounts the covered key prefix and keeps the stale conversion: EventDate is default-filled and the reverse-order merge announces UInt64_0 as the boundary. I reproduced it with the master arm_debug build of 38b6b20; this PR fixes that shape by design, since the merge compares the virtual row only on the covered prefix.

Since the PR was blocked, I pushed three commits (plus a master merge) to unblock it:

  • The 6b600a1e81f master merge had taken master's side in both conflict regions, which broke every build (use of undeclared identifier 'widened_over_previous_request' — the block from Reset stale virtual row conversion when in-order read prefix is widened #110725 survived while this PR removes its declaration) and silently dropped key_index_values_usable = false for skipped fixed keys, reverting this PR's behavior there (the EXPLAIN assertions in 04549 expecting Virtual row conversions failed on the merged branch). Restored both; I checked against a synthesized clean merge of the pre-merge tip (875686579f7) with current master that no other change was lost.
  • Added the fuzzed constant-first-key shape to 04549 as a regression case. It aborts on the master arm_debug debug build and passes with this PR.

Verified on a local aarch64 debug build (boundary assertions compiled in): the fuzzed query returns correct results with the optimization enabled, and 04549_virtual_row_distinct_in_order_boundary, 03031_read_in_order_optimization_with_virtual_row{,_explain,_special}, 03581_read_in_order_use_virtual_row_WHERE, 03794_read_in_order_virtual_row_and_sparse_primary_key_msan pass via clickhouse-test, both with default and randomized settings.

I also added Closes: #106630 to the description so the tracking issue closes on merge.

Resolved conflicts with #113291: keep this PR's covered-prefix comparison
(`sort_prefix_limit`) and drop the strict `checkVirtualRowCoversSortDescription`
debug check it supersedes; adopt master's `do_debug_checks` constexpr style and
the `setVirtualRow` pk-block return both sides introduced.
…ead of dropping it

The AI review Major: `requestReadingInOrder` kept the conversion based on the
logical primary-key width, while `readInOrder` and
`MergeTreeSelectProcessor::buildVirtualRowFromIndex` silently skipped the
virtual row for every part whose loaded index is shorter than the widened
prefix (`optimizeIndexColumns` drops near-unique suffix index columns, ratio
default 0.9), leaving the plan-level decisions (read-in-order through inner
join, skipped preliminary merge in per-block mode) believing virtual rows
exist. Now the virtual row degrades to the loaded index prefix — the merges
compare it only on the covered prefix — and is skipped only when the loaded
index cannot feed the conversion's inputs.

Test coverage asked by the review: a truncated-index section asserting the
virtual row reaches the pipeline (EXPLAIN PIPELINE) in both modes, LIMIT BY
sections for both plan shapes (`optimizeLimitByInOrder` cannot cross a
`SortingStep`, see the comments), `read_in_order_use_virtual_row_per_block = 1`
cases for the widened and skipped-key paths, and `SYSTEM STOP MERGES` + four
parts in the skipped-key sections so the multi-source merge is deterministic.
@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress in #123354 (same red as on #122482). Query #1 is mortonEncode((1, 2), number, number * 2); the mortonDecode queries (#0, #5, #7) did not move. On ARM, #1 and #4 have a per-binary slow mode, and the ee5df18c build drew it: #1 0.823 s -> 0.959 s, #4 0.803 s -> 0.893 s, while the shard's own report says success and only the dashboard flagged it. #123354 takes the per-row width switch and mask dispatch out of the mortonEncode row loop; on its own ARM run #1 went 0.816 s -> 0.528 s and #4 0.797 s -> 0.720 s.

Conflict in `ReadFromMergeTree.h`: master added `canReadInReverseOrder` next to
the virtual row conversion setters; kept it together with this branch's
`setVirtualRowConversions` taking `key_prefix_size` and the reset of
`virtual_row_key_prefix_size`.

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

Copy link
Copy Markdown
Member

🕵 Merged current master (d741c986088). The only conflict was in ReadFromMergeTree.h: master added canReadInReverseOrder next to the virtual row conversion setters; I kept it together with this branch's setVirtualRowConversions(..., key_prefix_size) and resetVirtualRowConversions that also clears virtual_row_key_prefix_size. The merged branch builds, and all virtual row stateless tests (including 04549 and 05153) produce the reference output locally up to the parts that need system.query_log or test clusters. Thanks @groeneai for the pointer to #123354 about the unrelated space_filling_curve perf red.

Comment thread src/Core/SortCursor.h Resolved
alexey-milovidov and others added 4 commits October 17, 2026 19:57
Conflict in `MergingSortedAlgorithm::initialize`: master switched containers to
`VectorWithMemoryTracking`; kept the PR's `virtual_row_blocks` using the same container.

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

Mirror the truncated-cursor handling of `SortCursor::greaterAt` in
`SortCursorWithCollation::greaterAt`: compare a read-in-order virtual row only on
its covered sort-key prefix and sort the more truncated cursor first on a tie.
Add a test of per-block virtual rows with collated ORDER BY.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s a key

`buildInputOrderFromSortDescription` truncates `match_infos` when the
NULL/NaN placement check rejects the current key, but kept the
`num_virtual_row_columns` counter incremented for it. The virtual row
conversion then indexed `match_infos` past its end, which aborted the
server in the Fast test (`00940_order_by_read_in_order_query_plan`:
`select * from tab order by (a + b) * c, sin(a / b) desc`).

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111457&sha=213645f8dbdab541de581345a1020fb579e9473f&name_0=PR&name_1=Fast%20test
#111457

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

Copy link
Copy Markdown
Member

🕵 The red Fast test was caused by this PR: the server aborted on select * from tab order by (a + b) * c, sin(a / b) desc (00940_order_by_read_in_order_query_plan). The aborting check was a libc++ out-of-bounds assertion on match_infos[i] in buildInputOrderFromSortDescription. The NULL/NaN placement check that came from master rolls the rejected key back by truncating match_infos, but num_virtual_row_columns kept counting that key, so the virtual row conversion read past the end of the vector. Fixed in b0323e27187: the rollback now also restores num_virtual_row_columns and virtual_row_prefix_open. After that I merged current master (f8e2989e99d), which had no conflicts. 00940, 02911, 04549, 05153 and 05406 pass locally on the merged build.

alexey-milovidov and others added 2 commits October 22, 2026 00:31
Resolve conflicts in `ReadFromMergeTree` with the `FINAL` virtual row refactoring
from master (`getVirtualRowBound`, `makeVirtualRowHeader`, `everyPartHasVirtualRowBound`):
- `makeVirtualRowHeader` takes `include_used_key_prefix`: the non-`FINAL` in-order read widens
  the header to the whole used key prefix (as this PR did), the `FINAL` read keeps master's header.
- `getVirtualRowBound` takes the minimal number of key columns (those the conversion reads) and
  builds the bound over the loaded index prefix when `optimizeIndexColumns` dropped suffix columns.

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

Copy link
Copy Markdown
Member

🕵 Merged current master (de621bdbc21) as a76986e7a65. It conflicted in ReadFromMergeTree with the FINAL virtual row refactoring (#124468), which moved the bound into getVirtualRowBound / makeVirtualRowHeader. I kept this branch's behavior inside the new helpers:

  • makeVirtualRowHeader(include_used_key_prefix): the non-FINAL in-order read widens the header to the whole used key prefix. The FINAL read keeps master's header (only the conversion inputs).
  • getVirtualRowBound takes the minimum number of key columns (the conversion inputs). When optimizeIndexColumns dropped suffix index columns, it builds the bound over the loaded index prefix.

Also fixed the red arm_tidy build in da384de17d7: clang-analyzer-deadcode.DeadStores flagged virtual_row_prefix_open, which was restored right before break and never read afterwards.

Locally, all 29 virtual_row stateless tests pass, including 05325_read_in_order_final_virtual_row. In the broader read_in_order/in_order run (193 tests), 183 passed. The other 10 failed only because of my local setup: no test.hits dataset, no macros, the server listening on 127.0.0.1 only, and no pandas.

alexey-milovidov and others added 2 commits October 26, 2026 07:15
…distinct_in_order_boundary`

The `COLLATE` cases guard the covered-prefix comparison introduced by this PR,
so they pass on master and made the bugfix validation job red (each new test
that passes on the unfixed binary counts as a failure there). Keep them in the
regression test that does reproduce the bug on master. The file now needs
`no-fasttest` because collations require ICU.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111457&sha=latest&name_0=PR&name_1=Bugfix%20validation%20(functional%20tests%2C%20amd64)

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

Copy link
Copy Markdown
Member

🕵 Merged current master (clean, no conflicts) and folded 05406_virtual_row_per_block_collation into 04549_virtual_row_distinct_in_order_boundary. The COLLATE cases guard the covered-prefix comparison added by this PR, so they pass on master, and bugfix validation counts a new test that passes on master as a failure. That was the only red check. 04549 now carries no-fasttest because collations need ICU. Locally, 04549 and 05153 match their references.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (d131adb16be) as bee78516944; the merge was clean, with no conflicts. The PR's own translation units (ReadFromMergeTree, optimizeReadInOrder, MergingSortedAlgorithm, MergeTreeReadInfo, SortCursor, MergeTreeSelectProcessor) compile on the merged tree. CI on the previous head fd56486fff2 had no failed tests, and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red check is Upgrade check (amd_release): test_1.t_replace_cover_rep (the fixture of 05259_replace_partition_covers_outdated_parts_replicated) stays read-only after the upgrade with TOO_MANY_UNEXPECTED_DATA_PARTS. It is unrelated to this PR (read-in-order virtual rows), and the fix is in progress in #127843. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111457&sha=bee78516944f7da56d7bca33b98e19155617e1c6&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29. There are no unresolved review threads; the branch was merged with master on 2026-11-03, so no new commits are needed.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (10e0db2ad742) as d231c1c5181f to refresh CI. The merge was clean. master touched SortCursor.h, ReadFromMergeTree.cpp, and MergeTreeSelectProcessor.cpp, so I rebuilt all of the PR's translation units on the merged tree, and they compile. The previous red check, Upgrade check (amd_release) (test_1.t_replace_cover_rep read-only with TOO_MANY_UNEXPECTED_DATA_PARTS), is unrelated to this PR. It is tracked by the open #127843. There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (1ecf62bc828) as 7e4ff9299e9 to pick up the fix for the only red test, 05515_global_subquery_projection_where in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel). That test is not related to this PR; it was fixed on master by 1cfc5bb (Do not rewrite GLOBAL IN in projection queries with parallel replicas). The merge was clean. master touched ReadFromMergeTree.cpp/.h, so I rebuilt the PR translation units (ReadFromMergeTree, optimizeReadInOrder, MergingSortedAlgorithm, MergeTreeReadInfo, MergeTreeSelectProcessor, SortCursor), and they compile. There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (d6f1f495fe4b) as 5e248134af3b to refresh CI, since the branch was last updated on 2026-11-08. The merge was clean, and master did not touch any of the PR's files. All of the PR's translation units (SortCursor, MergeTreeReadInfo, MergingSortedAlgorithm, optimizeReadInOrder, ReadFromMergeTree, MergeTreeSelectProcessor) compile on the merged tree. CI on the previous head had no failures, and there are no unresolved review threads.

alexey-milovidov and others added 2 commits November 21, 2026 03:32
`master` now keeps the read-in-order virtual row for a sorting key column that is fixed by the filter and listed
in `ORDER BY` (f148849, `Keep the read-in-order virtual row for a fixed ORDER BY key column`): the virtual row
takes such a column from the index like any other key column. That branch of `buildInputOrderFromSortDescription`
pushes a `MatchInfo` but, after the merge, did not advance `num_virtual_row_columns`, so the virtual row
conversion was cut one column short. For `WHERE a = 1 ORDER BY a, b` over the key `(a, b)` the virtual row
covered only `a`, announced nothing about `b`, and the parts far from the result were read anyway, which failed
`05620_read_in_order_virtual_row_fixed_key` in the Fast test.

Extend the virtual row prefix in that branch under the same conditions as for an ordinary matched key column
(only while the key prefix is contiguous, i.e. no key column was skipped before it).

`04549_virtual_row_distinct_in_order_boundary` pinned the old behavior (no virtual row for
`WHERE b = 1 ORDER BY a, b, c` over the key `(a, b, c)`). The virtual row is now kept there, as `master` intends,
and the result still matches the unoptimized read, so the expectation is updated.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111457&sha=5e248134af3b6480389dba366cb879fc9e820da6&name_0=PR&name_1=Fast%20test
PR: #111457

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The Fast test was red on 05620_read_in_order_virtual_row_fixed_key, a test that came from master with f148849 (Keep the read-in-order virtual row for a fixed ORDER BY key column). This was a semantic conflict with this PR, not a flaky test.

  • Cause. master now takes a key column that is fixed by the filter and listed in ORDER BY from the index, like any other key column. That branch of buildInputOrderFromSortDescription pushed a MatchInfo but did not advance this PR's num_virtual_row_columns, so the conversion was cut one column short. For WHERE a = 1 ORDER BY a, b over the key (a, b) the virtual row covered only a, and the parts far from the result were read anyway.
  • Fix (a846579). That branch now extends the virtual row prefix under the same conditions as an ordinary matched key column, that is only while no key column was skipped before it.
  • Test expectation changed. 04549_virtual_row_distinct_in_order_boundary pinned "no virtual row" for WHERE b = 1 ORDER BY a, b, c over the key (a, b, c). The virtual row is now kept there, as master intends, and the result still matches the unoptimized read. I updated the reference and the comment.
  • Verification. I merged current master (clean) and rebuilt. 05620_read_in_order_virtual_row_fixed_key, 04549_virtual_row_distinct_in_order_boundary and 05153_virtual_row_widened_prefix_constant_order_by pass locally on a release build, so the debug-only boundary assertion was not exercised. Of the other virtual-row and read-in-order tests, 27 pass; nine could not run to completion on my minimal local server (missing test clusters, system.processors_profile_log, graphite_rollup, test.hits, row policy storage), so CI has to cover them.

Two things are left for the author:

  • The PR description still says a column fixed by the filter that stays in ORDER BY "keeps disabling the virtual row, as before this fix". That no longer holds after f148849 and should be reworded.
  • The remaining red Finish Workflow check only says that a draft PR runs the Fast test alone. The full CI needs the PR to be marked ready for review or the ci-force-all label.

alexey-milovidov and others added 2 commits November 24, 2026 04:18
# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.h
…rsion

The merge with `master` brought `copyVirtualRowConversions` (used by `optimizeLazyFinal`),
which now copies `virtual_row_key_prefix_size` along with `virtual_row_conversion`.
Do the same in `ReadFromMergeTree::clone` and in the rebuilt parallel replicas read, so that
`requestReadingInOrder` on the copy still recognizes a prefix narrower than the one the
conversion was built for.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (a1ba05231040) as 10b6ecedac41 to resolve the conflict in ReadFromMergeTree.h.

  • Conflict. master added copyVirtualRowConversions (used by optimizeLazyFinal) next to the setVirtualRowConversions / resetVirtualRowConversions declarations this PR changes. I kept this PR's signatures and made copyVirtualRowConversions copy virtual_row_key_prefix_size together with virtual_row_conversion.
  • Follow-up (7405685). ReadFromMergeTree::clone and the rebuilt parallel replicas read copied virtual_row_conversion without virtual_row_key_prefix_size, so requestReadingInOrder on the copy would not recognize a prefix narrower than the one the conversion was built for. They now carry both.
  • Verification. Rebuilt on the merged tree (release build, so the debug-only boundary assertion was not exercised) and ran the 155 stateless tests matching virtual row, read-in-order, lazy FINAL, read by layers, distinct-in-order and LIMIT BY in order against a server with the default config: 129 pass, including 04549_virtual_row_distinct_in_order_boundary, 05153_virtual_row_widened_prefix_constant_order_by, 05620_read_in_order_virtual_row_fixed_key and 05829_read_by_layers_reads_only_key_prefix. The other 26 could not run there: they need the test clusters, the test.hits dataset, graphite_rollup, or pandas.
  • CI. The only red check on the previous head was can_be_merged.py: the PR is a draft, so only the Fast test ran. The full CI needs the PR to be marked ready for review or the ci-force-all label. There are no unresolved review threads.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

4 participants