Skip to content

Do not read sparse columns that have only default values in a Wide part - #130692

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:sparse-only-defaults-wide-reader
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:sparse-only-defaults-wide-reader

Conversation

@groeneai

@groeneai groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130330

Changelog category (leave one):

  • Performance Improvement

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

Sparse columns of a Wide part that contain only default values in that part are no longer read from disk: their files are not opened. SELECT * and merges on wide tables with many such columns are faster, for example a point lookup on a 400-column table takes 41% less time and 95% less memory.

Description

When a sparse column has only default values in a part, its values files are empty in the part's checksums: every non-default value writes at least one byte to them. MergeTreeReaderWide still created a stream for each of its files (marks load, open, read buffer) and decoded its offsets: a point lookup on a 400-column table opened 902 files to return one row.

addStreams now creates no streams for a top-level sparse column that has all its streams in the part and only empty values files, and readSegmentFromDisk appends as many defaults as reading the offsets would give: from the mark the read starts at (or where the previous read ended) up to the end of the part. Prefetch skips such columns. The type default is what the part stores, so a DEFAULT <expr> column that holds zeros still reads zeros.

This is the patch posted by @ snelheidai in #130330 (comment); it does not depend on the issue's SerializationSparse change.

Local release build, 100K rows in one part, 15 paired runs (issue's tables):

Query Change [95% CI]
400 all-default columns, point lookup -41.5% [-42.9, -40.1], FileOpen 902 -> 2
1600 all-default columns, point lookup -44.2% [-46.6, -41.6]
400 all-default columns, full scan -50.3% [-50.9, -49.7]
merge of 4 all-default parts -50.2% [-57.3, -41.9]

Columns with values and dense columns are unchanged: their point-lookup intervals include 0 (between -1.4% and +3.4%), dense merge -1.3% [-9.0, +7.1]. A new stateless test checks the results, the DEFAULT case and that no file is read; the performance test sparse_column_only_defaults_wide measures it in CI. Output is identical to master on a differential over all sparse-capable types, two disks and eight read settings profiles.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits November 11, 2026 04:48
A sparse column whose values files are all empty in the part's checksums
has no value that is not the default: every non-default value writes at
least one byte to them. Reading such a column still created a stream per
file (marks load, open and a read buffer for the offsets file and for each
empty values file) and decoded its offsets, once per column per reader. On
wide tables with many such columns this dominated point lookups, top-N
queries, full scans and merges.

`MergeTreeReaderWide::addStreams` now creates no streams for a top-level
sparse column (not a subcolumn) that has all its streams in the part and
only empty values files, and `readSegmentFromDisk` appends the defaults
itself: as many rows as reading the offsets would give, from the mark the
read seeks to (or from where the previous read of the column ended) up to
the end of the part. `prefetchForColumns` skips such columns. The type
default is what the part stores, so a `DEFAULT <expr>` column that holds
zeros still reads zeros; that is why the column is not treated as absent
from the part.

Measured on a 400-column table with 100K rows in one part (release build,
paired runs): a point lookup on all-default sparse columns -41.5%
(FileOpen 902 -> 2, memory 70.8 -> 3.7 MiB), full scan -50.3%, merge of
4 such parts -50.2%; columns with values and dense columns unchanged.

Patch by @ snelheidai in
ClickHouse#130330 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the only_defaults_next_row member comment to one line.

Co-Authored-By: Claude Opus 5.5 <[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, 0 on the re-review of the fix) plus my own review (2 findings, 0 on the re-review).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new performance test is selected by the Iceberg configuration of the performance tests, where it measures nothing this PR changes and its ALTER ... ADD COLUMN setup runs against an Iceberg table AGREE, fixed @ 8ac2075 <test iceberg="0">
2 ⚠️ The FileOpen / ReadCompressedBytes check can pass unfixed when parallel replicas do the read (05616...sql) AGREE, fixed @ 8ac2075 enable_parallel_replicas = 0 on the measured query
3 💡 countIf(n IS NOT NULL) is answered from n.null, so the non-NULL '' value never goes through the changed full-column read AGREE, fixed @ 8ac2075 the test reads n of that row 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-review-slot-8:20261111-045100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. In the new test, FileOpen, ReadCompressedBytes of SELECT sum(u) on an all-default sparse column is 3 132 on master and 0 0 with the change, every run.
b Root cause explained? The reader created streams (marks load, open, buffer) and decoded the offsets of a sparse column whose values files are all empty in the checksums, although that already proves the column holds only defaults.
c Fix matches root cause? Yes. No streams are created for such a column; the reader appends the defaults itself, exactly as many rows as the offsets read would give (seek: mark start; continue: previous end; capped at the part's rows).
d Test intent preserved / new tests added? New stateless test (kinds, counters, DEFAULT 5 stored as 0, LIMIT/OFFSET at the end, PREWHERE, a second part with values) and a new performance test. Dropping the values check or treating the column as absent makes the test fail. 100/100 randomized runs pass, and 20/20 with the parallel replicas profile (the counted query pins enable_parallel_replicas = 0, where master still fails).
e Both directions demonstrated? Yes: master fails the test (counters 3 132), the change passes; both mutants fail it.
f Fix is general across code paths? All reads go through readSegmentFromDisk (plain, columns cache, whole-part reads without marks, merges, patch parts, PREWHERE steps, lazy materialization, FINAL); prefetch skips the column. Compact parts use another reader. A differential over 8 read settings profiles and 2 disks gives identical output.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked for UInt32, String (both string serializations), FixedString, Decimal, Bool, Date, IPv4, sparse Nullable columns, DEFAULT/MATERIALIZED columns, and one minimal non-default value per type (which keeps the normal path). Subcolumns are excluded by design.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; existing parts give identical results.
i Invariants and contracts preserved? Each read returns the same rows (count and values) as the offsets decode. The per-column flag is set only in the constructor and the row position only by the reading thread; no lock changes.

Session id: cron:clickhouse-impl-slot-7:20261110-235100

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3a6c707]

Summary: ✅


AI Review

Summary

PR #130692 avoids opening streams for top-level sparse columns containing only stored defaults in a Wide part, generating the corresponding rows directly. No actionable findings at commit 3a6c7078645ef698a0432b79384b1e7873e520c5. The focused regression test and reported before/after measurements support the performance claim. Runtime tests were not independently rerun locally.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3a6c70786 with master 46bd37447 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

4 object files changed (+19.21 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderWide.cpp.o 408.99 KiB 428.20 KiB +19.20 KiB (+4.70%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 13.0 s +9.5 s (+274%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.2 s +5.2 s (+254%)
Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits November 11, 2026 08:58
The test inserted one row of zeros into a Wide part on `s3_disk`, so both
columns were sparse with only default values. Such columns are no longer
read from the disk, so the retried `SELECT a, b` made no S3 request and
`DiskConnectionsPreserved` stayed 0 (measured: 2 `S3GetObject` per query
before, 0 after). Insert non-default values so the query still reads the
part from S3 and the test keeps checking connection reuse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test counts FileOpen and ReadCompressedBytes of `SELECT sum(u)` to show
that a sparse column with only defaults is not read. With
`merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability`
above 0 and more than one stream, `ReadFromMergeTree` turns the read into an
in-order one and adds the sorting key `k` to the columns it reads, so `k.bin`
is read as well. Reads from object storage get more than one stream here, so
the test failed in `Stateless tests (amd_tsan, s3 storage, targeted)`.

Pin the injection to 0 on that query only; the other queries keep it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant