Skip to content

Reset stale virtual row conversion when in-order read prefix is widened - #110725

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-virtual-row-default-boundary-106740
Jul 23, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-virtual-row-default-boundary-106740

Conversation

@groeneai

@groeneai groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #106740

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 where distinct-in-order or aggregation-in-order widens the read to a longer sort-key prefix than the one ORDER BY set up the read-in-order virtual row for. The extra sort columns of the virtual row were default-filled, which could mis-order the MergingSortedTransform (and abort with a LOGICAL_ERROR in debug/sanitizer builds).

Description

Root cause. optimizeReadInOrder builds a read-in-order virtual row conversion sized for the sort-key prefix ORDER BY needs (e.g. CounterID for ORDER BY CounterID DESC). A subsequent in-order request, e.g. optimizeDistinctInOrder for SELECT DISTINCT CounterID, EventDate, then calls requestReadingInOrder with a longer prefix (CounterID, EventDate) but leaves the 1-column virtual_row_conversion in place. At read time setVirtualRow default-fills the columns the conversion does not produce (EventDate -> 0). The per-part merge then compares each source against that virtual-row boundary; in reverse order the default 0 understates the real values, so a real row exceeds the announced boundary. In debug this trips the boundary assertion added in #106565 (Virtual row boundary violated ... announced UInt64_0 but the source then produced UInt64_16151); in release the assertion is compiled out and the merge is silently mis-ordered.

This is the single-table read-in-order path, which the union-side fix in #107053 does not cover.

Fix. In ReadFromMergeTree::requestReadingInOrder(prefix_size, ...), drop the virtual row conversion when it no longer covers the whole merge prefix (getSampleBlock().columns() < prefix_size). Placing the guard in the common requestReadingInOrder chokepoint covers every caller that widens the prefix (distinct-in-order, aggregation-in-order), not just the one reproduced here. Reading in order still works; only the (now-invalid) virtual row optimization is skipped for that read.

Reproduced deterministically on a debug build (assertion fires without the fix, passes with it, and the result matches the non-optimized read):

CREATE TABLE t (CounterID UInt32, EventDate UInt64, s String)
ENGINE = MergeTree ORDER BY (CounterID, EventDate) SETTINGS index_granularity = 8;
-- 6 unmerged parts
INSERT INTO t SELECT number % 5, 16000 + (number % 1000), toString(number) FROM numbers(20000);
-- ... (repeat for several parts)
SELECT DISTINCT CounterID, EventDate FROM t ORDER BY CounterID DESC
SETTINGS optimize_read_in_order=1, read_in_order_use_virtual_row=1, optimize_distinct_in_order=1,
         read_in_order_two_level_merge_threshold=3, max_threads=2;

