Skip to content

Support virtual rows in reading in order with FINAL - #124468

Merged
vdimir merged 16 commits into
masterfrom
vdimir/vrow-final
Oct 21, 2026
Merged

vdimir merged 16 commits into
masterfrom
vdimir/vrow-final

Conversation

@vdimir

@vdimir vdimir commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

  • Queries with FINAL now use the virtual row optimization of reading in order. Supported for ReplacingMergeTree, CollapsingMergeTree, VersionedCollapsingMergeTree, SummingMergeTree, AggregatingMergeTree and CoalescingMergeTree.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.396-master (included in 26.11 and later)
  • Backported to: 26.10.2.56

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2f136ca]

Summary: ✅


AI Review

Summary

The PR enables virtual-row bounds after FINAL merges for the supported MergeTree variants and adds the force value to query_plan_read_in_order_through_join, preserving boolean shorthand. Reviewed the current diff and code at 2f136ca6ced51116ac41c9487cda12992c4c9f54 against all prior discussion. The earlier findings are addressed, including primary-index type conversion; no new actionable findings remain.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Oct 7, 2026
@vdimir
vdimir force-pushed the vdimir/vrow-final branch from ca42053 to dfacb80 Compare October 8, 2026 15:58
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Oct 8, 2026
Reading in order through an `INNER JOIN` requires a virtual row, and a
`FINAL` read refused to build one, so such queries read and sorted the
whole left table. The FINAL merges still do not consume virtual rows: a
`VirtualRowTransform` after each of them announces the least primary key
its parts start from, taken from the primary index (the greatest for a
read in the reverse order), so the merge downstream defers the FINAL
merges the limit does not reach. The virtual row covers the primary key
prefix the sort reads, which is all the merge downstream compares, so the
other sorting key columns do not matter. Excluded: `GraphiteMergeTree`,
whose rollup lowers the time column, and parallel replicas.

The virtual rows are attached only when a step requested reading in
order, since a FINAL read is in order for its merges anyway, and the
optimizer drops the conversions when `requestReadingInOrder` refuses the
request.

The test 04489_virtual_row_disabled_with_final pinned the old refusal and
is removed; 03928 pins `read_in_order_use_virtual_row`, which its
reference now depends on.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vdimir
vdimir force-pushed the vdimir/vrow-final branch from 08d19c7 to 91e3e3e Compare October 9, 2026 15:42
vdimir and others added 2 commits October 12, 2026 15:17
A layer's virtual row was the least index value at its parts' range starts.
That bounds the layer loosely: the first granule of a sparse part may span
many keys, so the announced key sat far below the layer's start (205k keys
below for the second layer of the `final_read_in_order_limit` perf table,
whose update parts have gaps between their key blocks). The merge downstream
then left the front layer after a few hundred rows, armed its read-ahead
window and read every layer, so `WHERE v = 7 ORDER BY k LIMIT 100` read
8.1M rows with virtual rows against 9.3M without and got 25% slower.

`splitPartsWithRangesByPrimaryKey` now returns the layer borders, and
`spreadMarkRangesAmongStreamsFinal` takes the tighter of the parts' bound and
the border a layer starts from: `borders[i - 1]` for a forward read,
`borders[i]` for a reverse one. The same query now reads 426k rows from a
single layer and is 8% faster than without virtual rows.

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

clickhouse-gh Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

This PR lets virtual rows (the read-in-order optimization) work with SELECT ... FINAL on Replacing, Collapsing, Summing, Aggregating and Coalescing MergeTree tables. For non-FINAL reads in order, the only change is a refactor that moves the virtual-row key header out of the per-part loop. All four flagged improvements are downgraded to not sure. ClickBench Q33 (-11.9%) and Q34 (-12.5%) are full-scan aggregations, and TPC-H Q1 (-18.5%) and Q7 (-24.7%) run on plain MergeTree tables. None of these queries uses FINAL or reads in order, all four have noisy master history, and both ClickBench medians sit inside master's recent range. This run shows no measurable effect from the PR. Its intended speedup, FINAL ORDER BY ... LIMIT reads that skip layers the limit never reaches, is exercised only by the updated final_read_in_order_limit performance test, which is not part of these benchmarks.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1134 999 -11.9% <0.0001 aggregation: Q33 is a full-scan GROUP BY on a plain MergeTree table, with no FINAL and no read-in-order. The PR's changes to FINAL virtual rows are not on its path, and the -11.9% median sits inside master's recent range.
⚠️ 34 not_sure 1140 998 -12.5% <0.0001 aggregation: Q34 is a GROUP BY URL with ORDER BY count LIMIT 10. It neither reads in order nor uses FINAL, so the -12.5% shift is not explained by this diff, and the median sits inside master's recent range.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 53 -18.5% <0.0001 aggregation: TPC-H Q1 is a scan plus aggregation with no FINAL and no ORDER BY ... LIMIT on the primary key. The changed virtual-row code is not executed, and the -18.5% is a 12 ms move on a query whose history is noisy.
⚠️ 7 not_sure 81 61 -24.7% <0.0001 join_operator: Q7 joins plain MergeTree tables with no FINAL and no LIMIT, so read-in-order through the join and FINAL virtual rows do not apply. The -24.7% is a 20 ms move on a query whose history is noisy.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 4de0ab34-99ff-413e-a755-e11c2d5862b6
  • MIRAI run: 26ad1cbf-bab6-4302-b2e4-496790877b41
  • PR check IDs:
    • clickbench_1095055_1791826921
    • clickbench_1095061_1791826921
    • clickbench_1095067_1791826921
    • tpch_adapted_1_official_1095078_1791826921
    • tpch_adapted_1_official_1095090_1791826921
    • tpch_adapted_1_official_1095126_1791826921

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 2f136ca6ced51116ac41c9487cda12992c4c9f54 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@vdimir

vdimir commented Oct 13, 2026 •

Copy link
Copy Markdown
Member Author

Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
final_read_in_order_limit #2 FAIL dashboard

Change speedups one query and slows down another.

This is not FINAL specific, same happens on regular query with similar layout and there virtual row already enabled by default.
The property the repro needs is a heavy first lane in merge order, since that lane is read alone before the window opens.

CREATE TABLE t_vrow2 (k UInt64) ENGINE = MergeTree ORDER BY k;
SYSTEM STOP MERGES t_vrow2;
INSERT INTO t_vrow2 SELECT number FROM numbers(32000000)
    SETTINGS max_block_size = 4000000, max_insert_block_size = 4000000, min_insert_block_size_rows = 4000000, min_insert_block_size_bytes = 0;
SELECT k FROM t_vrow2 WHERE sipHash64(k) = 0 ORDER BY k LIMIT 10
    SETTINGS max_threads = 8, use_query_condition_cache = 0, read_in_order_use_virtual_row = {1|0};

I suppose we can admit it and align queries with FINAL with regular in terms of using virtual row without introducing specific setting for it.

<fill_query>INSERT INTO final_inorder_limit SELECT number, cityHash64(number, 2) % 1000, toString(cityHash64(number, 102)) FROM numbers_mt(4000000)</fill_query>
<fill_query>INSERT INTO final_inorder_limit SELECT number, cityHash64(number, 3) % 1000, toString(cityHash64(number, 103)) FROM numbers_mt(4000000)</fill_query>

<settings><read_in_order_use_virtual_row>0</read_in_order_use_virtual_row></settings>

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.

With virtual row, it now behaves the same as regular queries, with virtual row enabled by default. Some layouts may be slower because of lazy reading and some faster, so I disabled the setting to test the previous code branch.

#124468 (comment)

Merged via the queue into master with commit 3ac2c47 Oct 21, 2026
179 checks passed
@vdimir
vdimir deleted the vdimir/vrow-final branch October 21, 2026 08:33
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Oct 21, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 21, 2026
KochetovNicolai added a commit that referenced this pull request Oct 21, 2026
Backport #124468 to 26.10: Support virtual rows in reading in order with FINAL
@vdimir vdimir removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 2, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 2, 2026
robot-clickhouse added a commit that referenced this pull request Nov 2, 2026
Cherry pick #124468 to 26.8: Support virtual rows in reading in order with FINAL
robot-clickhouse added a commit that referenced this pull request Nov 2, 2026
Cherry pick #124468 to 26.9: Support virtual rows in reading in order with FINAL
@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 Nov 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #124468 to 26.9: Support virtual rows in reading in order with FINAL
vdimir added a commit that referenced this pull request Nov 2, 2026
- `Settings.cpp`: drop the old `Bool` declaration of `query_plan_read_in_order_through_join` left by the conflict resolution and terminate the new `BoolForce` one
- `optimizeTree.cpp`: convert `read_in_order_through_join` at the second-pass call site too
- `ReadFromMergeTree`: add `getPartsForPrewhere` and `MergeTreeDataSelectExecutor::filterParts`, which master has and 26.8 does not
- `SettingsChangesHistory.cpp`: record the new `force` value in the 26.8 section
- `ReadFromMergeTree.cpp`: remove a whitespace-only line in a lambda capture

Build failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=128683&sha=d096f2332cff46ae424b5df8a698eb42c356c437&name_0=BackportPR&name_1=Build%20%28amd_debug%29
PR: #128683

Co-Authored-By: Claude Fable 5.1 <[email protected]>
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #124468 to 26.8: Support virtual rows in reading in order with FINAL
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
- `Settings.cpp`: drop the old `Bool` declaration of `query_plan_read_in_order_through_join` left by the conflict resolution and terminate the new `BoolForce` one
- `optimizeTree.cpp`: convert `read_in_order_through_join` at the second-pass call site too
- `ReadFromMergeTree`: add `getPartsForPrewhere` and `MergeTreeDataSelectExecutor::filterParts`, which master has and 26.8 does not
- `SettingsChangesHistory.cpp`: record the new `force` value in the 26.8 section
- `ReadFromMergeTree.cpp`: remove a whitespace-only line in a lambda capture

Build failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=128683&sha=d096f2332cff46ae424b5df8a698eb42c356c437&name_0=BackportPR&name_1=Build%20%28amd_debug%29
PR: #128683

Co-Authored-By: Claude Fable 5.1 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
vdimir added a commit that referenced this pull request Nov 17, 2026
The test of #130893 does not run on 26.3 as it is:

- The settings `read_in_order_use_virtual_row_per_block`, `max_bytes_ratio_before_external_join`,
  `max_bytes_before_external_join`, `join_runtime_filter_min_probe_rows` and `query_plan_optimize_join_order_randomize`
  do not exist in 26.3. The two cases with a virtual row after each block are removed.
- `EXPLAIN` prints `ReadType:` instead of `Read type:`.
- The virtual row is disabled for `FINAL` in 26.3 (#124468 is not there),
  so `FINAL` is not read in order through `INNER JOIN`, and the case is removed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants