Skip to content

Keep the read-in-order virtual row when WHERE fixes any sorting key column - #132113

Open
vdimir wants to merge 8 commits into
masterfrom
vdimir/read-in-order-fixed-key-virtual-row-generic
Open

vdimir wants to merge 8 commits into
masterfrom
vdimir/read-in-order-fixed-key-virtual-row-generic

Conversation

@vdimir

@vdimir vdimir commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

The read-in-order virtual row was disabled when a filter fixed a sorting key column that ORDER BY omitted (WHERE a = 1 ORDER BY b over the key (a, b)) or listed in the opposite direction (ORDER BY a DESC, b). This prevented reading in order through an INNER JOIN. A virtual row is an index entry. An entry with a different value of a does not bound rows that pass the filter, because the merge compares only the ORDER BY columns. Now ReadFromMergeTree gets the fixed values (VirtualRowFixedKeys, from column = constant or a single-element IN) and builds a virtual row only from an index entry with those values. A part whose entry has a different value gets no virtual row and is read from the start.

Related: #130893
Related: #110725

Changelog category (leave one):

  • Performance Improvement

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

With optimize_read_in_order, a query keeps the virtual row (read_in_order_use_virtual_row) when WHERE fixes a sorting key column and ORDER BY omits it or lists it in the opposite direction (WHERE a = 1 ORDER BY b over the sorting key (a, b)). The query reads in order through an INNER JOIN and reads fewer rows with LIMIT.

🤖 Generated with Claude Code


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

vdimir and others added 5 commits November 13, 2026 15:51
…lter

A virtual row is an index entry: it bounds the rows of its part in the order of the sorting key. A key column fixed by
the filter (`WHERE a = 1`) may be absent from `ORDER BY` (`ORDER BY b`), or be there in the other direction
(`ORDER BY a DESC, b`), or through a non-strict function. Then the merge of the sorted streams did not compare the column
like the sorting key does, so an index entry of a filtered-out row did not bound the rows. The virtual row was disabled,
and such a query was not read in order through an `INNER JOIN`.

Now the merge in `SortingStep` compares such a column as a hidden column, which holds the fixed value in the rows and
the index value in a virtual row. The value is taken from the predicate (`column = constant` or a single-element `IN`).
If it is not known, the virtual row stays disabled. A fixed column which is not in the sorting key
(`WHERE x = 1 ORDER BY x, a, b`) gets its value in the virtual row as well.

Related: #130893
Related: #94103

Co-Authored-By: Claude Fable 5.2 <[email protected]>
For a sorting key column fixed by the filter which `ORDER BY` does not compare like the sorting key does
(`WHERE a = 1 ORDER BY b`, `WHERE a = 1 ORDER BY a DESC, b`), the previous commit made the merge in
`SortingStep` compare a hidden column `__fixed_key_<key>`. That turned a one-column merge into a
two-column one: a full merge of 12M rows for `WHERE a = 1 ORDER BY b` took 1.30 s instead of 0.75 s.

Now `ReadFromMergeTree` gets the values of such key columns (`VirtualRowFixedKeys`) and builds a virtual
row only from an index entry which has them (`virtualRowMatchesFixedKeys`): for the first virtual row of
a part, for the virtual row of a `FINAL` merge, and for the per-block ones. A part whose index entry has
another value gets no virtual row and is read from the start. Its raw index entry led to the same,
because it sorted before the other rows. The merge compares only the columns of `ORDER BY` again, and
`SortingStep` is back to what it was before the previous commit.

A fixed key column after the last compared one is not checked: it does not affect the bound. The check
of `INNER JOIN` for virtual rows (`everyPartHasVirtualRowBound`) is unchanged, so a part where the fixed
value starts in the middle of a granule still passes it.

`FixedColumns` is now a map from the fixed column to its value, instead of a set with a separate map of
predicates. `EXPLAIN` shows the checked columns as `Virtual row fixed key: a = 1`. A `UNION ALL` of such
reads keeps the virtual rows, every read with its own values.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The test sets `max_block_size = 8` and `max_threads = 1` for the session, and these also applied
to the check that reads `system.query_log`, which holds the queries of every other test.
`04652_query_condition_cache_no_skip_index_single_entry` resets the block size for the same reason.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…r-fixed-key-virtual-row-generic

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

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.h
The style check forbids `std::vector` in `src/Processors/Merges`.

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

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d62da51]

Summary: ✅


AI Review

Summary

