Repository navigation
Conversation
… partial reads
`MergeTreeSelectProcessor::buildVirtualRowFromIndex` derived the
per-block boundary key from `index[next_mark]`, which is the start of a
granule. For wide parts (where `MergeTreeReaderWide::canReadIncompleteGranules`
returns true), one block can read only part of a granule, so a chunk
whose `read_mark_ranges` reports `[N, N+1)` may carry just a few rows of
granule N while the rest live in the adjacent forward chunk. The
index-derived key was then far below the actual values still pending
from this source, and `MergingSortedTransform` deprioritized the source
incorrectly, producing out-of-order output once it reached the next
chunk.
The fix prefers extracting the boundary PK from the chunk's actual data
(`buildVirtualRowFromChunk`): for forward reads the last row's PK is a
tight lower bound for the next data; for reverse reads (where
`MergeTreeInReverseOrderSelectAlgorithm` buffers all chunks and pops them
LIFO, then `ReverseTransform` flips each chunk's rows) the first
forward-row's PK is the tight upper bound on what the next emit can be.
When the chunk has no surviving rows (PREWHERE filtered everything) or
the PK columns are not part of the result, we fall back to the original
index-based path, but only if the chunk's `num_read_rows` exactly equals
the granule sizes covered by `read_mark_ranges` -- so partial-granule
reads no longer emit a misleading boundary.
Reproducer (failed before the fix, passes after):
CREATE TABLE t (CounterID UInt32, CounterID2 UInt32)
ENGINE = MergeTree ORDER BY CounterID
SETTINGS index_granularity = 28454, min_bytes_for_wide_part = 0;
-- 10 INSERTs of 100k rows each, with max_block_size = 14633
SET optimize_read_in_order = 1,
read_in_order_use_virtual_row = 1,
read_in_order_use_virtual_row_per_block = 1,
max_block_size = 14633;
SELECT CounterID FROM t ORDER BY CounterID DESC LIMIT 100;
-- output jumps back up around row 50 (e.g. 99988 followed by 99996)
Adds a stateless regression test `04301_virtual_row_per_block_wide_partial_granule`.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Pre-PR validation gate (TASK.md / a) Deterministic repro? YES. With b) Root cause explained? YES. c) Fix matches root cause? YES. The fix derives the boundary PK from the chunk's actual data ( d) Test intent preserved / new tests added? YES. The original e) Demonstrated in both directions? YES. Without the fix the local reproducer fails on every run; with the fix f) Fix is general, not a narrow patch?
Session id: |
|
cc @KochetovNicolai @vdimir -- could you review this? It fixes an ORDER BY ... LIMIT mis-ordering when |
|
Workflow [PR], commit [d1493db] Summary: ❌
AI ReviewSummaryThis PR fixes incorrect Final VerdictStatus: ✅ Approve |
The chunk-derived path of `buildVirtualRowFromChunk` materialized the source PK column via `convertToFullIfNeeded` and then called `insertFrom` into a destination cloned from `pk_block_header`. When the PK type is `LowCardinality(...)`, the destination is `ColumnLowCardinality` while the materialized source is the nested full column, so `insertFrom`'s type check rejects it (an exception in debug builds; release would otherwise corrupt the per-block boundary). Round-trip through `Field` instead: `IColumn::get` and `IColumn::insert` are universally implemented across column representations, so this works for any source wrapper and any destination wrapper without special casing. The path runs at most once per chunk, so the per-value `Field` cost is irrelevant. Adds a regression test `04302_virtual_row_per_block_lc_pk` covering `LowCardinality(String)` and `LowCardinality(Int32)` primary keys with `read_in_order_use_virtual_row_per_block = 1` in both directions, with wide parts and a sub-granule `max_block_size` so the chunk-derived path is always selected. Also drops two em-dashes from prior comments per maintainer style guidance. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Thanks for catching this. The Confirmed the exception locally with Field field;
data_columns[pk_positions[j]]->get(source_row, field);
column->insert(field);
Pushed fbc3458 with:
Local results with the new binary (debug):
Pre-PR validation gate for this delta:
Comment text in |
|
@groeneai where this repro came from? Was is caught by CI? Do we have any test which tests similar randomized scenarios with different block size/index granularity and virtual row? |
Yes. Master CIDB hit on 2026-05-27 at commit (plus
Existing
The combination this PR fixes - wide parts ( The new tests fill that gap:
Session: cron:clickhouse-ci-task-worker:20260604-100400 |
| for (size_t j = 0; j < num_pk_columns; ++j) | ||
| { | ||
| const auto & header_col = pk_block_header.getByPosition(j); | ||
| auto column = header_col.column->cloneEmpty(); | ||
| /// Round-trip through `Field` so insertion works for any column representation on | ||
| /// either side (sparse / const / `LowCardinality` / replicated source, and the | ||
| /// destination is `ColumnLowCardinality` when the PK type is `LowCardinality(...)`). | ||
| /// Called once per chunk, so the `Field` cost is negligible. | ||
| Field field; | ||
| data_columns[pk_positions[j]]->get(source_row, field); | ||
| column->insert(field); | ||
| pk_columns.push_back({std::move(column), header_col.type, header_col.name}); | ||
| } |
There was a problem hiding this comment.
Is this trick for low cardinality correct? Can't if be arbitrary expression (difference in virtual row conversions applied)? Or where it comes from?
There was a problem hiding this comment.
The Field round-trip is correct here, and it cannot be triggered for an arbitrary expression PK.
Why the Field round-trip is type-agnostic. IColumn::get(size_t, Field&) and IColumn::insert(const Field&) are the universal value-extraction / value-insertion API on IColumn. Every column kind implements them - sparse, const, LowCardinality, replicated, nullable - so the source's representation does not matter, and the destination (cloned from pk_block_header, which carries the PK type) accepts the value regardless. For LowCardinality(...), ColumnLowCardinality::insert(Field) calls getDictionary().uniqueInsert(x) and works whether the source was full-form, dictionary-encoded, or replicated. The same pattern is used elsewhere in the codebase (e.g. Processors/Formats/Impl/Parquet/parquetBloomFilterHash.cpp, Processors/QueryPlan/Optimizations/useVectorSearch.cpp).
Why this cannot fire for an expression PK. pk_block_header is built in ReadFromMergeTree from primary_key.column_names and primary_key.data_types - the AST identifier of each PK expression and its evaluated type. For ORDER BY toStartOfMonth(date), column_names[0] = "toStartOfMonth(date)". The chunk path looks up that name in result_header (result_header.getPositionByName(pk_col_name)); the chunk only contains source columns, so result_header.has("toStartOfMonth(date)") is false and we return {}. The fallback to buildVirtualRowFromIndex then runs, which IS correct for expression PKs because the index file stores the evaluated PK values (primary_key.data_types[j]->getDefaultSerialization()->deserializeBinary in IMergeTreeDataPart::loadIndex).
So the chunk path activates only when pk_block_header[j].name appears verbatim in the chunk - which by construction means an identity PK column. For monotonic-chain PKs (e.g. ORDER BY date with PK (toStartOfMonth(date), x)) the conversion DAG expects the evaluated PK as input named "toStartOfMonth(date)", again something the chunk cannot supply, so we correctly fall back.
I will tighten the comment in buildVirtualRowFromChunk to make this guard explicit (it is currently buried in the fallback comment in read()).
Address vdimir's question (ClickHouse#106026 (comment)): make the expression-PK fall-through guarantee explicit at the result_header.has guard, and shorten the Field round-trip comment. No behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 47/49 (95.92%) | Lost baseline coverage: none · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes how the per-block boundary key is computed in the read-in-order (ORDER BY ... LIMIT on the sort key) merge optimization. The two flagged ClickBench improvements, Q4 (a plain AVG full-scan aggregate) and Q15 (GROUP BY with ORDER BY on an aggregate), do not use that path, so a real ~10-11% speedup from this change is not plausible. The baseline measurements were also noisier than the new runs, so both deltas are most consistent with run-to-run variance. Downgraded both to not-sure; no genuine performance change attributable to this PR. clickbenchFlagged queries (2 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
CI ledger — covered SHA:
|
| Check | Test | Disposition |
|---|---|---|
Integration tests (amd_msan, 2/6) |
test_paimon_incremental_read/test.py::test_paimon_to_mergetree_via_refresh_mv, test_paimon_incremental_read_via_paimon_table_engine |
chronic PR-only flaky on amd_msan; 4 distinct PRs in 14d on unrelated branches (chdig version, docs, shard profile events, this PR). Tracked in task 2026-06-04-ci-testpaimonincrementalread-chronic. NOT PR-caused (this PR only touches read_in_order virtual-row code). |
Bugfix validation (functional tests) |
04302_virtual_row_per_block_lc_pk |
this PR's OWN regression test — Bugfix validation framework limitation when bug-class isn't reproducible on master HEAD (the read_in_order_use_virtual_row_per_block randomization needs LowCardinality+wide partial reads to hit). Not a real regression. |
Stateless tests (amd_tsan, s3 storage, parallel, 1/2) |
01666_merge_tree_max_query_limit |
chronic flaky max_query_limit timing test on s3 storage — 3 PRs in 14d. NOT PR-caused. |
No PR-caused correctness failures. Awaiting human review.
Session: cron:our-pr-ci-monitor:20260604-213000
Fixes an
ORDER BY ... LIMITcorrectness bug whenread_in_order_use_virtual_row_per_block = 1is combined with wide parts that read partial granules. Output values can appear out of order around the seam between a stream's first and second emitted chunk, e.g.99988, 99996, 99996, ...instead of monotonically descending.Root cause
MergeTreeSelectProcessor::buildVirtualRowFromIndexcomputes the per-block boundary key fromindex[next_mark], i.e. the start of the next granule. For wide parts (MergeTreeReaderWide::canReadIncompleteGranulesreturns true), a single block can contain only part of a granule, so a chunk whoseread_mark_rangesreports[N, N+1)may carry just the last few rows of granule N while the rest of that granule lives in the previous forward chunk. ForMergeTreeInReverseOrderSelectAlgorithm(which buffers all chunks and pops them LIFO, thenReverseTransformflips each chunk's rows), this means the index-derived key sits far below the actual values still pending from this source.MergingSortedTransformthen deprioritizes the source and emits smaller values from other parts before returning to it, producing the mis-ordered output.Fix
Prefer extracting the per-block boundary PK from the chunk's actual data (
buildVirtualRowFromChunk):ReverseTransform.When the chunk has no surviving rows (PREWHERE filtered everything) or the PK columns are not part of the query result, fall back to the original index-based path -- but only if the chunk's
num_read_rowsexactly equals the granule sizes covered byread_mark_ranges, so partial-granule reads no longer emit a misleading boundary.Source columns from the chunk are materialized via
convertToFullIfNeededbeforeinsertFromso the read works regardless of sparse / const / low-cardinality / replicated wrappers.Reproducer (fails on master, passes with this PR)
Before the fix, the output transitions from
99988straight back to99996, 99996, 99994, ...around row 50. After the fix, the output is monotonically non-increasing.The feature was introduced in #100603. The existing test
04057_virtual_row_many_partsdoes not pinmin_bytes_for_wide_part = 0and only catches the bug when the random-settings runner hits the wide + small-max_block_size+ small-index_granularitycombination. A new stateless test04301_virtual_row_per_block_wide_partial_granulepins these settings and asserts bothORDER BY ... DESC LIMIT 100andASC LIMIT 100are monotonic.Validation
04057_virtual_row_many_parts: 50/50 successful runs with--test-runs 50and full random-settings randomization on a local debug build.virtual_row/read_in_orderstateless tests still pass.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong
ORDER BY ... LIMIToutput when reading wideMergeTreeparts withread_in_order_use_virtual_row_per_block = 1and anindex_granularitylarger thanmax_block_size. The per-block virtual-row boundary is now derived from the chunk's actual data instead of the granule edge, soMergingSortedTransformno longer deprioritizes a source whose next chunk still contains larger values.Documentation entry for user-facing changes