Found via the stress test (Stress test (amd_debug), STID 2651-3359). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110638&sha=9331deb5&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Version info

  • Merged into: 26.8.1.40 (included in 26.8 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. Debug build, 6-part table (CounterID UInt32, EventDate UInt64) ORDER BY (CounterID, EventDate), SELECT DISTINCT CounterID, EventDate ... ORDER BY CounterID DESC with optimize_read_in_order=1, read_in_order_use_virtual_row=1, optimize_distinct_in_order=1, read_in_order_two_level_merge_threshold=3, max_threads=2 fires the exact assertion on demand.
b Root cause explained? Yes. ORDER BY builds a 1-column (CounterID) virtual row conversion; optimizeDistinctInOrder then calls requestReadingInOrder with a 2-column prefix without rebuilding it. setVirtualRow default-fills EventDate=0; in reverse order 0 < real max, so the merge boundary check fails.
c Fix matches root cause? Yes. requestReadingInOrder drops the conversion when getSampleBlock().columns() < prefix_size, i.e. exactly when it no longer covers the widened merge prefix.
d Test intent preserved / new test added? New test 04549_virtual_row_distinct_in_order_boundary. It asserts no error AND that the result equals the non-optimized read (so it catches both the abort and the silent release mis-order). No existing test weakened.
e Demonstrated both directions? Yes. Pristine binary: <Fatal> assertion reproduced. Fixed binary: 0 <Fatal> violations over 60 runs, result matches the optimize_read_in_order=0 baseline.
f Fix general, not a narrow patch? Yes. Guard sits in the common requestReadingInOrder chokepoint, so it covers every prefix-widening caller (distinct-in-order and aggregation-in-order), not only the reproduced query.
g Generalizes across inputs / directions? Verified for forward and reverse reads and both ORDER BY CounterID DESC and ORDER BY 1 ASC, CounterID DESC; EventDate is UInt64 as in CI. The fix is type-agnostic (column-count check).
h Backward compatible? Yes. Only skips an internal optimization when it would be unsafe; no setting default, on-disk/wire format, or user-visible behavior change beyond returning correct results.
i Invariants/contracts preserved? Yes. Upholds the MergingSortedAlgorithm invariant that a virtual row's announced boundary must bound the source's real rows across the full merge sort description. Reading-in-order still functions; only the virtual-row fast path is disabled for the widened prefix.

Session id: cron:clickhouse-worker-slot-2:20260716-154000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd for review: read-in-order virtual row fix in the single-table distinct-in-order path (the case #107053's union fix does not cover).

@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2d4b509]

Summary: ✅


AI Review

Summary

This PR fixes two real virtual-row correctness bugs in read-in-order planning and adds focused regressions, but the current head still leaves the widened-through-INNER JOIN path inconsistent: a later DISTINCT/aggregation/LIMIT BY re-request can drop the virtual row after the join eligibility check has already accepted the in-order join path. Because that path is explicitly guarded to avoid large extra reads when virtual rows are unavailable, I would not approve this as-is.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:3154-3156, src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:1212-1225, 1322-1331, 1444-1451, 1535-1540] requestReadingInOrder now resets virtual_row_conversion on a widened re-request, but the re-entry callers still keep INNER joins in order without rerunning the !uses_virtual_row guard. A plan that originally passed the guard because ORDER BY installed a virtual row can therefore lose that virtual row when DISTINCT, aggregation-in-order, or LIMIT BY widens the prefix, while keepLeftPipelineInOrder() remains latched. That re-enables exactly the high-read-amplification path the guard at optimizeReadInOrder.cpp:1212-1225 says must be rejected for non-LEFT ANY/ALL joins. Suggested fix: either make requestReadingInOrder report that it disabled virtual rows so the three widening callers can rerun the join-kind check before calling keepLeftPipelineInOrder(), or move the widening drop earlier so join eligibility is decided from the final uses_virtual_row state. Add one regression with read_in_order_through_join where ORDER BY installs the initial virtual row and a later DISTINCT/aggregation/LIMIT BY widens the prefix through an INNER JOIN.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
/// The virtual row then can't fill the extra sort columns, so it default-fills them; the merge
/// checks the boundary against those defaults and either aborts (debug) or mis-orders (release).
/// Drop the stale conversion when it no longer covers the whole merge prefix.
if (virtual_row_conversion && virtual_row_conversion->getSampleBlock().columns() < prefix_size)

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 clears virtual_row_conversion after buildInputOrderInfo has already decided that virtual rows are available (apply_virtual_row / uses_virtual_row are latched before the requestReadingInOrder call in optimizeReadInOrder.cpp).

That leaves read_in_order_through_join in an inconsistent state for plans where the conversion is dropped here. A concrete case is an INNER join on a table with sorting key (a, b, c) and a fixed skipped key, e.g. WHERE b = 1 ORDER BY a, c: buildInputOrderFromSortDescription still produces a 2-column virtual-row DAG and setVirtualRowConversions returns true, but this new check nulls it because prefix_size == 3. The caller then still runs keepLeftPipelineInOrder() on the join, even though the code above explicitly rejects inner-join read-in-order without virtual rows.

The result is that this fix can re-enable the high-read-amplification path that !uses_virtual_row currently blocks for joins. The stale-conversion check needs to happen before apply_virtual_row / join eligibility are decided, or requestReadingInOrder needs to report that it disabled virtual rows so the caller can re-run the !uses_virtual_row logic.

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.

The current HEAD still drops virtual_row_conversion only on the later widening re-entry (src/Processors/QueryPlan/ReadFromMergeTree.cpp:3122-3124), but the re-entry callers still never rerun the uses_virtual_row / join-kind check before keepLeftPipelineInOrder() (src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:1322-1331, :1444-1451, :1535-1540).

So an INNER-join plan that first got read-in-order for ORDER BY and is later widened by DISTINCT, aggregation-in-order, or LIMIT BY will still keep the join in-order after the conversion has been cleared.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed, and it is the same root problem as the fixed-middle boundary case above. All three widening re-entry sites (optimizeReadInOrder.cpp:1322, :1444, :1535) call requestReadingInOrder and then keepLeftPipelineInOrder() unconditionally, with no rerun of the uses_virtual_row / join-kind check, so clearing the conversion on the re-entry does leave an INNER join in-order without a valid virtual row.

