Skip to content

Enable packed skip indexes and sparsity-based trivial count by default - #111816

Merged
Algunenano merged 9 commits into
ClickHouse:masterfrom
Algunenano:promote-sparsity-and-packed-index-settings
Aug 4, 2026
Merged

Algunenano merged 9 commits into
ClickHouse:masterfrom
Algunenano:promote-sparsity-and-packed-index-settings

Conversation

@Algunenano

@Algunenano Algunenano commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Promotes three settings from experimental to beta and enables them by default:

  • packed_skip_index_max_bytes (MergeTree): 0 → 1 MiB. Skip-index substreams whose serialized on-disk size stays at or below 1 MiB are bundled into a single skp_idx.packed archive per part instead of one skp_idx_<name>.idx2 / .mrk2 pair each. Measured on 26.8: a minmax index costs 50-200 KiB per 100M rows (marks 10-30 KiB), so 1 MiB packs minmax/set indices for parts up to roughly half a billion rows even with incompressible values, while bloom filters (~1 MiB per 1M rows) keep the standalone layout on anything but the smallest parts. On object storage every packed substream saves 2 PUT requests per part written and reduces object count; reads below ~2-4 MiB are request-latency-bound (cf. reader_executor_min_bytes_for_seek, remote_read_min_bytes_for_seek), so nothing that benefits from being its own object is packed. Keeping the threshold at 1 MiB also bounds write-time buffering and the archive rewrite amplification on mutations.

  • compute_exact_num_defaults_for_sparse_columns (MergeTree) and optimize_trivial_count_with_sparsity_filter (query-level): with exact per-column num_defaults counters persisted at insert/merge time, SELECT count() FROM t WHERE <pred> is served directly from serialization.json when <pred> partitions rows into defaults vs non-defaults, with no data scan.

Closes #81043

Changelog category (leave one):

  • Performance Improvement

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

Enabled by default (and promoted to beta) two on-disk features: 1) packed_skip_index_max_bytes = '1M': skip-index substreams up to 1 MiB are now written into a single skp_idx.packed archive per part, reducing object count and write requests on object storage. Compatibility: only newly written parts are affected and they stay fully readable on older versions; versions before 26.6 simply do not use the packed indices for pruning (they are treated as not materialized). Set packed_skip_index_max_bytes = 0 to keep the standalone per-file layout. 2) compute_exact_num_defaults_for_sparse_columns plus optimize_trivial_count_with_sparsity_filter: exact per-column num_defaults counters are persisted and used to answer SELECT count() FROM t WHERE <pred> without a data scan when the predicate splits rows into defaults vs non-defaults. Compatibility: the exact_num_defaults flag in serialization.json is ignored by older versions, so parts remain fully readable after a downgrade; the count rewrite only applies to parts that carry exact counters, so results stay correct on tables with mixed parts.

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d277c9c]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
ThreadSanitizer: data race (STID: 2377-33f2) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR enables packed_skip_index_max_bytes, compute_exact_num_defaults_for_sparse_columns, and optimize_trivial_count_with_sparsity_filter by default, updates their compatibility history, and fixes the ENAMETOOLONG existence probe in DiskLocal. The DiskLocal fix looks correct in the current code, but the new MergeTree compatibility rollback path is incomplete, and the default-on sparse-defaults change still lacks convincing evidence that it does not regress ordinary reads.

Findings

⚠️ Majors

  • [src/Core/SettingsChangesHistory.cpp:1344] The new MergeTree compatibility rows do not reliably restore the 26.7 defaults in a long-lived session. registerStorageMergeTree.cpp seeds new tables from Context::getMergeTreeSettings / getReplicatedMergeTreeSettings, those helpers cache a computed MergeTreeSettings object after applying the then-current compatibility, and Context::setSetting('compatibility', ...) never invalidates either cache. After any prior MergeTree access in the same session, a later SET compatibility = '26.7' can still create a new MergeTree table with the 26.8 defaults. Suggested fix: clear the cached merge-tree settings when compatibility changes and add a focused regression test that warms the cache before the downgraded CREATE TABLE.
  • [dismissed by author -- https://github.com/Enable packed skip indexes and sparsity-based trivial count by default #111816#discussion_r3659060698] [src/Storages/MergeTree/MergeTreeSettings.cpp:205] Enabling compute_exact_num_defaults_for_sparse_columns changes the sparse-vs-dense layout of newly written and merged parts, and the only performance evidence linked on the PR is still the Cloud report showing four clickbench regressions on queries that do not use the trivial-count rewrite. The current code still makes this layout change default-on without a targeted before/after benchmark that rules those regressions out, so the Performance Improvement contract remains unproven.
Final Verdict

⚠️ Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 70/71 (98.59%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 24, 2026
Enabling optimize_trivial_count_with_sparsity_filter by default makes
count(*) with a default-vs-non-default predicate be served from the
persisted num_defaults counter, bypassing the data scan / primary-key
analysis these tests rely on:

- 00933: SELECT count() WHERE n > 0 (n's default is 0) no longer reads
  data, so UncompressedCacheHits drops to 0.
- 04327: value = '' / value != '' on a String column (default '') no
  longer touch the primary key, so EXPLAIN emits no Condition line.

Pin the setting to 0 in both so they keep testing their intended paths.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d1a9b94f-1b9a-4b10-ba0f-82b0a8a0d5ed
  • MIRAI run: 730dea89-c323-4469-b7c2-5fe483d349e5
  • PR check IDs:
    • clickbench_1646975_1785852257
    • clickbench_1646981_1785852257
    • clickbench_1646987_1785852257
    • tpch_adapted_1_official_1647003_1785852258
    • tpch_adapted_1_official_1647016_1785852257
    • tpch_adapted_1_official_1647581_1785852356

@Algunenano
Algunenano marked this pull request as draft July 27, 2026 15:38
`packed_skip_index_max_bytes` bundles a small skip index into a single
`skp_idx.packed` archive instead of a `.idx2` / `.mrk2` pair, so a part
holding one skip index now has one file less. Account for that in the
blob counts of `test_merge_tree_s3` and `test_replicated_merge_tree_s3`,
and keep the per-file layout in the escaping test of
`test_alter_settings_or_comment_on_cluster`, which observes the index
filename on disk.

`compute_exact_num_defaults_for_sparse_columns` adds
`"exact_num_defaults": true` to `serialization.json`, growing a part by
26 bytes. That pushed `test_max_suspicious_broken_parts` over its
1000-byte limit, which was already only 16 bytes above one part.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 82.30% 86.30% +4.00%
Functions 91.70% 92.00% +0.30%
Branches 74.40% 78.50% +4.10%

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

Full report · Diff report

Algunenano and others added 2 commits July 31, 2026 13:09
Packed skip indices probe for legacy extensions (e.g. `.idx` after
migrating to `.idx2`) using the unhashed, escaped logical file name.
When that name exceeds the filesystem's NAME_MAX (long non-ASCII index
names), the stat call fails with ENAMETOOLONG, and `DiskLocal::existsFile`
was using the throwing `fs::is_regular_file` overload, turning a normal
existence check into an uncaught `filesystem_error`. Use the
`std::error_code` overloads instead so any stat error is treated as
"does not exist", matching how callers use these functions.

Found via ClickHouse#111816 CI:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111816&sha=81c8a821e32b344cc7bfb4e7a16dc04e9ca0d2eb&name_0=PR&name_1=Fast%20test
Comment thread src/Disks/DiskLocal.cpp Resolved
The previous commit swallowed every stat() error in existsFile /
existsFileOrDirectory / existsDirectory, treating EACCES / EIO / ESTALE
on genuinely existing files the same as "missing". Several callers use
"missing" to trigger metadata fallback (e.g.
MergeTreeData::loadFormatVersion, IMergeTreeDataPart::loadColumns), so
that turned real disk errors into silent metadata resets instead of an
exception.

Only std::errc::filename_too_long is now caught and treated as "doesn't
exist"; every other filesystem_error still propagates as before.

Per PR review: ClickHouse#111816 (comment)
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@Algunenano
Algunenano marked this pull request as ready for review August 4, 2026 08:22
@Algunenano
Algunenano added this pull request to the merge queue Aug 4, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 4, 2026
@Algunenano
Algunenano added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit df87fd7 Aug 4, 2026
178 of 180 checks passed
@Algunenano
Algunenano deleted the promote-sparsity-and-packed-index-settings branch August 4, 2026 16:36
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 4, 2026
alexey-milovidov pushed a commit that referenced this pull request Aug 5, 2026
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113396&sha=94a3032a6add32ebbe5d21188606ad0bc9ce35fd&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29

- Since #111816 a small skip index goes into a single `skp_idx.packed`
  archive instead of an `.idx2` + `.cmrk2` pair, so a part holds one
  file less. Mirror the `FILES_SAVED_BY_PACKED_SKIP_INDEX` adjustment
  from `test_merge_tree_s3` (verified against the current master binary
  on a `local_blob_storage` disk: wide part = 16 objects, compact = 12,
  plus `format_version.txt`).

- In `test_url_reconnect`, heal the network only after the client
  demonstrably hit a connect timeout instead of after a fixed 4-second
  sleep. On a loaded runner the query reached its first connect attempt
  after the rule was already deleted, so nothing timed out and the
  expected log line never appeared. The log poll also subsumes the
  previous `contains_in_log` assertion.

Co-Authored-By: Claude Fable 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 8, 2026
Upstream ClickHouse#111816 made DiskLocal's three existence probes swallow ENAMETOOLONG and
return false instead of throwing. That removes the reason for this PR's second half:
the tolerance on the read, load, remove and backup paths caught a refusal that no
longer arrives, and the placeholder-projection state it protected against is no
longer reachable. It also made two of the four error-translation catches dead, since
both guarded a builder whose only filesystem touch is one of those probes.

So half of the diff goes back to master:

  - loadProjections and checkConsistencyBase in IMergeTreeDataPart
  - backupParts in MergeTreeData
  - remove in DataPartStorageOnDiskBase
  - isProjectionDirectoryProbeable and its two call sites in MutateTask
  - the builder-level catches in MergeTreeDataWriter and MergeTask
  - recoverFailedPath, isProjectionFilenameTooLongError and
    isInsideProjectionDirectory in ProjectionNameLength

The DDL check also moves to a better layer. It used to thread an is_fresh_definition
parameter through ProjectionDescription::getProjectionFromAST, which duplicated a
discriminator MergeTree already computes and put a policy decision in AST
construction. It now runs at the two MergeTree boundaries that own DDL input:
registerStorageMergeTree::create, which receives the normalized projection list so
CREATE TABLE AS is covered there too, and AlterCommand::apply for ADD PROJECTION.
getProjectionFromAST loses the parameter, and InterpreterCreateQuery.cpp and
ProjectionsDescription.{h,cpp} leave the diff entirely.

The CREATE boundary needs its own freshness flag rather than reusing the local the
allow_experimental_codecs gate uses. Replicated-database replay is already excluded
by the mode enum, since getLoadingStrictnessLevel returns SECONDARY_CREATE and the
guard is mode <= CREATE, but Shared Catalog secondaries are marked separately, via
is_shared_catalog_internal plus SharedDatabaseCatalog::isInitialQuery, and outside
the ZooKeeper metadata transaction. Reusing the codec gate's local verbatim would
have rejected legacy metadata during that replay and diverged the replicas.

ADD PROJECTION keeps duplicate handling where it already lives. A name that is
already present is ProjectionsDescription::add's business: a no-op under
IF NOT EXISTS, otherwise ILLEGAL_PROJECTION. Validating the length before that check
would turn the no-op into an error on exactly the legacy tables this change promises
to keep working, and would report "name too long" where "already exists" is the
right answer.

The runtime translation now attributes instead of matching errno alone. ENAMETOOLONG
covers a whole path over PATH_MAX as well as a component over NAME_MAX, so a server
with a deep data root used to be told its projection name was too long when a
ten-character name was at fault. The condition is NAME_MAX, not
maxProjectionNameLength(): callers pass the suffixed directory name, so a valid
214-byte name already exceeds the raw-name budget of 214 and would have been
misreported. One residual remains and is deliberate: the MergeTask catch wraps the
whole MergedBlockOutputStream constructor, which does more than create the
directory, so a long projection name combined with an unrelated deeper ENAMETOOLONG
can still be translated. Closing that would need the path-recovery helper this
commit deletes as dead.

Scope is bounded on purpose. The DDL check is pure string arithmetic and covers every
backend. The improved runtime message covers DiskLocal, the default disk. On
local_plain-family disks the probe still throws a bare fs::exists and
createDirectories is a metadata no-op with the real write in writeObject, outside the
retained catch, so those disks keep master's raw error at both ends.

The integration suite goes with the tolerance it pinned. Two of its cases now assert
master's own behaviour and cannot fail on this diff, and the third, that a legacy
over-long table stays readable, passes through upstream's path; it is kept as a
manual acceptance arm rather than a three-node cluster with two deep-path configs.
The stateless test gains the two IF NOT EXISTS and duplicate-precedence cases, and
its full-definition ATTACH case now uses the UUID form: the bare
ATTACH TABLE t (<definition>) form is rejected by an Atomic database with
INCORRECT_QUERY whatever the names are, so it never asserted the length check.

Co-Authored-By: Claude Opus 5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 3, 2026
…s on 26.6

Since ClickHouse#109272 the skip-index writer emits the `skp_idx.packed` archive in
format 1, which the 26.6 reader rejects with UNKNOWN_FORMAT_VERSION, so the
"stay fully readable on older versions" claim in the entry of ClickHouse#111816 is wrong.
The entry now names the operations that fail on 26.6 and the settings that
keep a rollback to 26.6 possible.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ClickBench Q1 analysis

2 participants