Skip to content

Packed storage format for skip indices - #105321

Merged
Algunenano merged 36 commits into
ClickHouse:masterfrom
Algunenano:packed-skip-indices
Jun 18, 2026
Merged

Algunenano merged 36 commits into
ClickHouse:masterfrom
Algunenano:packed-skip-indices

Conversation

@Algunenano

@Algunenano Algunenano commented May 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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

Added an experimental MergeTree setting packed_skip_index_max_bytes that bundles small skip-index substreams into a single skp_idx.packed archive per part, reducing inode pressure when many skip indices are defined on a table. The decision is per substream at write time: substreams whose serialized size stays under the threshold go into the archive, anything larger keeps the standalone skp_idx_<name>.idx2 / .mrk2 layout. A single part can mix layouts. Full-text indices are not supported and are always per-file. Default is 0 (packing disabled).

Version info

  • Merged into: 26.6.1.999

Algunenano added 10 commits May 19, 2026 10:20
… archive

Two correctness fixes from review:

1. collectFilesToSkip was inserting only the logical "skp_idx_<name>.<ext>"
   form into files_to_skip. When the source part had per-file index files
   stored under a hash (replace_long_file_name_to_hash kicks in for long /
   case-insensitive names), the actual on-disk file name was the hash and
   the hardlink loop carried it into the new part. The new checksums.txt
   no longer references that file, so CHECK TABLE fails with
   UNEXPECTED_FILE_IN_DATA_PART. Mirror the resolution that the
   checksum-removal path already does (getStreamNameOrHash against source
   checksums) and insert both shapes into files_to_skip.

   This was also the source of intermittent failures of 04252 / 04254
   under randomized merge-tree settings.

2. filterPackedSkipIndicesArchiveTo (the drop-only archive rewrite) called
   finalize on the new skp_idx.packed write buffer but never sync'd it.
   With need_sync=true the mutation fsyncs other on-disk artifacts, so a
   crash between finalize and checksum publication could leave the new
   part referencing an archive whose contents weren't flushed. Thread the
   sync flag through and call sync after finalize.

Tests:
- Relax 04250 to drop the absolute files_delta assertion; random
  merge-tree settings (sparse serialization, compress_marks,
  enable_block_*_column, etc.) perturb sidecar file counts even between
  before/after of the same part. The packed-specific signals are kept
  (secondary_indices_compressed_bytes lt/gt/eq, EXPLAIN granules,
  CHECK TABLE).
- 04252 / 04254 switch from absolute system.parts.files counts to
  secondary_indices_compressed_bytes > 0 (works regardless of layout
  randomization).

Stress run: --test-runs 10 with default randomization, 70/70 pass.
Replaces the type-allowlist (packed_skip_index_types) with a per-substream
size threshold (packed_skip_index_max_bytes, default 0 = disabled). Each
skip-index substream's data and marks now flow through a new
SizeAdaptiveSpoolBuffer that accumulates in memory while it stays under
the threshold and, on the first nextImpl() that crosses it, spills into a
standalone data_part_storage->writeFile so subsequent bytes go straight
to the on-disk per-file substream. Substreams that finish under threshold
are committed into the part's skp_idx.packed at finalize.

A single part can therefore mix layouts: small minmax indices land in the
archive while a large bloom_filter on the same part keeps the legacy
per-file layout. The reader was already layout-agnostic per substream
(getDeserializedFormat probes checksums), so no reader-side change.

Data and marks of the same substream share a SizeAdaptiveSpoolCoordinator
so they always end up in the same layout (the reader can't satisfy
half-packed-half-per-file).

Other simplifications:
- Drops getSupportedPackedSkipIndexTypes / parsePackedSkipIndexTypes.
- Removes the type-list validator and the corresponding sanityCheck.
- Mutation archive_dirty logic loses its type-allowlist branches; it's
  now purely "source has a packed archive and we're touching a substream
  inside it".

Tests:
- All existing tests switch from packed_skip_index_types = '...' to
  packed_skip_index_max_bytes = 4194304 (or 0 for disabled).
- Granule-count assertions normalized to "filtered / no_filter / missing"
  (04250) or to a SQL "kept < total" check (04253/04254/04255) so they
  stay green under random merge-tree settings.
