Skip to content

Stop SELECT ... FINAL WHERE ... LIMIT early with vertical FINAL when the matching rows are in a small part - #131560

Merged
fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:vertical-final-limit-early-stop
Nov 17, 2026
Merged

fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:vertical-final-limit-early-stop

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131381
Related: #131552

Changelog category (leave one):

  • Performance Improvement

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

SELECT ... FINAL WHERE <filter> LIMIT n on a ReplacingMergeTree table with enable_vertical_final (the default) now stops reading early when the rows that pass the filter come from a small part, instead of reading the whole table. Closes #131381.

Description

With enable_vertical_final, ReplacingSortedAlgorithm does not copy the winning rows: it records their row numbers in the source chunk and emits the chunk only when the merge passes the chunk's last row. A chunk of a small part spans the whole key range (a 3,000-row part is one granule), so its winning rows, here the only rows that pass the filter, reach Filter and Limit only after the whole layer is merged. Without vertical FINAL the merge emits every max_block_size rows.

Now, every max_block_size selected rows, the merge emits the rows selected so far of each chunk that has waited longer than max(max_block_size, 2 * num_inputs * chunk_rows) selected rows, as a chunk that shares the source columns and carries the partial selection. Chunks of inputs that hold at least 1 / (2 * num_inputs) of the keys still leave the merge in one piece, so dense merges keep emitting chunks without a copy.

The issue's fixture (13M rows, 4 overlapping parts), local release build, master -> this PR:

  • max_threads = 8: 13.04M rows / 0.161 s -> 1.11M rows / 0.016 s (enable_vertical_final = 0: 1.56M rows / 0.024 s)
  • max_threads = 1: 13.0M rows / 1.23 s -> 0.18M rows / 0.022 s
  • the issue's second shape (LIMIT 6, matches in a 3,000-row update part): 6.98M -> 1.20M rows

Full FINAL scans (dense, imbalanced and update-part fixtures, and the queries of final_big_column, parallel_final, optimized_select_final, replacing_final_non_intersecting) show no difference beyond noise; a dense merge emits the same blocks as before. Adds a performance test and a stateless test.

My open #131552 appends row numbers to the same selection in batches; whichever of the two lands second has to count those rows in num_selected_rows.


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

Version info

  • Merged into: 26.11.1.2646-master (included in 26.11 and later)
  • Backported to: 26.10.6.16

groeneai and others added 2 commits November 14, 2026 07:01
…IT stops early

With `enable_vertical_final`, `ReplacingSortedAlgorithm` records the row
numbers of the winning rows in the source chunk and emits the chunk only
when the merge has passed the chunk's last row. A chunk of a small part
spans the whole key range of a layer (a 3,000-row part is a single
granule), so its winning rows, which in ClickHouse#131381 are the only rows that
pass the filter, reach `Filter` and `Limit` only after the whole layer is
merged: `SELECT ... FINAL WHERE <filter> LIMIT 1` reads the whole table
(13,003,000 rows at max_threads = 1, against 199,608 without vertical
FINAL). The non-vertical path emits every `max_block_size` merged rows.

Every `max_block_size` selected rows, the merge now emits the rows
selected so far of each source chunk that has waited longer than
`max(max_block_size, 2 * num_inputs * chunk_rows)` selected rows, as a
chunk that shares the source columns and carries the partial selection;
the source chunk stays in the merge and starts a new selection. A chunk
of an input holding 1/num_inputs of the keys is merged within about
`num_inputs * chunk_rows` selected rows, so chunks of inputs holding at
least 1/(2 * num_inputs) of the keys still leave the merge in one piece
and dense merges keep emitting whole chunks without a copy (measured: the
same output blocks on 4 balanced parts). The `max_block_size` term gives
small chunks the same latency bound as the non-vertical path.

`saveChunkForSkippingFinalFromSource` now also drops the source's
reference when `selected_row` is the last holder of the chunk: a finished
source is not consumed again, so its last chunk could otherwise be both
queued in `to_be_emitted` and visible in `sources`, and an early emission
of its selection would leave `emitChunk` a null selection.