The PR retains virtual rows when filters fix sorting-key columns that ORDER BY skips or compares in another direction. Index entries are checked against the fixed values before becoming bounds, including initial, per-block, and FINAL bounds. Reviewed head d62da51db58fa8166e3c9f8f5754cdd0683edc78. No new inline findings; one previously reported, deliberately deferred correctness issue remains reproducible in the shared fixedness inference.

Validation with the PR's Fast test binary passed the SQL regression's 13 ordering checks, plans, joins, and FINAL results, 408 comparisons against optimize_read_in_order = 0 across 17 key types and mixed directions, and focused DISTINCT, GROUP BY, and LIMIT BY probes. The server-only query-log read-count comparison was omitted locally; the Fast test report reports no failures.

Virtual-row consumers traced: ExpressionTransform preserves chunk metadata; FilterTransform preserves virtual rows through filtering; JoiningTransform forwards them without probing; BufferChunksTransform preserves initial bounds and defers reading; preliminary MergingSortedTransform consumes the raw key prefix without conversions; the final MergingSortedAlgorithm applies the conversions and skips synthetic rows; RemoveVirtualRowTransform removes them on the single-stream path.

Findings

❌ Blockers

  • src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:634 — Fixedness propagation still treats comparison-equivalent floating-point values as one exact input. [dismissed by author -- https://github.com/Keep the read-in-order virtual row when WHERE fixes any sorting key column #132113#discussion_r4597216457] The author correctly identifies this as pre-existing and prefers a separate fix. It remains real because f = 0 admits both signed zeros, while reinterpretAsUInt64 distinguishes them; propagating fixedness through that function lets the optimizer skip a varying sorting-key component.

    Reproduced on the current PR binary:

    SET max_threads = 1, max_block_size = 1,
        query_plan_optimize_lazy_materialization = 0;
    CREATE TABLE t (f Float64, b UInt64)
    ENGINE = MergeTree ORDER BY (reinterpretAsUInt64(f), b);
    INSERT INTO t VALUES (0, 1), (0, 2), (-0., 1), (-0., 2);
    SELECT b FROM t WHERE f = 0 ORDER BY b LIMIT 4
    SETTINGS optimize_read_in_order = 1;

    The result is 1,2,1,2; with optimize_read_in_order = 0, it is 1,1,2,2. The shared inference also serves aggregation and LIMIT BY. Preserve the distinction between an equality class and one exact value before propagating fixedness through arbitrary deterministic functions. Since this defect predates the PR, linking a dedicated tracking issue is an acceptable way to defer it. No duplicate comment or thread reopening was performed.

Final Verdict

Status: ⚠️ Request changes.

Minimum action: link a tracking issue for the confirmed pre-existing signed-zero defect, or fix the shared inference with focused regression coverage. No additional changes are requested for the new virtual-row implementation.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 16, 2026
The test relied on a fixed key prefix (`WHERE k = 1`) to get a read-in-order merge without virtual rows.
The virtual row is now kept for such a query, so the test counted 8 inputs with a virtual row instead of 0,
and `Fast test` failed. Set `read_in_order_use_virtual_row = 0`: the test still checks that a buffered input
without a virtual row stops reading ahead.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=132113&sha=854362d86090daa8626b9f8676cbcdcc7e9711a2&name_0=PR&name_1=Fast%20test
#132113
Related: #129198

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

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d62da51db with master f3e79c38e (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.

Object file sizes

52 object files changed (+75.65 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp.o 416.07 KiB 454.89 KiB +38.82 KiB (+9.33%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

vdimir and others added 2 commits November 17, 2026 09:57
…-generic

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

# Conflicts:
#	tests/queries/0_stateless/05620_read_in_order_virtual_row_fixed_key.sql
The flaky check of the sync pull request failed the test with
`Test runs too long (> 180s)`. Under the thread fuzzer of the flaky check
the time goes to the number of `INSERT` queries and of result comparisons.

Remove the table with the key `(a, b, c, d)`, the parts and the result
comparisons which repeat a case another query covers, and insert into
`t_fixed_key_right` in one block instead of blocks of 8 rows.
The test has 111 statements instead of 168 and 15 `INSERT` queries
instead of 26.

Run the comparisons of the fixed middle key with
`read_in_order_use_virtual_row_per_block` and the one with `FINAL` in
several threads: no query failed without the check of the fixed key
values in the virtual row after each block and in the one of `FINAL`.
The plan with `IN` now shows the value taken from the set.

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

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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant