Skip to content

Fix for virtual row is not being applied in some cases - #113291

Merged
vdimir merged 10 commits into
masterfrom
vdimir/read_in_order_virtual_row_sort_prefix
Aug 10, 2026
Merged

vdimir merged 10 commits into
masterfrom
vdimir/read_in_order_virtual_row_sort_prefix

Conversation

@vdimir

@vdimir vdimir commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

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

  • Fixed wrong monotonicity metadata for toString and CAST(..., 'Nullable(String)') over a String column. As a result the read-in-order optimization was silently skipped and queries with ORDER BY <sorting key columns> LIMIT n sorted the whole table instead of stopping early.

  • Fixed the read-in-order with virtual row optimization being silently skipped for ORDER BY over a prefix of the table's sorting key

  • Fix incorrect results for queries with a filter or ORDER BY on toString of a Time, Time64, or DateTime column whose time zone has daylight saving time. Function toString was assumed to preserve the order of such columns, but it does not: Time is formatted with a sign and a variable number of digits for hours ('99:00:00' is greater than '100:00:00' as a string), and local time goes backwards when the clocks are turned back. As a result the primary key index could exclude parts holding matching rows, and optimize_read_in_order could return unsorted results.

Version info

  • Merged into: 26.8.1.1127 (included in 26.8 and later)
  • Backported to: 26.7.4.19, 26.6.3.37, 26.5.7.49

@vdimir vdimir changed the title Fix virtual row is not applied in some cases Fix for irtual row is not being applied in some cases Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c5410fd]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR does two related things: it allows read_in_order_use_virtual_row to work when the sortable prefix is shorter than the full ORDER BY, and it tightens toString monotonicity so MergeTree no longer treats Time / Time64 and DST-sensitive DateTime values as safely ordered when they are not. The toString(String) monotonicity issue from the earlier bot review is fixed in the current code, but the new regression coverage is still not strong enough to prove the riskier contracts this patch changes.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04672_read_in_order_virtual_row_sort_prefix.sql:70] The new "results stay correctly ordered" check still does not exercise the failure mode this PR is taking on. Both correctness queries run with LIMIT 10 against a six-row dataset, so they only prove the final output is sorted, not that prefix-only virtual rows return the same top-N row set as the unoptimized path when different parts share the same (name, code) prefix and a later column (for example dict.label) breaks the tie.
  • [tests/queries/0_stateless/04695_to_string_monotonicity.sql:7] The changelog and the code both say this fixes Time64, but the regression test only covers Time. Because DataTypeTime64 goes through a separate type branch and formatting path, a Time64-only monotonicity regression would still merge cleanly here.
Final Verdict

