Repository navigation
Conversation
Pre-PR validation gate
Note: measured on x86 (the build machine); the regression reported on ARM is the cost of reading the larger column off disk through the planning/exec path on a tiny query, which is architecture-independent and directly observed here via Session id: cron:clickhouse-worker-slot-0:20260612-201200 |
|
cc @KochetovNicolai @davenger — could you review this? When a query reads no real columns (e.g. |
|
Workflow [PR], commit [ae9d462] Summary: ❌
AI ReviewSummaryThis PR improves no-output Findings❌ Blockers
Final Verdict❌ Not ready to merge: the two unresolved |
|
📊 Cloud Performance Report
Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. This PR only changes how ReadFromMergeTree picks a fallback column for queries that read no real columns (for example count() with trivial-count optimizations off, or isNullable(x)). It now ranks candidates by on-disk compressed size instead of in-memory size. None of the flagged ClickBench or TPC-H queries is that kind of query, so all directional improvements except one were downgraded to not_sure. ClickBench Q32 (-46.1%) is too large to override, but it reads real columns, so it is most likely an upstream gain. All flags are improvements, and the base build (26.9) is older than the source (26.10), so a baseline built on the PR's exact merge-base would show this PR as performance-neutral on these benchmarks. clickbench🟢 1 improved · Flagged queries (6 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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_officialFlagged queries (5 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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. Debug info
|
bb97bb2 to
06e574b
Compare
When a query references a column whose result is constant-folded away (for example isNullable(lc), which depends only on the type), ReadFromMergeTree ends up with no columns to read and must pick one column just to know the number of rows. It picked the column with the smallest in-memory value size via ExpressionActions::getSmallestColumn. That metric mis-ranks compactly stored columns: a LowCardinality(String) is tiny on disk but looks larger in memory than a UInt64 (8 bytes), so the reader read the larger UInt64 column and pulled far more data off disk than necessary. Pick the column with the minimum on-disk compressed size instead, using the existing IMergeTreeDataPart::getColumnNameWithMinimumCompressedSize helper. This is the same metric the read path already uses in injectRequiredColumns, so the two carrier-selection sites now agree. Fall back to getSmallestColumn only when no parts are available. This recovers the low_cardinality_argument performance test query 0 (SELECT isNullable(lc) FROM test_lc) without degrading the case where a small column is genuinely cheaper than the referenced one. The regression test uses ORDER BY tuple() so the table has no sorting-key column. With a sorting key, the split-ranges read path (controlled by the randomized merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability testing setting) additionally reads the key column to merge intersecting ranges, which inflated ReadCompressedBytes past the assertion threshold regardless of the carrier column and made the test flaky. Removing the sorting key keeps the carrier choice the only thing that decides what is read. Closes: ClickHouse#106597 Co-Authored-By: Claude Opus 4.8 <[email protected]>
06e574b to
ae4fddf
Compare
Pre-PR validation gate (test-determinism follow-up, commit ae4fddf)The previous commit's regression test
Note: the flaky-check "Server died" verdict was investigated and is NOT a real server crash. The flaky-check ran only this test 50x, hit the failure cap on the same Session id: cron:clickhouse-worker-slot-0:20260613-010900 |
…-evolved parts The previous commit on this branch switched the no-columns-to-read carrier selection in selectRangesToRead from ExpressionActions::getSmallestColumn (in-memory size) to IMergeTreeDataPart::getColumnNameWithMinimumCompressedSize measured on parts.front(). That has two problems, both raised in review: 1. The carrier is global to the read but was sampled from a single part. A column that is tiny in the first part but dense in the later (larger) parts would be picked, and since injectRequiredColumns then finds it physically present, the read would still pull the large column for most of the table. 2. getColumnNameWithMinimumCompressedSize throws LOGICAL_ERROR when the measured part has files for none of the columns it is given. A selected part can be in that state when it predates the current schema (e.g. written with column `a` while the metadata has since added `c DEFAULT` and dropped `a`), so a query reading no columns (SELECT 1 FROM t FORMAT Null) crashed the server. Sum each current physical column's compressed size over all selected parts and pick the global minimum. Only parts that actually have a column's files contribute, so a schema-evolved part simply does not vote; if no current column has files in any part, fall back to getSmallestColumn. The carrier stays a current metadata column, so it resolves against the StorageSnapshot and the per-part read setup substitutes missing columns as before. Co-Authored-By: Claude Opus 4.8 <[email protected]>
432e9a7 to
3755e7c
Compare
|
Follow-up commit 3755e7c addresses both review findings (schema-evolved-part LOGICAL_ERROR and single-part carrier sampling). Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-1:20260613-003600 |
The aggregate on-disk size used to rank carrier candidates is only meaningful for wide parts. Compact parts keep every column in one file and report a per-column data_compressed of 0, so summing it tied every column at 0 and the carrier fell to the first metadata column, which can be the most expensive one to read. Restrict the candidates to columns physically present in every selected part, rank those by the aggregate on-disk size when it is positive, and fall back to ExpressionActions::getSmallestColumn (the in-memory heuristic) otherwise. Requiring presence in every part also keeps the carrier from being a column stored only in a new part after schema evolution, which would otherwise force a DEFAULT materialization that pulls a large dependency column on the parts where the carrier is missing. Extends 04337 with a compact-part scenario that fails before this change (the carrier reads the dense String column instead of the UInt8). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (follow-up commit 4175aff, finding #3)
Session id: cron:clickhouse-worker-slot-0:20260613-023600 |
The count() on the all-pruned part is deterministic only via the trivial count optimization, which reads the row count from part metadata. With optimize_trivial_count_query and optimize_use_implicit_projections both randomized off (as the flaky check does), count() takes the no-columns read path, hits the unreadable part and throws NO_SUCH_COLUMN_IN_TABLE. Pin the setting so the row count stays metadata-derived regardless of randomization. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Also fixed a flaky-check failure the msan run surfaced on the new 04337 schema-evolved scenario (commit 499a2f2):
|
A compact part stores all columns in one file and reports a per-column on-disk size of 0. Summing the aggregate compressed size over all parts therefore ignores the compact part entirely: in a mixed compact/wide layout, a column that is small in a tiny wide part but huge in a dominant compact part could still win the ranking and become the carrier, reading the whole expensive column off the compact part. Only rank a candidate by aggregate on-disk size when every selected part reports a positive size for it; otherwise leave it unranked and fall back to the in-memory heuristic (getSmallestColumn), which ranks a UInt8 below a String. This is the same fallback already used for the all-compact and heavily-schema-evolved cases. Extend 04337 with a mixed compact/wide scenario, and pin query_plan_remove_unused_columns: when it is disabled the planner keeps an unused column as a read input instead of reaching the carrier path, which would read megabytes and break the byte-count assertions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit ad3f1da)
Session id: cron:clickhouse-worker-slot-0:20260613-034000 |
|
CI finished on ad3f1da. The only red is
|
|
CI finished on ad3f1da. The only red is This PR's own regression test |
The carrier column for a no-columns read (e.g. SELECT count() or SELECT isNullable(x) where x constant-folds away) was chosen over the pre-pruned `parts`, before filterPartsByPartition, filterPartsByPrimaryKeyAndSkipIndexes, the query-condition cache and projection filtering populate result.parts_with_ranges. Ranking over the pre-pruned set is both wasteful (an O(parts * columns) size scan over parts that may be dropped) and fragile: parts pruned later neither contribute to the cost of the read nor make a column "present in every part", so a column that is cheap only in pruned parts could be picked as the carrier for the surviving parts. Move the non-streaming carrier choice to after result.parts_with_ranges is final, so it ranks only over the parts that will actually be read. The streaming early-return path runs before pruning, so it keeps choosing over the pre-pruned parts as before. When no part survives, the read is a NullSource that reads nothing, so no carrier is appended. The selection logic is unchanged and is factored into a shared helper. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (bot finding #5: defer carrier choice past pruning)
Session id: cron:clickhouse-worker-slot-2:20260613-131500 |
The carrier column for a no-columns read (e.g. SELECT count()) was ranked during selectRangesToRead, after partition/PK/skip-index/query-condition-cache pruning. But optimizeUseNormalProjection and optimizeUseAggregateProjection run later and call filterPartsByProjection, removing parent parts from parts_with_ranges without recomputing the carrier. A column cheap only in a projection-covered (now pruned) part could win and the surviving parent part would then be read through an expensive column. Defer the carrier choice to initializePipeline, the last point before the read, once all plan optimizations (including projection filtering) have finalised parts_with_ranges. The streaming path keeps choosing over the pre-pruned parts as before. When no part survives the read is a NullSource, so no carrier is needed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The no-columns carrier (the cheap column a SELECT count() reads just to learn the row count) was chosen in initializePipeline before the distributed_read_bucket_count block. In a bucketed make_distributed_plan read, filterMarkRangesForBucket trims ranges and can drop whole parts per worker, so the carrier was ranked over the pre-bucket part set. A worker reading only the part where the globally-cheapest column is expensive then reads that expensive column, reintroducing the stale-carrier problem for distributed reads. Move the carrier choice past the bucket block so it ranks over the parts this pipeline actually reads, keeping the !parts_with_ranges.empty() guard (zero surviving parts become a NullSource). This mirrors the earlier move past the projection-filtering optimizations. Non-distributed reads are unaffected: the bucket block is skipped, so the carrier site is functionally identical. Local A/B over a two-part table where the globally-cheapest column is the expensive one in one part (make_distributed_plan, 3 buckets): the distributed read went from 2,008,345 to 502 ReadCompressedBytes. The committed scenario asserts the bucketed no-columns read stays correct (the distributed worker pipeline does not surface ReadCompressedBytes, so the byte win cannot be asserted in a parallel-safe stateless test). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-0:20260624-081000 |
The no-columns carrier (SELECT count() etc.) ranks candidate columns by getColumnSize().data_compressed, a whole-part figure. A distributed bucket read (filterMarkRangesForBucket) can leave a worker only a subset of a part's mark ranges, so a column cheap over the whole part may be the expensive one in the marks that worker actually reads. Scale each column's per-part compressed size by selected/total marks so the ranking reflects the ranges this pipeline reads. The factor is 1 for a full read, so non-distributed plans are unchanged; it tracks cross-part trimming exactly and intra-part trimming under a uniform-compression assumption (per-range compressed sizes are not tracked in part metadata). Follow-up to the carrier-after-bucket-filter move. Added a single-many-mark-part bucketed scenario to 04337. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (bot finding #8 — per-range carrier cost, commit
|
| # | Question | Answer |
|---|---|---|
| a | Deterministic repro? | Yes. Two-part table (part1 a 251 B/b 2 MB, part2 a 10 MB/b 251 B, global a>b); a bucketed count() (make_distributed_plan=1, distributed_plan_execute_locally=1, reader_bucket_count=2/3) ranks the carrier over the pre-bucket set and reads ~2 MB off the part where the global carrier is the expensive column. Measured via system.events['ReadCompressedBytes'] deltas on a debug build. |
| b | Root cause explained? | chooseColumnToReadForNoColumnsQuery ranked candidates by getColumnSize().data_compressed, a whole-part figure, ignoring part.ranges. filterMarkRangesForBucket can trim a part to a mark subset per worker, so a column cheap over the whole part can be the expensive one in the marks that worker reads. Finding #7 moved the choice after the bucket block (fixing whole-part DROP); this fixes intra-part range TRIM. |
| c | Fix matches root cause? | Yes. The per-part cost is now scaled by selected_marks / total_marks (getMarksCountWithoutFinal), so the ranking reflects the marks this pipeline reads — directly the quantity that was wrong. |
| d | Test intent preserved / new tests added? | Yes. Added t_smallest_column_bucket_ranges (single many-mark part under a bucket plan, exercising the mark-fraction path). All 6 existing scenarios unchanged; no assertion weakened; SET enable_analyzer=1 / query_plan_remove_unused_columns=1 / optimize_trivial_count_query pins intact. |
| e | Both directions demonstrated? | Yes. Without scaling (pre-fix) the bucketed count() reads ~2 MB; with scaling it reads 602 / 502 bytes (each worker picks the column cheap in its own part). 04337 passes 20/20 with randomization. |
| f | Fix is general across code paths? | Yes. Both carrier call sites (streaming selectRangesToRead and initializePipeline) go through the same function; the scaling applies uniformly. No symptom-guard — the cost computation itself is corrected. |
| g | Fix generalizes across inputs? | Yes. Independent of column type/wrapper (cost is bytes-on-disk); handles 1..N parts, full and trimmed ranges, and any reader_bucket_count. The zero-size-part fallback (compact parts) is unchanged. The factor-1 full-read path keeps LowCardinality/Nullable ranking identical to before. |
| h | Backward compatible? | Yes. Internal planner heuristic for which physical column a no-columns read materializes; no setting, on-disk/wire format, or result change. Only the bytes read off disk for count()-like queries change. |
| i | Invariants and contracts preserved? | Yes. The carrier stays a current-metadata physical column present in every selected part (resolves against the StorageSnapshot); the carrier.empty() in-memory fallback is preserved for compact/schema-evolved parts. part.ranges is already final at both call sites (after pruning, projection filtering, and the bucket filter). |
Session id: cron:clickhouse-worker-slot-0:20260624-105400
The no-columns carrier ranked candidate columns by whole-part compressed size scaled by the read mark fraction. Within one part that fraction is the same constant for every candidate, so it cannot reorder columns: a worker that keeps only a subset of a part's marks still picked the column cheapest over the whole part, even when it is the expensive one in the marks read. Part metadata holds no per-mark-range compressed sizes, so a range-local cost cannot be computed at plan time. When any selected part is read with trimmed ranges (a distributed bucket / parallel-replicas read), distrust the whole-part on-disk sizes and fall back to the in-memory heuristic, which does not depend on how many marks are read. A true no-columns query has no predicate, so a non-distributed read is never range-trimmed and keeps the on-disk ranking, leaving all existing byte-count behaviour unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gateHead
Session id: cron:clickhouse-worker-slot-0:20260624-125300 |
CI finish ledger — 7addc3aEvery failure below has an owner. This PR is a
STID 2508-34af/3e7b is a chronic trunk RefreshTask scheduling crash (24 master hits / dozens of unrelated PRs / 30d, Issue #106737). The hung-check deadlock is a separate chronic trunk family. Neither is reachable from this PR's diff. Session id: cron:our-pr-ci-monitor:20260624-173000 |
CI finish ledger — d45eeb1Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-043000 |
Master gained a check-style rule on 2026-07-27 (PR ClickHouse#110471, ci/jobs/scripts/check_style/various_checks.sh) that rejects the phrases "new analyzer" and "new query analyzer": the analyzer has been enabled by default since 24.3 and is no longer new. Two comment lines in this test used that wording. They were style-clean when written; the rule arrived on this branch with a master merge, which is why Style check turned red without a change of ours. Comment text only: no assertion, setting or query is touched, so the byte-count assertions the test makes are unaffected. The "old analyzer" wording in the same paragraph is not covered by the rule (its pattern requires a leading "new") and remains the accepted term on master. Reverting either changed word alone reproduces one of the two reported lines, and reverting both reproduces the CI output verbatim; driving check_style.py's check_other over the tree reports OK after the change.
The streaming early-return in selectRangesToRead stored the ranked carrier in result.column_names_to_read, but a streaming read never looks at that list: groupPartitionsByStreams builds MergeTreeCommitOrderSequentialSource from the all_column_names member, and the source derives its own read list from that (extendWithAuxiliaryColumns(user_requested_columns)) against a snapshot it builds itself. The only consumers of column_names_to_read - the spreadMarkRanges family and the deferred-filter block - are on the non-streaming path. So the per-part ranking scan behind that push was dead work, and the comment claiming a carrier was chosen there was wrong. Restore the cheap in-memory choice on that path, which is what the code did before this PR, so streaming behaviour is unchanged and no part metadata is scanned for a value nobody reads. The read-time site in initializePipeline is now the helper's only caller. Also say "throwing a LOGICAL_ERROR exception" instead of "crashing the server" in the schema-evolved scenario comment: that failure is a caught exception in release builds and only aborts under debug and sanitizer builds. Verified on a debug build (Build ID a79bf5c7990c8118779c5ebbb7ccac3a367fbb82): the regression test's output matches its reference exactly, and the annotated statement still throws NO_SUCH_COLUMN_IN_TABLE. Forcing the on-disk ranking to fall back to the in-memory heuristic turns three of the five byte assertions from 1 to 0, so the ranking this PR adds is still the thing under test.
The comment claimed that parallel-replica reads fall back to the in-memory heuristic, which they do not: the range-trimming check runs in initializePipeline, while the coordinator assigns and cuts mark ranges later, in MergeTreeReadPoolParallelReplicas::getTask. At selection time the parts still carry the full announced ranges, so the check cannot see that trimming and such a read keeps the whole-part ranking. That is the intended behaviour, not a defect to guard: the whole-part size is the best estimate available at plan time, and the carrier only supplies the row count, so every candidate is equally correct and a per-replica mis-rank costs bytes rather than correctness. Disabling the ranking whenever parallel replicas are active would give up the improvement this PR exists for on those reads. Say what actually happens instead, and name the boundary that would have to move to make the estimate per-assignment. Comment text only: with comments stripped and whitespace collapsed the translation unit hashes identically to the previous commit (5d120c2a…), while the pre-PR master version of the same file differs (dc31fa1e…).
The comments around the no-columns carrier had grown to 58 added lines in this file and restated the reasoning that belongs in the commit message and the PR description. Cut them to 37 and keep only what is not evident from the code at each site: why candidates must be present in every part, why a whole-part size cannot describe a range-trimmed read, why parallel replicas keep the whole-part ranking, why a zero size is not "free", and why this has to run last. Comment text only: with comments stripped and whitespace collapsed the translation unit hashes identically to the previous commit (5d120c2a…), while the pre-PR master version of the same file differs (dc31fa1e…).
| /// both shrink parts_with_ranges, so a carrier chosen earlier could be ranked over parts this | ||
| /// pipeline never reads. An empty parts_with_ranges needs no carrier (the read becomes a | ||
| /// NullSource below). | ||
| if (result.needs_no_columns_carrier && result.column_names_to_read.empty() && !result.parts_with_ranges.empty()) |
There was a problem hiding this comment.
result.column_names_to_read still is not final here. A no-output SAMPLE query reaches this branch with the list empty, but spreadMarkRanges appends the sample_by_ast inputs later at ReadFromMergeTree.cpp:3591-3600, and the deferred-filter block below can append row-policy / PREWHERE columns at ReadFromMergeTree.cpp:4185-4192. So SELECT count() FROM t SAMPLE ... still pays chooseColumnToReadForNoColumnsQuery's O(parts * columns) size scan and can drag along an extra carrier column even though sampling already gives the read a real physical column.
Before this PR the dead work here was only the cheap ExpressionActions::getSmallestColumn heuristic; with the new helper it becomes a per-part walk over every candidate column on a path the new test file does not cover. Please delay carrier insertion until after all mandatory read columns are known, or skip it when sampling / deferred filters already guarantee that some physical column will be read.
There was a problem hiding this comment.
Half of this reproduces and half does not. Measurements below are on a debug build of this head
(server buildId() matched the binary's ELF note), with a master control built from the same
snapshot so "new cost" claims are attributable.
The SAMPLE half does not reproduce, for two independent reasons.
spreadMarkRanges does not append to result.column_names_to_read. It copies into a local first
(Names column_names_to_read = result.column_names_to_read;) and the sample_by_ast loop pushes
into that local, which is then passed by value to spreadMarkRangesAmongStreams. Grepping the whole
function body for result.column_names_to_read returns exactly one hit, the copy. So the guard at
:4149 cannot be invalidated by sampling. Call order also runs the other way: :4149 executes before
the single spreadMarkRanges call site at :4540.
The O(parts * columns) size scan does not run on this path either. chooseColumnToReadForNoColumnsQuery
already declines the on-disk ranking when any part is range-trimmed, and SAMPLE trims ranges, so the
getColumnSize loop is skipped and the in-memory fallback is used. What remains is hasColumnFiles
per candidate, which is a checksums-map lookup in both the Wide and Compact implementations and does
not force the lazy size calculation.
That is visible in the bytes. With big 141,664, mid 1,606,925, k 3,213,823 and 25 sampled marks,
SELECT count() FROM t SAMPLE 0.5 reads 2,501,601, matching mid alone (2,501,122) rather than the
on-disk smallest big (1,653,096) - i.e. the in-memory pick, so the ranking really was skipped. On the
untrimmed path the same table reads 141,887, matching big.
The extra carrier under SAMPLE is also not new. On the master control, same fixture and queries, the
sampled count() reads 2,501,601 - byte-identical to this head, same carrier. Master inserts its carrier
unconditionally when the read set is empty, earlier and with the same heuristic. The two builds differ
only on the untrimmed path, where master reads 1,606,925 against this head's 141,887.
The deferred-filter half does reproduce, and it is the part worth fixing. That block does append to
result.column_names_to_read, and it runs after :4149. With a ReplacingMergeTree and a row policy on a
column other than the carrier, SELECT count() FROM t FINAL goes from 1,964 bytes to 157,831 once the
policy is added, and the policy column alone accounts for 157,386 - so the read gets a real physical
column anyway and the carrier is dead weight.
I have not taken the suggested "skip it when sampling guarantees a physical column" here. Because the
sampling columns land in that local copy, skipping the carrier would leave result.column_names_to_read
empty for the consumers that do read it, including the deferred-filter name set immediately below, so it
is not a drop-in. SAMPLE BY also takes an expression, so at :4149 only use_sampling is known, not
which columns sampling will end up needing.
So I am folding the ordering point into the redesign already open on this PR rather than special-casing
it: two earlier findings ask the same question, whether the cached getColumnSize figure is the right
cost oracle for this ranking and where the carrier decision belongs once the read set is final. A local
guard here would be rewritten by that work. The coverage gap is fair and I will add SAMPLE and
deferred-filter cases to the test as part of it.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 64/66 (96.97%) · Uncovered code |
CI finish ledger - 21f2528Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-120000 |
|
Before this merges: I found a shape where this change reads more bytes than master, and I had not disclosed it here yet. I would rather say so than let it merge on my silence.
For CREATE TABLE t_share3 (n Nested(a UInt64, b String))
ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t_share3
SELECT arrayResize(emptyArrayUInt64(), 1 + rand() % 200, 7::UInt64),
arrayResize(emptyArrayString(), 1 + rand() % 200, 'q')
FROM numbers(300000);
OPTIMIZE TABLE t_share3 FINAL;One Wide part, 50 marks. Stream sizes on disk: Measured
The carrier figure equals the predicted To be clear about the size of the claim: it needs two columns sharing a substream with I have not sent a fix, because I do not think the right one is a patch on top of this ranking loop. Happy to do that work. Given you have just merged master in, tell me whether you would rather hold this for the redesign, or merge the |
Resolves one conflict in ReadFromMergeTree.cpp. Master's 6b27f2d deprecated merge_tree_enable_remove_parts_from_snapshot_optimization and made the snapshot stripping in initializePipeline unconditional, dropping the enable_remove_parts_from_snapshot_optimization || query_info.isStream() guard that this branch had adapted. I kept master's unconditional block and its comment, and kept the deferred no-columns carrier injection immediately above it, which is where this branch needs it: filterPartsByProjection and the distributed bucket filter both shrink parts_with_ranges, so the carrier has to be ranked after them. Checked after the merge: selectRangesToRead still computes needs_no_columns_carrier before the streaming early return, which keeps the cheap in-memory choice there; initializePipeline still reaches the deferred injection with no intervening return; and master's own use of getColumnNameWithMinimumCompressedSize is confined to the estimateReadBytes cost estimator, so it does not overlap the read path this branch changes.
| bool measurable_in_all_parts = true; | ||
| for (const auto & part : parts) | ||
| { | ||
| size_t part_size = part.data_part->getColumnSize(column.name).data_compressed; |
There was a problem hiding this comment.
getColumnSize is not the cost of reading this candidate in isolation on Wide parts. MergeTreeDataPartWide::calculateEachColumnSizes caches per-column sizes with one processed_substreams set shared across the whole part, so a shared stream is charged only to the first column that visits it. With share_nested_offsets = 1, a Nested(a, b) layout puts n.size0 entirely on n.a; n.b then looks smaller here even though reading n.b alone still has to pull n.size0.
That means a no-columns read can now pick the more expensive carrier and regress against master on shared-substream tables. I think this needs either an accessor that prices a candidate column independently, or a fallback that refuses the on-disk ranking when a candidate shares streams with a sibling.
There was a problem hiding this comment.
Confirmed, and it is the same mechanism I disclosed in #107368 (comment) rather than a new one: one processed_substreams set per part (MergeTreeDataPartWide.cpp:641, :644) and getColumnSizeImpl returns early for a stream already in it (:226 at this head, :225 when I wrote that comment). So the column visited later has the shared stream charged to its sibling.
That comment carries the Nested(a UInt64, b String) reproducer and the ReadCompressedBytes numbers: on that shape the carrier path reads 1,980,648 against master's 1,862,300, so it is a 6.4% regression there rather than a missed optimization.
Your two remedies are the two I listed there. One caveat on the second: "refuse the on-disk ranking when a candidate shares streams with a sibling" must not be implemented as "only rank single-stream candidates", because that would exclude LowCardinality(String), whose dictionary and index streams are its own, and that is the case this PR exists to fix.
Choosing between the two is the open question in that comment and it is still unanswered, so I do not think this should merge as it stands.
| bool measurable_in_all_parts = true; | ||
| for (const auto & part : parts) | ||
| { | ||
| size_t part_size = part.data_part->getColumnSize(column.name).data_compressed; |
There was a problem hiding this comment.
This getColumnSize call also makes the first virtual-only read on a cold part bootstrap calculateColumnsAndSecondaryIndicesSizesOnDiskUnlocked() when columns_and_secondary_indices_sizes_lazy_calculation = 1 (the default). That computes all column sizes and all secondary-index sizes before returning this one number, and the secondary-index side goes through the storage overlay / Keeper path for packed substreams.
So a SELECT count() / SELECT 1 FORMAT Null that used to stay in a pure in-memory heuristic can now pay a full size-cache build just to choose the carrier. We should avoid triggering the lazy size calculation from this path unless the sizes are already cached, or precompute/store a cheaper carrier metric elsewhere.
There was a problem hiding this comment.
Confirmed, and also on the record in the last paragraph of that same comment: #107368 (comment)
Re-verified at this head: getColumnSize computes under the lock when the sizes are absent and checksums are loaded (IMergeTreeDataPart.cpp:3169-3173), which runs both calculateColumnsSizesOnDisk() and calculateSecondaryIndicesSizesOnDisk() (:3068-3069); the setting defaults to true (MergeTreeSettings.cpp:2413); and the secondary-index half's packed-substream fallback goes through the storage overlay, "which reaches Keeper in the metadata-in-Keeper configuration" (:3100-3103).
Two refinements, in opposite directions. The memory is not charged to the query (MemoryTrackerBlockerInThread, :3062), so what a virtual-only read on a cold part pays here is latency and IO rather than query memory. Against that, your "unless the sizes are already cached" remedy is cheaper than I assumed when I wrote that comment: IMergeTreeDataPart::areColumnAndSecondaryIndexSizesCalculated() is already public on master and documented as never triggering the lazy computation, so gating this path on it needs no new accessor.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units122 translation units recompiled, 1388 s compile time in total, 122 of them have a recent master baseline. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Superseded by #131371 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
When a query reads no real columns (for example
SELECT isNullable(lc) FROM t, where the result is constant and depends only on the type), theMergeTreereader now picks the column that is cheapest to read from disk to carry the row count, instead of the one with the smallest in-memory value size. The previous metric mis-ranked compactly stored columns such asLowCardinality(String)below aUInt64, causing the reader to read a much larger column off disk.Description
Closes: #106597
SELECT isNullable(lc) FROM test_lcis constant-folded away (isNullabledepends only on the column type), soReadFromMergeTreeis left with no columns to read and must pick one column just to know the number of rows.selectRangesToReadpicked it withExpressionActions::getSmallestColumn, which ranks by the in-memory value size: aUInt64is 8 bytes, while aLowCardinality(String)falls back to a heuristic of 100. So it chose theUInt64columnx, which is far more expensive to read off disk than the dictionary-encodedlc.This PR makes the fallback pick the column with the minimum on-disk compressed size via the existing
IMergeTreeDataPart::getColumnNameWithMinimumCompressedSizehelper. That is the same metric the read path already uses ininjectRequiredColumns, so the two carrier-selection sites now agree. It falls back togetSmallestColumnonly when there are no parts to measure.Verified locally with
ReadCompressedByteson the perf-test table (x UInt64,lc LowCardinality(Nullable(String)), 1e7 rows):SELECT isNullable(lc)x)lc)SELECT 1 FROM test_lcx)lc)SELECT isNullable(big)on(tiny UInt8, big String)tiny)tiny)The last row is the no-regression check: when a small column is genuinely cheaper than the referenced one, the choice is unchanged. Added a regression test
04337_read_smallest_column_by_disk_sizethat fails before this change and passes after it.Workflow [PR]
Sync PR [sync-upstream/pr/107368]