Closes ClickHouse#131381

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the waiting-selection member comment and the threshold comment to one line each.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 The first waiting-selection check is seeded from the constructor's max_block_size_rows, later ones from merged_data->maxBlockSize() AGREE, not blocking same value (MergedData is built from that argument)
2 💡 #131552 (mine, open) appends row numbers to the same selection in batches without counting them in num_selected_rows AGREE, not blocking correct on master; whichever of the two lands second counts the batched rows (noted in the description)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261114-070400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's fixture (4 overlapping parts, 13M rows) with enable_vertical_final = 1, max_threads = 1 reads all 13,003,000 rows on master every run (199,608 with = 0). The new stateless test's read_rows line fails on master every run.
b Root cause explained? Vertical FINAL records the winning row numbers in the source chunk and emits the chunk only when the merge passes its last row. A small part's chunk spans the whole key range, so its winning rows (the only filter matches) reach Limit only after the whole layer is merged. The non-vertical path is bounded by max_block_size merged rows.
c Fix matches root cause? Yes. The merge now bounds how long a recorded selection waits, with the same max_block_size budget as the non-vertical path, by emitting the partial selection of a long-waiting chunk with shared columns. No planner switch, no setting.
d Test intent preserved / new tests added? New stateless test (early stop, exactly-once emission of split selections, a one-row part that ends while selected) and a new performance test. Three mutations of the new code (copy instead of move, no check, no reference drop) each fail the test.
e Both directions demonstrated? Yes. Master: read_rows < 50000 gives 0 (220,100 rows read); this PR: 1 (at most 6,244 rows over 50 randomized runs). Issue fixture: 13.0M -> 0.18M rows at 1 thread, 13.04M -> 1.11M at 8 threads.
f Fix is general across code paths? Only ReplacingSortedAlgorithm has vertical FINAL; distributed, full and per-partition FINAL all build the same algorithm. Merges pass enable_vertical_final = false, and in-order reads disable vertical FINAL. The other merging algorithms emit through MergedData and are already bounded.
g Fix generalizes across inputs (params/datatypes/wrappers)? The new code is type-agnostic: it copies column pointers and passes row numbers to IColumn::index. Checked with String and integer keys, a version column, a LowCardinality column, 1/4/8/192 threads, max_block_size 64/1024/default, a one-row part, sparse update parts, and 50 randomized runs.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change. Only the number and size of output chunks changes, for sparse inputs; the output order of vertical FINAL was already unspecified.
i Invariants and contracts preserved? Every selected row is emitted exactly once (a flushed selection is moved out and a new one starts). A chunk queued for emission is no longer also referenced by its finished source. Pending selections are drained before the merge ends, and they hold plain chunks, so the shared-chunk allocator capacity is unchanged.

Session id: cron:clickhouse-impl-slot-7:20261114-055100

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [06c6e87]

Summary: ✅


AI Review

Summary

Reviewed head 06c6e87b80cd09fd98b8389ed0d3af918db1d23e, the full diff, prior discussion, and linked issue. The change lets vertical FINAL emit completed selections from long-waiting chunks so selective LIMIT queries can stop reading early. No actionable findings. The stateless test covers early termination, exactly-once emission, parallel execution, and a finished source retaining a selected row. The PR supplies before/after measurements and a focused performance test; the latest revision removes a timing-dependent benchmark query and correctly opts out of Iceberg.

Consumer coverage: IMergingTransform forwards partial chunks without interpreting their indices; SelectByIndicesTransform, installed by addMergingFinal for local, full, and distributed vertical FINAL, materializes each selection before downstream filtering and limits. Background merges and insert-time deduplication leave vertical FINAL disabled; ordered reads disable it as well. The source and consumer files inspected match the PR head. Validation used source inspection and existing reported results; no local build or tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 06c6e87b8 with master d011c6b84 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

The test ran over the 180 s limit in `Stateless tests (amd_asan_ubsan, flaky check)`.
The 15 of 50 runs that drew Wide parts took 92-188 s, against 27-37 s with Compact
parts: the `max_block_size = 64` vertical FINAL scans of the 220,100-row table cost
about 10x more CPU on Wide parts. That is the same on master and on this PR.

Shrink the fixtures 8x (t_vf_limit) and 4x (t_vf_last), keeping their shape: the z
keys still overwrite x and y rows, and the LIMIT query reads 6,244-6,696 rows with
the fix against all 27,600 without it, hence the 15,000 threshold. Locally the file
costs 0.18x the CPU on Wide parts and 0.16x on Compact parts. Every check still
fails on the binary it failed on before: the master base on the read_rows line,
the double-emission mutant on the counts, the mutant that keeps a finished chunk in
its source with a LOGICAL_ERROR, also in the t_vf_last block alone.

Also check that the LIMIT query runs vertical FINAL (`SelectByIndicesTransform` in its
pipeline): the plain FINAL merge reads the same 6,244-6,696 rows, so the read_rows line
alone cannot tell the two apart.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 93b4110

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) perf harness, not this PR's code: this PR adds a performance test, so the Iceberg jobs run only that test, none of its queries ran on both servers there, and compare.sh stops with INCORRECT_RESULT_OF_SCALAR_SUBQUERY before writing report/all-query-metrics.tsv (Errors while building the report.) #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 2/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 3/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 2/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 3/3) same harness failure as the row above #129874 (mine, open)
PR praktika rollup of the rows above #129874 (the owner above)

Session id: cron:our-pr-ci-monitor:20261114-150101

@fm4v

fm4v commented Nov 16, 2026

Copy link
Copy Markdown
Member

@groeneai merge master

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (82a889b) in 247fe90, no conflicts. 05632_vertical_final_limit_small_part passes 30/30 randomized runs on the merged debug build.

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review approves this commit, see the AI Review comment.

…very run

Drop the query that runs with the default `max_threads`. Its FINAL layers
are merged in parallel, and the number of rows the other threads read
before `LIMIT 1` cancels them depends on thread timing: on the tested
server of `Performance Comparison (amd_release, master_head, 5/6)` the
measured runs read 1.06M to 1.99M rows (19 to 30 ms, time proportional to
rows), and the profile runs 0.84M to 2.92M. Runs 0-3 landed low and runs
4-6 high, so the run-trend check reported "time keeps growing with each
run" (correlation 0.86, last/first 1.50) on a read-only query with no
state change between runs (marks and mark-cache hits are the same every
run). The `max_threads = 1` query reads 183,224 rows on every run and
keeps measuring the fix (0.925 s -> 0.019 s on that shard).

Also opt the test out of the Iceberg configuration with
`<test iceberg="0">`: Iceberg tables do not support FINAL, and the fill
asserts the number of active parts, so the six iceberg_* jobs that a PR
adding this test schedules cannot run it. The skip list is not edited
because it is in ICEBERG_PERFORMANCE_PATHS, and changing it runs the
whole Iceberg suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
auto-merge was automatically disabled November 16, 2026 16:28

Head branch was pushed to by a user without write access

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review approves this commit, see the AI Review comment.

@fm4v
fm4v added this pull request to the merge queue Nov 17, 2026
Merged via the queue into ClickHouse:master with commit 317c590 Nov 17, 2026
192 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 17, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 17, 2026
Backport #131560 to 26.10: Stop `SELECT ... FINAL WHERE ... LIMIT` early with vertical `FINAL` when the matching rows are in a small part
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
…g-merge-no-per-row-rowref

Conflicts resolved against master:
- ClickHouse#126158 added [[nodiscard]] to lines this PR edits: kept, except on
  RowRefWithOwnedChunk::firstNonEqualSortColumnsWith, which this PR removes.
- ClickHouse#131513 gated the part-level shortcut of rowsHaveDifferentSortColumns with
  nonzero_level_parts_have_unique_keys: the cursor overload keeps that gate,
  so CollapsingMergeTree still compares rows of merged parts.
- ClickHouse#131560 counts selected rows in vertical FINAL: kept, the selection is
  appended with push_back instead of insert(Field).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
Since ClickHouse#131560, vertical FINAL emits the rows selected so far from a chunk whose
selection waited longer than a merge of its input should take, measured in
selected rows (`num_selected_rows`). `insertUniqueRows` appended whole batches to
`replace_final_selection` without counting them and without stamping
`replace_final_selection_start` on a new selection, so on a merged part the clock
advanced by about three rows per batch and the small part's selection waited to
the end of the merge.

Measured on a debug build: a merged 200000-row part plus a 400-row part holding
the newest version of every 500th key, `SELECT k FROM t FINAL WHERE v = 'target'
LIMIT 1` with `enable_vertical_final = 1, max_threads = 1` read 200400 rows
without this change and reads 4496 with it, the same as master. Results of
FINAL with and without vertical FINAL are unchanged.

The new case in 05632 fails without this change (5 of 5 randomized runs) and
passes with it (30 of 30) and on master.
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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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 pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

enable_vertical_final=1: SELECT ... FINAL WHERE <filter> LIMIT n no longer stops early on a ReplacingMergeTree with overlapping parts (up to 4x slower)

4 participants