I am not going to patch this at the caller independently. As shown above, dropping the conversion in the planner is itself wrong for the fixed-middle key (it returns mis-ordered results, not just an over-eager assertion), so the widening-drop is likely to be replaced entirely by a boundary-level fix in the conversion. This join re-eligibility gap will be handled as part of that rework: whichever mechanism ends up clearing/narrowing the virtual row must also re-run the !uses_virtual_row gate before keepLeftPipelineInOrder(), and the regression will cover the widened-INNER-join case (read-in-order for ORDER BY, then widened by DISTINCT/aggregation-in-order/LIMIT BY) asserting the high-read-amp join path is not re-enabled after the conversion is gone. Holding on @vdimir's direction on the boundary approach before pushing.

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.

We have method resetVirtualRowConversions to drop virtual row from reading step

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both make sense.

I will switch the reset to resetVirtualRowConversions().

For the widening re-entry, carrying the produced-prefix width with the conversion is better than dropping it: keep the conversion and bound only the columns it produces at the merge boundary, so the optimization still applies for that prefix. This also keeps uses_virtual_row consistent for the join path, since the conversion is no longer cleared from under the latched eligibility. The skipped-middle-key read stays disabled at build time, since its columns are not a contiguous key prefix and cannot be bounded this way.

Reworking along these lines and will push.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Pushed the rework (head 2d4b509).

Switched the drop to resetVirtualRowConversions(). I did not take the carry-prefix option: the virtual row is consumed by the read's preliminary MergingSortedTransform, which compares over the full used_prefix_of_sorting_key_size, not just the outer FinishSorting prefix. Making it "apply for the covered prefix" would need that merge to compare the virtual row on only its produced columns and treat a produced-prefix tie as a non-skip, which is an invasive change to the merge hot loop with real mis-ordering risk. Dropping the stale conversion on a widening re-request is the minimal safe fix; the covered-prefix optimization can be a follow-up if the perf in the narrow covered-widening case matters.

Also made the regression deterministic: the prior distinct queries passed even without the widening drop (only the skipped-middle-key build-time guard was exercised). Added SYSTEM STOP MERGES plus a fixed-key widening case on key (a, b) that trips the boundary violation without the drop and passes with it.

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.

The current head still clears the virtual row after the original uses_virtual_row gate has already admitted the join path.

ReadFromMergeTree::requestReadingInOrder now calls resetVirtualRowConversions() on widened re-requests at src/Processors/QueryPlan/ReadFromMergeTree.cpp:3154-3156, but the three widening re-entry sites still call keepLeftPipelineInOrder() unconditionally at src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:1322-1331, :1444-1451, and :1535-1540, without rerunning the inner-join check from :1212-1225.

So an INNER join that originally passed because ORDER BY installed a valid virtual row can still lose that virtual row when DISTINCT, aggregation-in-order, or LIMIT BY widens the prefix, while the join stays on the in-order path the guard is supposed to block.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed on head 2d4b509: the three widening re-entry sites (optimizeReadInOrder.cpp:1319, :1442, :1533) call keepLeftPipelineInOrder() with no !uses_virtual_row re-check, and resetVirtualRowConversions() can clear the conversion after them.

The gap cannot be closed at those re-entry sites. keepLeftPipelineInOrder() and read_in_order are already committed by the earlier ORDER BY pass (the !uses_virtual_row-gated block at :1211-1237). A widening pass returning early does not un-commit them, so re-running the join check there has no effect on the already-installed in-order join path.

The correct fix is to not lose the conversion on widening: carry the produced prefix width with virtual_row_conversion and bound only the produced columns at the merge boundary (the carry-prefix option under discussion above). Head 2d4b509 ships the minimal resetVirtualRowConversions() form; the carry-prefix follow-up closes this join case. Leaving that choice to the open design thread.

When ORDER BY builds a read-in-order virtual row for a sort-key prefix and a
later in-order request (distinct-in-order, aggregation-in-order) widens the
merge to a longer prefix, the virtual row conversion was left covering only the
original prefix. setVirtualRow then default-filled the extra sort columns, so
the merge compared the boundary against those defaults. In reverse order the
default (0) understated the real values and tripped the boundary check in
MergingSortedAlgorithm (LOGICAL_ERROR in debug, silent mis-ordered merge in
release).

Drop the conversion in requestReadingInOrder, but only when this request widens
a prefix an earlier request already established. The first, conversion-building
request may legitimately be narrower than the used prefix (a fixed middle sort
key, e.g. WHERE b = 1 ORDER BY a, c on key (a, b, c)); dropping it there would
defeat the virtual row optimization and, behind a join, re-enable the
high-read-amplification path that the !uses_virtual_row guard in
optimizeReadInOrder is meant to block.

