Skip to content

Do not open the value files of a sparse column for a wide-part range without values - #130699

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:sparse-wide-skip-values-without-rows
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:sparse-wide-skip-values-without-rows

Conversation

@groeneai

@groeneai groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130330
Related: #130692

Changelog category (leave one):

  • Performance Improvement

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

Reading a sparse column of a wide part no longer opens its value files for granules that contain only default values. SELECT * point lookups, top-N queries and scans of wide tables with many mostly-default columns are up to 20% faster and use less memory (a 1600-column point lookup: 29 MB instead of 293 MB). Closes #130330.

Description

A read of a sparse column of a wide part always called the nested deserialization of the values, even when the offsets say the range has none (analysis and patch by @ snelheidai). The wide reader then opened the value file, allocated a read buffer, positioned it and read nothing, also for the empty value files of an all-default column.

In a wide part, a range without values now only positions the value streams at the new mark through seek_stream_to_current_mark_callback (a continuous read leaves them where they are). An already open stream first gets the current read bound, as in getStream, because on object storage a seek past the old bound is clamped to it. MergeTreeReaderStream performs a seek requested before its buffer exists at the first getDataBuffer, after the read bound is set, so a stream that is only positioned is never opened. Compact parts, other formats and ranges with values keep the current path, and a prefetch still opens the streams it prefetches. A bad mark now reports ARGUMENT_OUT_OF_BOUND at the first read instead of at the seek.

Measured on master 94af6233 (release build, one wide part of 100,000 rows), a 400-column point lookup in a granule without values: FileOpen 902 -> 402, IOBufferAllocBytes 66 MB -> 0.5 MB, query memory 74 MB -> 6.4 MB, bytes read unchanged. The new performance test (1600 columns) with perf.py: point lookups -19%, top-10 -18%, full scans -22% and -11%, dense control -0.2%. 4218 deterministic query/table/setting combinations (local and S3 disks, read pools, prefetch, caches, mmap, PREWHERE, subcolumns, a mutation, a compact part) return the same results as master. The new stateless test fails without the positioning, without the deferred seek, and on S3 without the read bound update.

Creating no streams for an all-default column is the separate #130692.


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

groeneai and others added 3 commits November 11, 2026 02:10
…without values

Reading a sparse column of a wide part reads its offsets and then always
called the nested deserialization of the values, even when the offsets say
the range has none. The wide reader's getter then created the stream's read
buffer (stat, open, a max_read_buffer_size buffer), positioned it and read
nothing. A `SELECT *` point lookup on a wide table with many mostly-default
columns paid one open and one buffer per such column; for a column with only
defaults in the part its value files are empty and were still opened.

- SerializationSparse: in a wide part, a range without values does not call
  the nested deserialization. A read from a new mark only positions the value
  streams there through `seek_stream_to_current_mark_callback`, so that a later
  continuous read of the same column finds them where reading zero values
  would have left them. Compact parts and other formats keep the old path.
- MergeTreeReaderStream: a `seekToMarkAndColumn` on a stream whose buffer does
  not exist yet is recorded and performed at the first `getDataBuffer`, so a
  stream that is only positioned is never opened. `init` and `adjustRightMark`
  are unchanged, so a deferred seek still lands after the read bound is set;
  an eager seek clears a pending one.

Measured on master 94af623 (release build, one wide part of 100,000 rows,
400 columns, 3/4 UInt32 and 1/4 String): a point lookup in a granule without
values opens 402 files instead of 902 and allocates 0.5 MB of read buffers
instead of 66 MB; query memory 74 MB -> 6.4 MB (1600 columns: 293 -> 29 MB).
The number of bytes read is unchanged.

The value files are still opened by prefetching (which positions every stream
up front) and on every read of a range that has values, so only the useless
opens go away. The test reads a range that starts in a granule without values
and continues into one with values, and fails when either the positioning or
the deferred seek is dropped.

Closes ClickHouse#130330 (analysis and patch by @ snelheidai). The variant that creates no
streams at all for an all-default column touches `MergeTreeReaderWide` and is
left for a separate change.

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

The skip path for a sparse range without values positions the value
streams through `seek_stream_to_current_mark_callback`, which seeked
without the `adjustRightMark` that `getStream` does first. Readers are
reused across the read tasks of one part, so a value stream that read
values in an earlier task still had that task's read bound. On object
storage `AsynchronousBoundedReadBuffer` clamps a seek past the bound to
the bound, and the next read of the range decoded the values of an
earlier granule (`remote_filesystem_read_method = 'threadpool'`) or
failed with `ATTEMPT_TO_READ_AFTER_EOF` (`'read'`). It needs one-mark
read tasks and `remote_filesystem_read_prefetch = 0`: with prefetching,
every non-empty stream is bounded and positioned before each read.

Now an open stream gets the current read bound before it is positioned,
the order `getStream` uses. A stream that is not open yet keeps its
deferred seek, which runs after `getStream` sets the bound.

The test gets an S3 case: one-mark tasks read granules 0 to 3, skip a
granule with values, and read a granule whose first rows have none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
State why the read bound is set before the seek in seek_stream_to_current_mark_callback instead of restating the code.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 1 blocker fixed, 3 findings declined with evidence
Finding Verdict
❌ An already open value stream was positioned without the current read bound (on object storage such a seek is clamped to the old bound) AGREE, fixed in d7ec016: the open stream gets the read bound first, as in getStream; S3 case added to the test
⚠️ No counter assertion guards the gain DISAGREE: the performance test guards it
⚠️ The S3 test case does not pin remote_filesystem_read_method DISAGREE: without the fix it fails with both values (read: ATTEMPT_TO_READ_AFTER_EOF, threadpool: wrong values; 20/20 randomized runs)
💡 Dense control +7% in one interleaved local benchmark design DISAGREE: allocator carry-over between queries; equal allocator state gives -0.0%, perf.py -0.2%

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, by counters (this is a speed-up, not a wrong result). One wide part of 100,000 rows with 400 sparse columns, SELECT * FROM s400 WHERE k = 30000 SETTINGS max_threads = 1, load_marks_asynchronously = 0, local_filesystem_read_method = 'pread', use_uncompressed_cache = 0, warm mark cache: FileOpen 902 on master 94af6233, 402 with the change, every run.
b Root cause explained? SerializationSparse::deserializeBinaryBulkWithMultipleStreams called the nested deserialization for a range with 0 values. Its first step is the reader's getter, which creates the stream's read buffer (stat, open, allocation) and seeks it, and then nothing is read.
c Fix matches root cause? Yes. The range without values is detected where it is known (the sparse offsets) and the values are not read; MergeTreeReaderStream defers a seek on a stream without a buffer to its first getDataBuffer. An open stream gets the current read bound before it is positioned, as in getStream.
d Test intent preserved / new tests added? New 05616_sparse_wide_range_without_values (a read that starts in a granule without values and continues into one with values, on a local disk and on S3 after earlier one-mark tasks opened the value stream) and the performance test sparse_columns_wide_part_read.xml. No existing test changed.
e Both directions demonstrated? The new test fails 40/40 randomized runs when the positioning is removed and 40/40 when the deferred seek is dropped. Its S3 case fails 20/20 randomized runs when an open stream is positioned before its read bound is raised (wrong values with remote_filesystem_read_method = 'threadpool', ATTEMPT_TO_READ_AFTER_EOF with 'read'). It passes 50/50 with the change, and on master, which reads eagerly. Counters and perf.py timings are shown against master for the gain itself.
f Fix is general across code paths? Every caller of the changed seek was checked: wide and compact readers, skip index and text index readers, prefetch, whole-part reads (read_without_marks), the substreams cache, subcolumns of a sparse column. Streams reused across the read tasks of one part get the read bound before an eager seek, on every read pool (thread, in order) and read method. Compact parts and other formats keep the old path.
g Fix generalizes across inputs (params/datatypes/wrappers)? The differential covers sparse UInt32, String, Nullable(String) (allow_sparse), FixedString, Tuple elements; granularity 8192 and 64; two parts merged, a mutation, a compact control, local and S3 disks; prefetch, uncompressed and columns caches, pread, mmap, max_block_size = 97, one-mark tasks on S3 without prefetch with both read methods, read in order and 2 threads: 4218 deterministic combinations, all equal to master and to a dense twin.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format or on-disk change.
i Invariants and contracts preserved? A stream's position at its first data access is the position of the last seek requested before it, as if every seek had been eager; an eager seek clears a pending one. The read bound is raised before every seek, deferred or eager. After a range without values each value stream stands where reading zero values would leave it. A bad mark is reported at the first read of the stream instead of at the seek, with the same message.

Session id: cron:clickhouse-impl-slot-6:20261111-043400

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [06af739]

Summary: ✅


AI Review

Summary

Reviewed #130699 at 06af739b013b4e9c000b2c0012f8800fc4a524f4, including all prior discussion. The change avoids opening sparse value streams for empty ranges in wide parts while preserving stream positioning through deferred seeks and read-bound updates. No actionable findings. On the unchanged C++ revision, targeted ASan CI passed the new regression test 50/50 times; performance CI measured five sparse workloads 15.9–29.3% faster with a 0.3% change in the dense control. The latest commit only excludes this performance test from Iceberg configurations; current-head broader CI remains pending. No local tests were run because this checkout has no ClickHouse binary.

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 06af739b0 with master d011c6b84 (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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c5ee730

Every failure below has an owner: a fixing PR (mine or external), 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
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) / Insert historical data perf CI harness, the same signature in all six Iceberg jobs: this PR adds tests/performance/sparse_columns_wide_part_read.xml, so these jobs run only that test, no query of it is measured on both servers, and compare.sh stops before it writes report/all-query-metrics.tsv (FileNotFoundError, Errors while building the report.) #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 2/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 3/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 2/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 3/3) / Insert historical data same as the first row #129874 (mine, open)
PR praktika rollup of the rows above #129874 (mine, open)

The Config Workflow / Pre Hooks failure in CIDB comes from the run before the can be tested label was added. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261111-103006

The test measures reading sparse columns of a wide MergeTree part, which
Iceberg tables do not have. In the Iceberg performance comparison jobs its
queries fail with `Params with size 1 is not supported` (Code: 36), so no
query is measured on both servers and the report is not built.

`<test iceberg="0">` keeps the test out of the Iceberg configuration; the
skip list is not used because editing it runs the whole Iceberg suite.

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

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@clickhouse-gh clickhouse-gh Bot added comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

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.

Wide parts: sparse columns open value files that have nothing to read (wide SELECT * lookups -18% to -22%)

1 participant