⚠️ Not ready to merge yet. The implementation looks directionally correct, but I would close the two coverage gaps above before trusting the new optimizer behavior and the Time64 monotonicity fix.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 66/74 (89.19%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@vdimir vdimir changed the title Fix for irtual row is not being applied in some cases Fix for virtual row is not being applied in some cases Aug 4, 2026
@vdimir vdimir added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 5, 2026
@vdimir

vdimir commented Aug 5, 2026

Copy link
Copy Markdown
Member Author

@groeneai, please suggest someone suitable to review this PR and tag them with a review request.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

cc @KochetovNicolai @nihalzp, could you review this?

@KochetovNicolai wrote the can_optimize_virtual_row guard that this PR relaxes, in bf591fa12b27f16 ("Introduce virtual row conversions"), including the TODO: partial sort description can be used as well comment that the optimizeReadInOrder.cpp hunk now implements. That one commit touched three of the five source files changed here (optimizeReadInOrder.cpp, MergingSortedAlgorithm.cpp, MergeTreeReadInfo.h), and he is the top all-time author of optimizeReadInOrder.cpp with 55 commits.

@nihalzp wrote the adjacent toString(FixedString(N)) monotonicity branch in 76d52a4b47ea688, so he has the most recent context on which types ToStringMonotonicity claims, and on the is_strict and is_always_monotonic flags, which is what the FunctionsConversion.h hunk changes. He is also the most frequent author of optimizeReadInOrder.cpp since February with 14 commits, so he covers both halves of the change.

One thing worth a look during review: FunctionsConversion.h keeps the superseded predicate as a commented-out line next to the new one.

@vdimir
vdimir requested a review from nihalzp August 5, 2026 11:57
Comment thread src/Functions/FunctionsConversion.h Resolved

SELECT '--- results stay correctly ordered';

SELECT groupArray(t) = arraySort(x -> x, groupArray(t)) FROM (

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.

This only proves that the returned tuples are internally sorted. Because the two INSERTs never put the same (name, code) into different parts, it would still pass if the relaxed prefix-only virtual row returned a sorted but wrong top-N set when ref / dict.label breaks ties across parts.

Could we duplicate a prefix across the two parts and compare the optimized result against SETTINGS optimize_read_in_order = 0, read_in_order_use_virtual_row = 0, like the existing 04549_* regressions do?

@Avogar Avogar self-assigned this Aug 6, 2026

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good. The comment from the bot about toString(String) worth fixing I think.

-- Monotonicity of `toString` for date and time types, see `ToStringMonotonicity`.

DROP TABLE IF EXISTS t_time;
CREATE TABLE t_time (x Time) ENGINE = MergeTree ORDER BY x;

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.

This regression is supposed to cover Time64 too, but it only exercises Time. The new ToStringMonotonicity branch explicitly changes DataTypeTime64, and the changelog entry calls out Time64 incorrect results, so we need the same filter / ORDER BY toString(x) checks for a Time64 table here as well. Otherwise a Time64-only regression can slip through while this test still passes.

@vdimir
vdimir added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit 75b17ad Aug 10, 2026
527 of 531 checks passed
@vdimir
vdimir deleted the vdimir/read_in_order_virtual_row_sort_prefix branch August 10, 2026 19:43
@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 Aug 10, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 11, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 11, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 11, 2026
Backport #113291 to 26.7: Fix for virtual row is not being applied in some cases
vdimir pushed a commit that referenced this pull request Aug 13, 2026
Three things the automated cherry-pick left in a state that does not build or
pass on 26.5.

FunctionsConversion.h: the DateTime branch of ToStringMonotonicity binds a
variable it never reads, which is -Wunused-but-set-variable and therefore an
error under -Weverything -Werror. All 7 Build (*) jobs fail with this one
signature, 18 times. Dropping the binding makes the block byte-identical to
the same block on 26.6.

04695_to_string_monotonicity: the t_utc table was removed from the setup but
two queries against it and its DROP were left behind, so the test aborts with
UNKNOWN_TABLE. Its .reference still carried the three corresponding lines.

04672 and 04695: join_runtime_filter_min_probe_rows does not exist on 26.5, so
the SET raises UNKNOWN_SETTING before any assertion runs. Only that one clause
is removed; max_bytes_ratio_before_external_join does exist here, so the
resulting SET line is byte-identical to the merged 26.7 backport, and
04029_join_convert_to_fixed_hash_table needs no change at all.
explain_query_plan_default is also absent on 26.5, so instead of pinning it the
EXPLAIN PLAN calls pass compact = 1, pretty = 1 explicitly, which keeps the
expected output byte-identical to master.
vdimir pushed a commit that referenced this pull request Aug 13, 2026
The case asserts hasInformationAboutMonotonicity() on toNullable, but that
monotonicity was not added by #113291. It came from #110121, which is labelled
pr-performance and carries no backport label, so 26.5 does not have it and the
assertion fails under asan_ubsan and tsan.

Deleting the one case is the smaller change. Forward-porting the toNullable
monotonicity to 26.5 instead is the alternative; that is a call for the release
owner, so this is a separate commit and can be dropped on its own.
alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
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.
vdimir added a commit that referenced this pull request Aug 14, 2026
Backport #113291 to 26.5: Fix for virtual row is not being applied in some cases
vdimir added a commit that referenced this pull request Aug 14, 2026
Backport #113291 to 26.6: Fix for virtual row is not being applied in some cases
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
Two stateless tests from ClickHouse#113291 cannot run on 26.6 as cherry-picked, so
they fail before any assertion executes.

04672: join_runtime_filter_min_probe_rows does not exist on 26.6 (added by
ClickHouse#104860, settings history 26.8), so the SET at line 21 aborts the test with
UNKNOWN_SETTING. Dropping that one clause makes the line identical to the
merged 26.7 backport. max_bytes_ratio_before_external_join does exist here,
so it stays and 04029 needs no change.

04695: the t_utc block was removed from this branch but the trailing
DROP TABLE t_utc and the three matching reference lines were left behind,
so the test dies with UNKNOWN_TABLE.

Both files: EXPLAIN PLAN defaults to actions=1, compact=1, pretty=1 only
from 26.7 via explain_query_plan_default, which does not exist on 26.6, so
the references written for master do not match. Pinning the three options
explicitly restores the byte-exact output. All three are needed: compact
and pretty without actions collapse the plan and hide the sort description
rows.

Verified with clickhouse local on stock 26.6.3.30 and on a master build.
On 26.6 both tests now run to completion and every remaining difference is
the defect ClickHouse#113291 fixes. On master the same files match the references
byte for byte, so the pinning loses no coverage.
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
This is the only failing gtest on asan_ubsan and tsan. ClickHouse#113291 added the
TEST, but the monotonicity it asserts lives in src/Functions/toNullable.cpp
and came from ClickHouse#110121, which is labelled pr-performance and was not
backported: hasInformationAboutMonotonicity is absent from toNullable.cpp
on 26.6 and present on 26.7, which is why 26.7 went green.

Separate commit so it can be dropped if ClickHouse#110121 is backported instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

6 participants