- New 04256_packed_skip_indices_layout_transitions walks one bloom_filter
  through packed -> spilled -> packed transitions via small inserts,
  OPTIMIZE FINAL, and ALTER DELETE.

Stress run: --test-runs 10 with default randomization, 80/80 pass.
Two related fixes from review:

1. archive_dirty in updateIndicesToRecalculateAndDrop was missing the case
   where the source part has skp_idx.packed AND a recalc'd index isn't
   inside it (e.g. the index used to be per-file because the threshold
   was lower, and is now over a higher threshold or vice versa). The
   writer in the new part would still create a fresh skp_idx.packed for
   the substreams that pack under the current setting, while the hardlink
   loop happily linked the source's skp_idx.packed -- writeFile then
   truncates the shared inode, both corrupting the source and dropping
   the surviving archive members from the new part.

   Reproduced with a small minmax (packed at threshold = 200) plus a
   per-file bloom_filter; after raising the threshold and ALTER UPDATE
   on the bloom_filter column, the source archive's inode was overwritten
   and the new part lost the minmax bytes.

   Fix: also mark archive_dirty whenever the source has skp_idx.packed and
   the mutation will run any skip-index aggregator under a non-zero
   packed_skip_index_max_bytes. This excludes the source archive from
   hardlinks and lets the existing preserve+preload mechanism carry the
   surviving in-archive substreams forward.

2. MutateAllPartColumnsTask's is_in_packed_archive lambda only probed
   ".idx" / ".idx2" base extensions. The partial-mutation detector uses
   IMergeTreeIndex::getSubstreams() so it also catches text-index side
   streams (.dct, .pst). Mirror that here -- otherwise a mixed-layout
   text index can be treated as not in the archive during a full rewrite
   and lose its packed side streams.

Test 04254 was rewritten to actually exercise the hazard from (1): it now
starts with packed_skip_index_max_bytes = 200 so the small minmax packs
while the bloom_filter spills to per-file, then raises the threshold and
ALTER UPDATEs the bloom_filter column. With the bug, the source's archive
gets truncated and m_v stops gating granules; with the fix, both indices
still filter and CHECK TABLE passes.

Stress: --test-runs 10 with default randomization, 80/80 pass.
Four review fixes:

1. Exclude text (full-text) indices from packing in the INSERT path.
   MergeTextIndexesTask, which handles their MERGE output, doesn't thread
   a PackedFilesWriter -- so packing on INSERT would only get un-packed by
   OPTIMIZE FINAL, leaving an inconsistent per-INSERT vs per-merge layout
   drift. Per-file in both paths is the consistent choice for the current
   experimental rollout; threading packing through the text-merge pipeline
   would be the proper long-term fix.

2. Skip-index reordering in ReadFromMergeTree sized packed substreams
   as 0 bytes because the checksums-only lookup misses (packed virtual
   files don't get individual checksum entries). Cost-based reordering
   then treated expensive packed indices as free. Fall back to the storage
   overlay (DataPartStorageOnDiskFull serves packed sizes from the archive
   index) when the checksums lookup misses.

3. cached_index_marks was emplaced under the on-disk hashed stream name
   during accumulation, but the reader looks up packed substreams' marks
   under the LOGICAL (unhashed) name -- packed substreams have no per-
   substream checksum entry that would let the reader's getStreamNameOrHash
   pick the hashed form. Long-name + packed substreams therefore missed
   their prewarmed marks. Re-key the cached_index_marks entry at finalize
   when isPacked() and on-disk != logical.

4. Setting doc was misleading: it claimed the threshold was "uncompressed"
   bytes, but SizeAdaptiveSpoolBuffer sits below the compression/hashing
   chain so the threshold actually applies to serialized on-disk bytes.
   It also understated the worst-case memory (data and marks each buffer
   up to the threshold per substream). Doc updated to match implementation
   and to note text-index exclusion.

Tests:
- 04257_packed_skip_indices_text_excluded: text index materialized in
  both INSERT and merged parts, DROP INDEX removes all skip-index bytes
  (would fail if a stray skp_idx.packed lingered after DROP).
- 04258_packed_skip_indices_long_name_prewarm: long-name minmax with
  prewarm_mark_cache = 1; merged part must keep the index filtering and
  CHECK TABLE.

Stress: --test-runs 10 with default randomization, 100/100 pass.
…mments

Drop the rollout / merge-pipeline narrative from the setting doc and the
in-code comments. Full-text indices are not supported by
packed_skip_index_max_bytes and are never packed; that's all the reader
needs to know.
- Use DBMS_DEFAULT_BUFFER_SIZE instead of a hardcoded 4096 for the two
  skp_idx.packed writeFile call sites; the archive is typically larger
  than 4 KiB and the small buffer just multiplied syscalls for no reason.
- Invert the parallelSyncFiles loop's `if (isPacked()) continue;` into a
  positive `if (!isPacked()) push_back(...)` so the loop body reads as
  "sync the non-packed streams".
- Allman-style braces on the two lambdas I added (initSkipIndices' text-
  exclusion comment site and openStreamFile's open_per_file).
- Drop the unused ErrorCodes::NOT_IMPLEMENTED extern in MutateTask.cpp.
- Rename `dropped_archive_file_names` / `preserved_archive_file_names`
  to `dropped_skip_index_archive_file_names` /
  `preserved_skip_index_archive_file_names` so it's clear which archive
  they refer to (the skip-index one, not statistics.packed).
- Reword the "drop the inherited skp_idx.packed checksum" comment: the
  point is that the inherited entry may reference a file the new part
  no longer has, not that CHECK TABLE flags it.
- Replace the `if (!packed_writer) promoteToPerFile()` fallback in
  SizeAdaptiveSpoolBuffer::commitToPackedIfNeeded with a LOGICAL_ERROR
  throw: the call path guarantees a writer.
- Collapse the `shared_ptr<SizeAdaptiveSpoolCoordinator>` (struct holding
  one bool) into a plain `bool` owned by MergeTreeWriterStream, and pass
  a non-owning pointer to both peer SizeAdaptiveSpoolBuffers.

Stress: --test-runs 10 with default randomization, 100/100 pass.
- 04249: add EXPLAIN indexes = 1 asserts for both Wide and Compact:
  in-range predicate must drop some granules ("kept < total"),
  out-of-range predicate must drop ALL granules ("kept == 0"). Add a
  Compact merge variant alongside the existing Wide one so both layouts
  exercise the post-merge archive read path.

- 04250: document the inputs of run_scenario.

- All tests: switch the threshold literal from 4194304 to '1M'. ClickHouse
  setting parsers accept human-readable size suffixes; '1M' = 1 MiB. The
  intentional outliers stay as numbers: 04254 keeps 200 (forces bf_w to
  spill) and 04256 keeps 4096 (drives the packed -> spilled -> packed
  transition).
The setting-flip scenarios asserted only that the index was materialized
(secondary_indices_compressed_bytes > 0) and that count() matched. Add an
EXPLAIN indexes = 1 check at the post-merge point of each scenario, plus
at the post-mutation point of the flip + ALTER UPDATE regressions, so we
also confirm the index actually drops granules under the new layout.
Random merge-tree settings move the absolute kept/total numbers around,
so the assertion is the qualitative "kept < total".

Also update the section comments to describe the threshold change in
terms of the current setting (0 vs 1 MiB) rather than the obsolete
"minmax" type-allowlist value.
Add packed_skip_index_max_bytes to clickhouse-test's
MergeTreeSettingsRandomizer (0 / 100B / 1KiB / 1MiB / 10MiB) so the
size-adaptive write path gets covered by every test run touching skip
indices.

Sweep of 246 stateless tests using skip indices found three that pin
absolute, layout-dependent quantities and would flake under the
randomizer; for each, pin packed_skip_index_max_bytes = 0 in the
table's SETTINGS clause and explain why in a comment:

- 01344_min_bytes_to_use_mmap_io_index: counts read-buffer mmaps on
  per-file index substreams; packed routes those bytes through the
  archive's read path so the buffer count differs.
- 02028_system_data_skipping_indices_size: asserts per-substream
  absolute byte sizes in system.data_skipping_indices; packed
  substreams are bundled into one archive file so the size accounting
  is layout-dependent.
- 03175_sparse_and_skip_index: predicate
  secondary_indices_uncompressed_bytes > 200 assumes per-substream
  uncompressed accounting, which doesn't apply cleanly to packed
  substreams.

A fourth test (03629_storage_s3_disallow_index_alter) also failed but
for an unrelated reason (missing s3_conn named collection in this
environment).
@clickhouse-gh

clickhouse-gh Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec080e6]

Summary: ✅


AI Review

Summary

This PR adds experimental packed storage for small MergeTree skip-index substreams in skp_idx.packed, including writer, reader, mutation, size-accounting, and regression-test coverage. The current code addresses the earlier archive rewrite, hardlink, vertical merge, text-index exclusion, and test-coverage concerns I checked, but one compatibility invariant remains unresolved: packed parts must fail closed for binaries that do not understand the layout, otherwise an old binary can preserve stale packed index bytes through a mutation and a later upgrade can use them for pruning.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeSettings.cpp:1926] [dismissed by author -- https://github.com/Packed storage format for skip indices #105321#discussion_r3434371440] packed_skip_index_max_bytes can create skp_idx.packed parts without persisting an old-code-visible incompatibility marker when the nonzero value comes from server-level <merge_tree> defaults. An older binary can load such a table, fail to see any per-index skp_idx_<name>.idx2 / .mrk2 files, skip recomputing the affected skip index during a mutation that changes indexed data, and hardlink or inherit the stale skp_idx.packed; after upgrading again, the new reader can use stale skip-index data for pruning, which can return wrong results. I still consider this real because the current code marks the setting EXPERIMENTAL, but does not force an explicit table setting or part-format marker that old binaries reject on the server-default path.
    Suggested fix: make every part/table that can write skp_idx.packed fail closed on old binaries, for example by persisting an explicit incompatible table setting or part-format marker before packed parts can be produced from an effective server default.
Final Verdict

Status: ❌ Block

Minimum required action: add a fail-closed compatibility marker for skp_idx.packed parts, including the server-default packed_skip_index_max_bytes path, so old binaries cannot silently mutate packed parts while ignoring the packed skip-index layout.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label May 19, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
- Drop the `= nullptr` default for the new IDataPartStorage * storage
  parameter on getDeserializedFormat. clang-tidy's google-default-arguments
  flags default arguments on virtual methods, and every caller already
  passes storage explicitly. Removes the corresponding stale NOLINT on the
  MinMax override.
- Settings history entry called the threshold "uncompressed size"; the
  setting doc was updated earlier to "serialized on-disk bytes". Align
  the history text with it.
…cesSerialization

The outer index `i` is unused; range-iterate over `skip_indices_streams` directly.
…rge writers

In a vertical merge, the horizontal MergedBlockOutputStream and each per-column
MergedColumnOnlyOutputStream both constructed their own PackedFilesWriter and
both wrote skp_idx.packed to disk. The horizontal writer finalizes last and
silently overwrites the vertical writer's archive, dropping every per-column
substream that should have been packed (data, not just accounting -- the index
is unusable).

Plumb a borrowed PackedFilesWriter through MergeTreeWriterSettings so the
vertical-merge per-column writer contributes packed substreams to the
horizontal writer's archive instead of racing on the file. Only the owner
finalizes skp_idx.packed on disk; the size-based per-substream packing
decision is preserved end to end.
CI's flaky check (25 reruns) hit "> 180s" because each iteration ran ~80
clickhouse-client invocations to set up and probe 10 mutation scenarios.

Reduce INSERT sizes 10000 -> 2000 (still gives multiple granules so the
"kept < total" assertion holds), batch each scenario's DROP + CREATE + INSERT
into a single --multiquery, and batch the four post-mutation reads (state,
count, EXPLAIN, CHECK TABLE) into one --multiquery using awk to split the
result blocks. Restore the final-cleanup DROP as a single multi-table
statement.

Per-iteration: 5.25s -> 2.12s. Flaky-check budget: 25 * 2.12 ~= 53s.
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Algunenano and others added 8 commits May 20, 2026 13:57
…ations

writer_can_open_archive treated a text-index recalc as if it could touch
skp_idx.packed, which forced the mutation to drop the inherited archive
checksum and reread+rewrite the archive unchanged via the preload path.
Text indices are excluded from packing (see initSkipIndices), so a
text-only recalc cannot produce a packed substream and the source archive
can be hardlinked.
…re commit

MergedBlockOutputStream::finalizePartAsync calls
calculateColumnsAndSecondaryIndicesSizesOnDisk between the writer's
fillSkipIndicesChecksums (which only preFinalizes skp_idx.packed) and
the actual finalize that happens later in the Finalizer. On local disks
preFinalize is enough for IDisk::existsFile to find the archive; on
object-storage disks the file is not visible until the underlying
multipart upload completes, so the existsFile overlay returns false and
the per-part secondary_indices_compressed_bytes / data_skipping_indices
sizes cache zero forever.

After writing the archive, hand the in-memory PackedFilesIO::Index from
PackedFilesWriter::finalize to the storage object via
seedSkipIndicesPackedReader. getSkipIndicesPackedReader returns the
seeded reader, so existsFile / getFileSize answer queries about packed
substreams from the in-memory index without touching the not-yet-
committed archive file. The on-disk reader is reseeded on rename; the
seed is dropped at that point so subsequent reads of the committed part
go through the normal disk-probe path.
03623 asserts an absolute data_uncompressed_bytes (~107M) for a
set(100000) skip index and uses it to gate distributed-index-analysis
activation against a 10M threshold. With packing enabled, the overlay
exposes the archive's per-substream compressed size (~4.5M) instead,
which falls below the activation threshold and flips both assertions.
Pin packed_skip_index_max_bytes=0 on the affected table so the
index always lives in its own per-file substream and the assertion stays
layout-independent.
…be to override

Two minor refactors that keep the public PR aligned with private-side
plumbing for packed-part storage (DataPartStorageOnDiskPacked), where
skp_idx.packed lives as a virtual file inside data.packed and the
default disk-based probe in getSkipIndicesPackedReader can't see it:

* Move looksLikePackedSkipIndexFile from an anonymous namespace in
  DataPartStorageOnDiskFull.cpp to MergeTreeIndicesSerialization.h next
  to SKIP_INDEX_FILE_PREFIX / SKIP_INDICES_PACKED_FILENAME so other
  storage backends (notably packed-part storage in private) can share
  the same prefix check without duplicating it.

* Mark DataPartStorageOnDiskBase::getSkipIndicesPackedReader virtual so
  the packed-part subclass can override the probe path. Public behaviour
  is unchanged: full storage still uses the default implementation,
  which does a disk->existsFile against the part-relative path and
  constructs a PackedFilesReader from there.

Verified by running the new packed-skip-indices tests (04249-04258) and
a sample of pre-existing skip-index tests on a zero-config public build
with --no-random-settings: 131/132 OK. The single failure is
00837_minmax_index_replicated_zookeeper_long which requires ZooKeeper
that isn't available in zero-config.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
copyPackedSkipIndicesFilesInto and filterPackedSkipIndicesArchiveTo
previously called source_archive->readFile(name, ...) directly.
Equivalent on full storage (the existing looksLikePackedSkipIndexFile
overlay in DataPartStorageOnDiskFull::readFile ends up calling the
same archive reader), but a storage subclass where skp_idx.packed
isn't a flat disk file would need readFile to compose the read
differently. Going through the virtual readFile entry point keeps
both helpers subclass-friendly without changing public behaviour.

No-op on the public surface; this mirrors a private-side fix to avoid
long-lived diffs between public and private on a hot file.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Algunenano and others added 2 commits June 17, 2026 11:08
`filterPackedSkipIndicesArchiveTo` (the `DROP INDEX` drop-only path, no
writer pipeline) rewrites `skp_idx.packed` into the new part but never
seeded the new storage's `PackedFilesReader`, unlike the symmetric writer
path `fillSkipIndicesChecksums`.

On object-storage disks with a non-fake transaction (Keeper metadata, as
ClickHouse Cloud uses) the rewritten archive's metadata is not committed
until the part transaction commits, which happens after `finalizeMutatedPart`.
With `columns_and_secondary_indices_sizes_lazy_calculation = 0` the per-part
secondary-index size accounting runs inside `finalizeMutatedPart`, before
that commit; `getSkipIndicesPackedReader` then probes the disk, misses the
not-yet-committed archive, caches `nullptr`, and the surviving packed index's
size is latched at zero in `system.data_skipping_indices` and
`system.parts.secondary_indices_compressed_bytes`.

Query results and granule filtering are unaffected: `rename` drops the
cached reader before the part becomes queryable, so query-time reads
re-probe the committed archive. The defect is the reported size (and, via
`data_uncompressed`, `distributed_index_analysis` activation).

Fix: keep the `PackedFilesIO::Index` returned by `writer.finalize` and seed
`new_storage` when it is a `DataPartStorageOnDiskBase`, matching the writer
path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Algunenano and others added 2 commits June 17, 2026 15:05
Companion to the DROP INDEX rewrite fix. When a mutation leaves `skp_idx.packed`
unchanged it is hardlinked into the new part rather than rewritten
(`collectFilesToSkip` excludes the archive only when
`packed_skip_index_archive_dirty`), so `filterPackedSkipIndicesArchiveTo` never
runs and the new storage's reader is not seeded.

On object-storage disks with a non-fake transaction (Keeper metadata) the
hardlink isn't committed until the part transaction commits, after
`finalizeMutatedPart`. With `columns_and_secondary_indices_sizes_lazy_calculation = 0`
the eager size accounting runs before that commit, probes the disk, misses the
not-yet-visible hardlink, caches `nullptr`, and the surviving packed index's size
is latched at zero (e.g. `ALTER UPDATE` of a non-indexed column).

Seed the new storage's reader from the source archive index in the
hardlink/copy path via the new `seedSkipIndicesPackedReaderFrom`, mirroring
`filterPackedSkipIndicesArchiveTo` and `fillSkipIndicesChecksums`. The hardlink
shares the source's bytes, so the source's index applies verbatim.

Extends the `04341` regression test with the hardlinked-archive case.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MutateTask.cpp
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This change introduces an optional packed skip-index archive (skp_idx.packed) plus the storage/mutation/merge plumbing to read and rewrite it; the controlling setting defaults to off, so behavior is unchanged unless packing is explicitly enabled, and the query-time cost code only runs when a table has skip indices. The flagged ClickBench and TPC-H queries are plain scans/aggregations with no skip indices, so this change cannot plausibly speed them up. All seven flagged items are improvements moving together across two benchmarks, which is consistent with a baseline shift between the two builds rather than a real effect of this change. We downgraded all seven to not-sure.

clickbench

⚠️ 5 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 264 212 -19.5% <0.0001 ClickBench hits has no skip indices and packing is off by default; query path untouched, delta is baseline variance
⚠️ 15 not_sure 246 201 -18.3% <0.0001 No skip indices exercised here; PR only touches packed skip-index storage (off by default), so this improvement is unrel
⚠️ 22 not_sure 334 237 -29.0% <0.0001 Very noisy underlying measurements (wide spread) and no skip-index path touched; improvement is run-to-run variance
⚠️ 23 not_sure 297 193 -35.0% <0.0001 Large delta but on a scan with no skip indices; off-by-default packing cannot touch this path, so baseline shift
⚠️ 34 not_sure 1486 1393 -6.3% <0.0001 Small delta on a query that uses no skip indices; PR's storage feature is off by default, unrelated

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 7 not_sure 113 72 -36.3% <0.0001 Query is intrinsically flaky and exercises no packed skip-index path; improvement is variance, not this PR
⚠️ 20 not_sure 248 120 -51.6% <0.0001 Noisy history and very wide measurement spread; no skip-index path touched, so this large drop is variance

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
  • StressHouse run: 8f7f376d-0753-4550-9acd-9959596c451a
  • MIRAI run: b5ac4dd2-e8c0-43e0-b5ae-2ff0f9606631
  • PR check IDs:
    • clickbench_27534_1781787155
    • clickbench_27547_1781787155
    • clickbench_27553_1781787155
    • tpch_adapted_1_official_27561_1781787155
    • tpch_adapted_1_official_27577_1781787155
    • tpch_adapted_1_official_27587_1781787155

The packed-substream fallback in calculateSecondaryIndicesSizesOnDisk
issues existsFile / getFileSize through the storage overlay. In the
metadata-in-Keeper configuration this reaches Keeper, and
Coordination::pushRequest aborts with a logical error when no current
component is set for the scope. Reading system.parts (which computes
secondary index sizes) crashed the server in debug builds.

Set the component like the other Keeper-touching paths in this class
(removeIndexMarksFromCache, getSkipIndicesPackedReader, etc.).
04250_packed_skip_indices_mutations: each scenario now runs in a single
client invocation (create + mutate + read back) instead of three-plus,
because client process startup dominates on sanitizer builds where the
test was timing out. Results are labelled (tag<TAB>value rows and
@check / @Explain markers) and picked out by label rather than by
position, which is easier to read and debug.

04256_packed_skip_indices_layout_transitions: assert the packed -> spilled
-> packed layout transition via system.parts.files instead of relying on
secondary_indices_compressed_bytes > 0, which is true in both layouts.
The file count is recorded per phase in a side table and compared between
same-lineage parts (spilled merged part has more files than the packed
merged part; the repacked part has fewer than the spilled one), so the
assertions stay stable under randomized merge-tree settings.
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Address three review comments on the packed skip indices PR:

- Add 04356_packed_skip_indices_vertical_merge: force MergeAlgorithm::Vertical
  (low vertical_merge_algorithm_min_* thresholds, asserted via system.part_log)
  with packed minmax indices on the gathered columns, then verify both indices
  still prune granules and CHECK TABLE succeeds. This covers the vertical-merge
  borrowed-PackedFilesWriter handoff, which the existing tests did not exercise.

- Force Compact parts in the Compact scenarios of 04249, 04250 and 04252 by
  pinning min_bytes_for_wide_part / min_rows_for_wide_part (and asserting
  part_type where practical). Under --random-merge-tree-settings these could
  silently run as Wide, so the Compact path went untested.

- Make scenarios D, E and G of 04250 actually mixed-layout: a large set index
  over high-cardinality strings spills to a standalone per-file substream while
  the minmax stays packed. The new set_index_layout assertion fails if the set
  is packed instead, so the per-file update/drop paths are really exercised.
The style check forbids the global SYSTEM FLUSH LOGS in tests; flush only
the part_log table the test reads.
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.30% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.50% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 614/666 (92.19%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@Algunenano

Copy link
Copy Markdown
Member Author

The PR has been green multiple times and the AI reviewers are happy. If you find something in the post-review please let me know and I'll address it, but I'd rather merge this and not have to deal with conflicts multiple times again. Also, it's experimental so I want to have it in 26.6 and enable it in the next release

@Algunenano
Algunenano added this pull request to the merge queue Jun 18, 2026
Merged via the queue into ClickHouse:master with commit 8e5a2d5 Jun 18, 2026
166 checks passed
@Algunenano
Algunenano deleted the packed-skip-indices branch June 18, 2026 18:10
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 18, 2026
Comment on lines +56 to 61
if (looksLikePackedSkipIndexFile(name))
{
if (const auto * reader = getSkipIndicesPackedReader(); reader && reader->exists(name))
return true;
}
return volume->getDisk()->existsFile(fs::path(root_path) / part_dir / name);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the heads up. I'll fix it

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Algunenano added a commit to Algunenano/ClickHouse that referenced this pull request Jun 20, 2026
existsFile/getFileSize for a packed skip-index file open skp_idx.packed via
getSkipIndicesPackedReader. On shared storage another replica can remove the
archive between the existence check and the open, so the read throws NO_SUCH_KEY
and existsFile propagates it (and the error is counted as a DiskS3NoSuchKeyError,
which fails stress tests). Wrap the open in Expect404ResponseScope (so the 404 is
not logged/accounted) and treat NO_SUCH_KEY as 'no archive present'.

Reported in review of ClickHouse#105321.
alexey-milovidov added a commit to azat/ClickHouse that referenced this pull request Jun 22, 2026
Resolve conflict in `MergeTreeDataSelectExecutor.cpp`: master added the
`partHasStaleTopKIndex` helper (from the top-k granule skip index work,
ClickHouse#105321) immediately before `filterPartsByPrimaryKeyAndSkipIndexes`, the same
location where this branch added `toExplainSearchAlgorithm` (the EXPLAIN
search-algorithm helper). The two functions are independent; keep both.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@alesapin alesapin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've accidentally noticed this change (was working on a new part format). The code here is not well structured. Knowledge about packed format for skip indices is introduced in almost every class related to merge tree. Somehow, even Read step from MergeTree and optimizations had to be changed to support new format of serialization for skip indices. Some abstraction (similar to IDataPartStorage) for indices serialization is missing here. That is why methods and functions like looksLikePackedSkipIndexFile or isPacked or if (skip_indices_packed_writer are everywhere, breaking a lot of abstractions.

For some reason we even support packed indexes in packed parts. What's the point to have this redundant indirection?

Very similar change was done with much less damage: #93414.

While idea is very good and useful, I would say this change is better to be reverted and reimplemented from scratch.

@Algunenano

Copy link
Copy Markdown
Member Author

For some reason we even support packed indexes in packed parts. What's the point to have this redundant indirection?

Full explanation is here: https://github.com/ClickHouse/clickhouse-private/issues/58264#issuecomment-4506869050

I've accidentally noticed this change (was working on a new part format). The code here is not well structured. Knowledge about packed format for skip indices is introduced in almost every class related to merge tree. Somehow, even Read step from MergeTree and optimizations had to be changed to support new format of serialization for skip indices. Some abstraction (similar to IDataPartStorage) for indices serialization is missing here. That is why methods and functions like looksLikePackedSkipIndexFile or isPacked or if (skip_indices_packed_writer are everywhere, breaking a lot of abstractions.

Very similar change was done with much less damage: #93414.

There are some key differences between the 2.

Namely that packed statistics is all or nothing in a part, while packed indices is supported per substream in order to differentiate between large and small indices and be able to work with both.

Also, there are tons of existing code working with indices. Skip indices are enumerated, hardlinked, checksummed, etc. in many places from existed code. Statistics is just read by the estimator.

While idea is very good and useful, I would say this change is better to be reverted and reimplemented from scratch.

I'll work on a followup to simplify this design, although it will require a major refactor of existing code similar to the one that introduced the packed format for indices. Do you mind if I ask for a review from you once it's ready?

Comment on lines +2713 to +2725
/// data_uncompressed is approximated as compressed size for packed substreams:
/// the archive's per-virtual-file index records only the on-disk (compressed)
/// size, and the uncompressed count is lost once `MergeTreeWriterStream` is
/// destroyed. The undercount matters in one place behaviorally:
/// `ReadFromMergeTree::get_indexes_size` gates `distributed_index_analysis`
/// activation on `data_uncompressed`, so a packed skip index that compresses
/// well (`set` / `bloom_filter` over strings) may not cross
/// `distributed_index_analysis_min_indexes_bytes_to_activate` and distributed
/// index analysis won't trigger. The fallback is the normal query plan, not
/// a wrong result. Elsewhere `data_uncompressed` only feeds telemetry in
/// `system.data_skipping_indices` / `system.parts`. To remove this
/// approximation entirely, add `uncompressed_size` to
/// `PackedFilesIO::Index` entries and bump the archive format version.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Algunenano just having "correct plan" is not enough - since it will do incorrect assumptions which may just not activate distributed index analysis
It is OK for now I guess, since it is experimental for now, but we need proper uncompressed_size.
Are you planing to work on this?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How critical is it? The index won't be packed if it's larger than packed_skip_index_max_bytes. The initial idea that I had once I remove it from experimental is 4MB (and text indices are always unpacked because they use a different mechanism). Would it make a difference if it says 1MB and not 2MB to decide on distributed analysis? For reference distributed_index_analysis_min_indexes_bytes_to_activate is 1GB

I can try to get the size from other metrics (if loaded from memory for example) to provide a better number if it's critical.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting. Thanks for the heads up. I think this should cover it: #109272

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

Labels

pr-experimental Experimental Feature 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.

7 participants