Closes: ClickHouse#106740

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-virtual-row-default-boundary-106740 branch from e4eba90 to 79981c1 Compare July 16, 2026 18:56
@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed in 79981c1. The clear was unconditional, so it also dropped a legitimately-narrower conversion built on the FIRST request. Verified on a debug build with EXPLAIN actions=1: for a fixed middle key (key (a, b, c), WHERE b = 1 ORDER BY a, c) the conversion is now preserved (it was dropped before), so the inner-join in-order path keeps its virtual rows and the !uses_virtual_row guard is not bypassed.

The drop is now gated on the request widening a prefix an earlier request already set (query_info.input_order_info->used_prefix_of_sorting_key_size < prefix_size) rather than on columns() < prefix_size alone. That is exactly the distinct/aggregation-in-order re-entry after ORDER BY; the first conversion-building request is untouched, so no single-request (join or not) path changes. Added an EXPLAIN-based assertion for the fixed-middle-key case to the regression test.

The regression test needs several unmerged parts with many small granules to
reliably reproduce the boundary violation, so a single run can exceed the 180s
per-run flaky-check limit under sanitizer builds (5/50 asan runs hit TOO_LONG).
The long tag exempts the flaky-check time limit; the test body is unchanged and
still crashes on master and passes with the fix.

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

Copy link
Copy Markdown
Collaborator Author

Pushed ae050b9: tagged `04549_virtual_row_distinct_in_order_boundary` as `long`.

The 5 asan flaky-check FAILs were all `Test runs too long (> 180s)`, not functional failures (debug/msan/tsan flaky checks passed 50/50; the Bugfix-validation job succeeded overall, the 04549 row there is the expected master-HEAD reproduction). Reliably tripping the boundary needs several unmerged parts with many small granules, so a single sanitizer run can exceed the per-run 180s flaky-check limit. The `long` tag exempts that limit. Test body and .reference are unchanged; I re-verified locally on a debug build that it still crashes on master (SIGABRT, "\Virtual row boundary violated ... EventDate DESC: announced UInt64_0 but produced UInt64_16999'") and passes with the fix.

A key column fixed by WHERE (e.g. WHERE b = 1 ORDER BY a, c on key (a, b, c))
is skipped in buildInputOrderFromSortDescription without being added to the
virtual row, so the columns matched after it are no longer a contiguous key
prefix. The virtual row builder and pk_header index key columns densely, so the
skipped key shifts every later column onto the wrong key column. The wrong value
trips 'Virtual row boundary violated in MergingSortedAlgorithm' and, when the
shifted-to key column has a different type (e.g. Nullable), 'Virtual row has
different type'. Both abort in debug and mis-order the merge in release.

Disable the virtual row optimization whenever a key column is skipped, not only
when it is the first key.

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

Copy link
Copy Markdown
Collaborator Author

Pushed c87e2ed to fix the AST-fuzzer finding on this PR (STID 1637-309b, "Virtual row has different type").

It is a pre-existing master bug, not caused by this PR. Confirmed by reverting this PR's source change, rebuilding, and reproducing the identical abort:

CREATE TABLE t (a UInt32, b UInt32, c Nullable(UInt32))
ENGINE = MergeTree ORDER BY (a, b, c) SETTINGS index_granularity = 8, allow_nullable_key = 1;
INSERT INTO t SELECT number % 10, 1, number % 7 FROM numbers(2000);
INSERT INTO t SELECT number % 10, 1, number % 7 FROM numbers(2000, 2000);
SELECT a, c FROM t WHERE b = 1 ORDER BY a ASC NULLS FIRST, c ASC
SETTINGS read_in_order_use_virtual_row = 1, optimize_read_in_order = 1;

Root cause: in buildInputOrderFromSortDescription, a key column fixed by WHERE (here b) is skipped without being added to the virtual row, so the columns matched after it are no longer a contiguous key prefix. The virtual row builder and pk_header index key columns densely, so the skipped b shifts c onto key column b. Wrong value trips the boundary check (STID 2651-3359); when the shifted-to column has a different type (Nullable c), it trips the type check (STID 1637-309b). Both abort in debug and mis-order the merge in release.

Fix: disable the virtual row optimization whenever a key column is skipped, not only when it is the first key. The prior condition only guarded the first-key case.

Verified on a debug build (buildId a23386f5): both aborts gone, results match the non-optimized read, the distinct-in-order case this PR targets still works, and 02149_read_in_order_fixed_prefix / 02564_read_in_order_final_desc still pass. Extended 04549 to assert virtual rows are disabled for the skipped-middle-key read and to cover both the boundary and the Nullable type-mismatch manifestations.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (for commit c87e2ed, click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (a UInt32, b UInt32, c Nullable(UInt32)) ENGINE=MergeTree ORDER BY (a,b,c) SETTINGS index_granularity=8, allow_nullable_key=1; + 2 parts of 2000 rows (b always 1), then SELECT a, c FROM t WHERE b=1 ORDER BY a ASC NULLS FIRST, c ASC SETTINGS read_in_order_use_virtual_row=1, optimize_read_in_order=1 aborts every time. Non-nullable c instead aborts with the boundary check (STID 2651-3359).
b Root cause explained? In buildInputOrderFromSortDescription, a key column fixed by WHERE (b) is skipped without being added to the virtual row, so matched columns after it are no longer a contiguous key prefix. The virtual row builder and pk_header index key columns densely, so the skipped b shifts c onto key column b. Wrong value → boundary check (2651-3359); wrong type (Nullable c vs b's UInt32) → type check (1637-309b). Abort in debug, mis-order in release.
c Fix matches root cause? Yes. Disable the virtual row optimization whenever a key column is skipped (the fixed_key_columns branch), not only when it is the first key. This removes exactly the non-contiguous-prefix case the builder cannot represent.
d Test intent preserved / new tests added? 04549 extended: asserts virtual rows are disabled for the skipped-middle-key read, and asserts correctness (optimized == non-optimized) for both the boundary (non-nullable) and type-mismatch (Nullable) manifestations.
e Both directions demonstrated? Yes. Pristine (buildId e6c17a26, fix reverted): SIGABRT on both variants. Fixed (buildId a23386f5): both pass, results match non-optimized read.
f Fix is general across code paths? Yes. Both crash sites (setVirtualRow type check and MergingSortedAlgorithm boundary check) are downstream of the single mis-indexing in the DAG builder; disabling at the builder covers both. Root cause fixed at origin, not guarded at the crash site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The trigger is the skipped middle key, independent of c's type. Verified non-nullable UInt32 (boundary variant) and Nullable(UInt32) (type-mismatch variant); the disable is type-agnostic (no type-specific branch). Fixed-last-key and no-fixed-key cases still keep virtual rows (verified via EXPLAIN).
h Backward compatible? Yes. No setting/format/metadata change. Only removes an incorrect internal optimization for the skipped-key case; results are unchanged (they were already wrong/aborting). No SettingsChangesHistory impact.
i Invariants and contracts preserved? Yes. Restores the contiguous-key-prefix invariant the virtual row builder and pk_header builder assume. can_optimize_virtual_row=false makes the reader take the plain read-in-order path (no virtual row), which is the correct, already-supported fallback.

Session id: cron:clickhouse-worker-slot-0:20260717-091400

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c87e2ed

CI fully finished (Finish Workflow + Mergeable Check pass; 0 checks queued/in-progress). All functional, integration, stress, fuzzer, and sanitizer checks are green at this commit (278,430 test rows OK, 0 FAIL/ERROR in CIDB). No failure has an outstanding owner.

Check / test Reason Owner / fixing PR
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260717-170000

@vdimir vdimir 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.

Could we alternatively carry prefix size along with virtual_row_conversions? So optimization will be applied for prefix still

@vdimir vdimir self-assigned this Jul 20, 2026
groeneai and others added 2 commits July 20, 2026 22:02
The widening-drop in requestReadingInOrder cleared virtual_row_conversion
by raw assignment. Use the existing resetVirtualRowConversions() member
instead, per review on ClickHouse#110725. The trigger is unchanged: a later
distinct/aggregation-in-order re-request that widens the read prefix
beyond the columns the conversion produces cannot fill the extra merge
sort columns, so the virtual row would announce a wrong boundary; drop
it and let the merge fall back to normal cross-part comparison.

No behavior change from this refactor (the member sets the pointer to
nullptr, identical to the prior assignment).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The prior distinct-in-order queries passed even without the
requestReadingInOrder widening drop (only the fixed-middle-key build-time
guard was actually exercised), and the six parts could be merged away by a
background merge before the cross-part in-order merge ran.

Add SYSTEM STOP MERGES so the parts stay unmerged, and add a focused
fixed-key widening case on key (a, b): ORDER BY a builds a one-column
virtual row, distinct-in-order widens the read prefix to (a, b), and in
reverse order the default-filled b tripped the boundary check. This case
fails (boundary violation) without the widening drop and passes with it,
so it protects the requestReadingInOrder change directly.

Co-Authored-By: Claude Opus 4.8 <[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; 1 finding; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The distinct-in-order queries did not deterministically prove the requestReadingInOrder widening fix: they neither stop background merges nor assert the widened virtual-row path was exercised, and the deterministic base failure was the separate fixed-middle-key case. AGREE — fixed @ 2d4b509 Verified: on a build with the widening drop removed (hunk kept for the skipped-middle guard), the prior distinct queries still PASS, so they did not protect the widening fix. Added SYSTEM STOP MERGES to keep parts unmerged, plus a focused fixed-key widening case on key (a, b) (DISTINCT a, b WHERE b = 1 ORDER BY a DESC). That case aborts with the boundary violation without the widening drop and passes with it, so it protects the requestReadingInOrder change directly.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-1:20260720-201200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a pre-PR base build the committed test aborts (SIGABRT) with Virtual row boundary violated ... sort column 'c'/'b'. The new widening case (DISTINCT a,b WHERE b=1 ORDER BY a DESC on key (a,b), SYSTEM STOP MERGES, 4 parts, two_level_merge_threshold=3) aborts deterministically without the widening drop.
b Root cause explained? Yes. optimizeReadInOrder builds a virtual-row conversion for the sort-key prefix ORDER BY needs (W columns). A later distinct/aggregation-in-order re-request widens requestReadingInOrder's prefix to P>W, but the conversion still produces only W columns; setVirtualRow default-fills columns [W..P) with 0, so in reverse order the announced boundary (0) understates the real values and the per-part merge mis-orders (aborts in debug via the #106565 assertion).
c Fix matches root cause? Yes. The widened re-request drops the now-too-narrow conversion (resetVirtualRowConversions() when getSampleBlock().columns() < prefix_size) so the merge falls back to correct cross-part comparison. The separate build-time guard disables the virtual row when a key column is skipped (fixed-middle key). Both remove the wrong boundary at its source, not at the assertion.
d Test intent preserved / new tests added? Yes. 04549_virtual_row_distinct_in_order_boundary is a new regression test. This change adds SYSTEM STOP MERGES (so the cross-part merge is exercised) and a focused fixed-key widening block that fails without the widening drop; nothing weakened.
e Both directions demonstrated? Yes. Updated test crashes (boundary violation, client exit 32) on a build with the widening drop removed, and passes (matches reference 1000/1000/1/1/0/1/1, server alive) on the fix.
f Fix is general across code paths? Yes. The drop lives in the shared requestReadingInOrder chokepoint, so it covers every widening caller (distinct-in-order, aggregation-in-order, limit-by). The virtual row is consumed only by MergingSortedAlgorithm (one consumer, no sibling to patch). The !uses_virtual_row INNER-join guard stays consistent: the drop only fires on a widening re-request (after the ORDER BY request already committed with a valid virtual row).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified over UInt32/UInt64 keys, a Nullable key (existing NULLS FIRST case), ASC and DESC, and a 50-iteration randomized sweep over read_in_order_two_level_merge_threshold {0..3}, max_threads {1..3}, max_block_size {32..160}, read_in_order_use_virtual_row_per_block {0,1} — all result-equivalent to optimize_read_in_order=0, 0 failures. The drop is type-agnostic (clears a pointer).
h Backward compatible? Yes. No setting default, on-disk/wire/replication/metadata format, or new validation changed. Pure query-plan behavior fix; when the virtual row cannot be used, reading-in-order still works via the normal merge.
i Invariants and contracts preserved? Yes. The invariant the #106565 boundary assertion guards ("a virtual row announces a boundary the source will not cross") is upheld: the virtual row is used only when it can announce every merge sort column correctly, otherwise it is not built (skipped-key guard) or dropped (widening). resetVirtualRowConversions() sets the member to nullptr — identical semantics to the prior raw assignment, so no behavior change from this refactor. Block structure is unchanged (the virtual row is skip_last_row, removed before output).

Session id: cron:clickhouse-author-slot-1:20260720-201200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2d4b509

CI fully finished (Finish Workflow pass; 0 checks queued/in-progress; ingest buffer elapsed). No failure was caused by this PR's diff. Every failed check below has an owner: an existing fixing PR, 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
Stateless (amd_debug, parallel) + (amd_tsan, s3, 2/3) / 01730_distributed_group_by_no_merge_order_by_long flaky (MEMORY_LIMIT_EXCEEDED, 20 master + many unrelated PRs / 30d) #109847 (external, open)
Integration (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (107 master fails / 30d) #111029 (external, open)
Stateless (amd_llvm_coverage, ParallelReplicas, s3) / 04507_mvt_encode_state_serialize trunk bug (folded Variant constant loses member type under parallel replicas) #111136 (external, open)
Performance Comparison (arm_release, master_head, 6/6) shard job-level ERROR, no artifacts uploaded (perf-runner infra, chronic across master + unrelated PRs) a fix task is created (investigating at full effort; fixing-PR link to follow here)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260721-053000

/// e.g. WHERE b = 1 ORDER BY a, c on key (a, b, c)); dropping it there would defeat the
/// optimization and, behind a join, re-enable the path the !uses_virtual_row guard blocks.
const bool widened_over_previous_request
= query_info.input_order_info && query_info.input_order_info->used_prefix_of_sorting_key_size < prefix_size;

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.

It still not clear why widening should disable virtual row. If vrow is narrower then we still can decide which stream to read based on prefix

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The narrow virtual row is not safe to keep as-is here, because it is not only a stream-selection hint: it is injected into the read's own MergingSortedTransform, whose sort_description spans the full widened used_prefix_of_sorting_key_size (ReadFromMergeTree.cpp:1109-1116, and :1632-1651 for the preliminary merge), and the boundary check compares over all of those columns (checkVirtualRowBoundary, loop over description.size()).

setVirtualRow builds the announced row across the full merge header and default-fills any sort column the conversion does not produce (MergeTreeReadInfo.cpp:77, createColumnConstWithDefaultValue). So on a widened prefix the trailing/skipped columns are announced as 0. In reverse order 0 is the smallest key, so the announced boundary sits below the real values and the source then produces rows that sort ahead of its own announced boundary: the mis-order this PR's assertion catches (announced UInt64_0 but source produced UInt64_12).

To apply the optimization for the prefix still, the merge has to compare the vrow on only its produced columns and treat a produced-prefix tie as "do not defer this source": your carry-prefix option, i.e. store the produced width with virtual_row_conversion and bound both checkVirtualRowBoundary and the cursor compare to it. The current PR just drops the conversion as the minimal safe fix; I will switch it to the carry-prefix approach you propose so the narrow conversion is kept and applied for its covered prefix.

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.

Let's carry the virtual row prefix width through conversions so that optimization remains working. If we replace a fixed key with a constant in the middle of vrow, then update the conversion and replace it with that constant node.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I implemented the carry-prefix direction and tested it on a debug build. Two findings that change the plan:

  1. Re-enabling the fixed-middle-key virtual row (the WHERE b = 1 ORDER BY a, c on key (a, b, c) case that is currently disabled at build time) is not sound, even with the prefix width carried. I made the fixed key emit its real primary-key value into the conversion so the produced prefix stays contiguous (a, b, c), then ran:
CREATE TABLE t(a UInt64, b UInt64, c UInt64) ENGINE=MergeTree ORDER BY (a,b,c)
  SETTINGS index_granularity=8;
SYSTEM STOP MERGES t;
INSERT INTO t SELECT number%7, number%3, number%13 FROM numbers(0,8000);
INSERT INTO t SELECT number%7, number%3, number%13 FROM numbers(8000,8000);
SELECT a,c FROM t WHERE b=1 ORDER BY a, c
  SETTINGS optimize_read_in_order=1, read_in_order_use_virtual_row=1,
           read_in_order_two_level_merge_threshold=1, max_threads=3, max_block_size=64;

This aborts with Virtual row boundary violated ... on sort column 'c' ASC: announced UInt64_12 but source produced UInt64_0. On the current PR HEAD (fixed-middle vrow disabled) the same query is correct.

Root cause: b = 1 is a PREWHERE inside the source, so the source emits a compacted b = 1 stream, but the virtual row is the next physical granule's index mark over all b values. The mark's c no longer lines up with the compacted stream's next c, so on an (a, b) tie the announced c overstates. The width is not the problem here: c is a produced column of the conversion, so carrying/bounding the width still compares the bad c. This is why the middle-fixed-key case is disabled at build time, and it needs to stay disabled.

  1. The case where carry-prefix does help is the fixed-LAST-key widening you pointed at, e.g. SELECT DISTINCT a, b FROM t WHERE b = 1 ORDER BY a on key (a, b): the conversion covers a, DISTINCT widens the read prefix to (a, b), and the current code drops the still-valid a-only virtual row. Keeping it is correct there. But making the merge apply an a-only virtual row on an (a, b) merge is a variable-width SortCursor change in the merge queue: the virtual row is a real queue element compared over the full prefix (including the JIT-compiled comparator, which ignores sort_columns_size), and sort_columns_size is also read by MergeJoin. Bounding only the debug boundary check mis-orders in release (verified earlier). So this is a genuine comparator contract change in the merge hot loop, not a planner-only tweak.

Given that, I would keep the current minimal fix (disable the middle-fixed case, reset the conversion on genuine widening) and do the variable-width virtual-row comparator as a separate, focused change so it gets its own review. Does that split work for you, or do you want the comparator change in this PR?

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.

Given that, I would keep the current minimal fix (disable the middle-fixed case, reset the conversion on genuine widening) and do the variable-width virtual-row comparator as a separate, focused change so it gets its own review. Does that split work for you, or do you want the comparator change in this PR?

Good, I'm implementing variable-width virtual-row comparator in #111457

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Split works, thanks. This PR keeps the minimal fix (disable the middle-fixed case, reset the conversion on genuine widening); the variable-width comparator stays out of scope here. Noted #111457 for it.

@vdimir

vdimir commented Jul 23, 2026

Copy link
Copy Markdown
Member

@groeneai check out CI failures please

else if (fixed_key_columns.contains(sort_column_node))
{

if (next_sort_key == 0)

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.

Do you understand why it was if (next_sort_key == 0) before? Which cases it targeted to support and which we may loose after the change?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The old next_sort_key == 0 disabled virtual rows only when the FIRST sorting-key column was the WHERE-fixed one skipped in this branch, e.g. key (a, b), WHERE a = 1, ORDER BY b (the example kept in the comment).

It missed a fixed key skipped in the MIDDLE of the prefix, e.g. key (a, b, c), WHERE b = 1, ORDER BY a, c. There match_infos ends up [a, c] mapping to key slots [0, 2], i.e. non-contiguous. The virtual-row builder and pk_header index matched columns densely (0, 1, 2, ...), so the c match reads pk[1] = b: wrong value -> "Virtual row boundary violated", wrong type -> "Virtual row has different type". That is the #106740 abort.

After the change (disable whenever ANY key column is skipped) we lose nothing that was sound: the only reads newly excluded are the fixed-middle-key ones that were already building malformed virtual rows. That case cannot be made sound at this layer, because WHERE b = 1 is applied as a prewhere: the source emits a compacted b = 1 stream, but the virtual row is the next physical granule mark taken over all b, so its trailing columns no longer align with the post-filter stream and the announced boundary overstates the real one. Verified: emitting the fixed key as a normal pk source instead of disabling still aborts ("announced UInt64_12 but source produced UInt64_0").

Reads with no skipped key, or only an ORDER-BY-fixed column, keep the optimization exactly as before. The narrow-but-valid case #111457 recovers (fixed suffix, e.g. DISTINCT a, b WHERE b = 1 ORDER BY a) is a widening case, separate from this middle-skip branch, so this disable stays correct after #111457.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Checked head 2d4b509. All four red checks are pre-existing flakies, none caused by this PR (it only touches read-in-order virtual rows):

The first two now have merged fixes, so a rebase would clear those reds; the minimal fix here is otherwise ready. Full ledger: #110725 (comment)

@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.10% 92.00% -0.10%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 17/17 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 23, 2026
Merged via the queue into ClickHouse:master with commit d60e827 Jul 23, 2026
517 of 527 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 23, 2026
alexey-milovidov pushed a commit that referenced this pull request Aug 5, 2026
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]>
alexey-milovidov pushed a commit that referenced this pull request Aug 5, 2026
…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]>
alexey-milovidov pushed a commit that referenced this pull request Aug 5, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The widening-drop in requestReadingInOrder cleared virtual_row_conversion
by raw assignment. Use the existing resetVirtualRowConversions() member
instead, per review on ClickHouse#110725. The trigger is unchanged: a later
distinct/aggregation-in-order re-request that widens the read prefix
beyond the columns the conversion produces cannot fill the extra merge
sort columns, so the virtual row would announce a wrong boundary; drop
it and let the merge fall back to normal cross-part comparison.

No behavior change from this refactor (the member sets the pointer to
nullptr, identical to the prior assignment).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…al-row-default-boundary-106740

Reset stale virtual row conversion when in-order read prefix is widened
vdimir added a commit that referenced this pull request Nov 17, 2026
It is the change of `buildInputOrderFromSortDescription` from #110725,
which is not in 26.3. A key column fixed by `WHERE` and not listed in `ORDER BY` is skipped without a `MatchInfo`,
and the virtual row builder takes the following columns from wrong key columns. In 26.3 the virtual row was disabled
only if the skipped column was the first one, so `WHERE b = 1 ORDER BY a, c` over the key `(a, b, c)` returned rows
in a wrong order with `read_in_order_use_virtual_row`.

It is needed for #130893: with the virtual row kept for a fixed column
listed in `ORDER BY`, `WHERE a = 1 AND b = 2 ORDER BY a, c` would get into the same case.

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

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants