Skip to content

Allow skip index pruning over unmaterialized lazy JSON type hints - #122846

Merged
Avogar merged 10 commits into
masterfrom
allow-skip-index-pruning-lazy-json-hints
Nov 4, 2026
Merged

Avogar merged 10 commits into
masterfrom
allow-skip-index-pruning-lazy-json-hints

Conversation

@Avogar

@Avogar Avogar commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

With enable_json_lazy_type_hints, ALTER MODIFY COLUMN j JSON(path Type) is metadata-only: existing wide parts keep the path on disk as Dynamic and cast it to the hinted type at read time, without a mutation. A skip index materialized over such a hinted subcolumn (for example j.a) builds its granules against the hinted type, but until now the read path refused to use it — the part's own column type (Dynamic) did not match the index's built-against type, so the staleness guards (isPartTypeCompatibleImpl, canUseIndex) treated the index as stale and silently disabled pruning. A user who adds a type hint lazily and then adds and materializes an index over it got no pruning at all.

This change records, per part, the type each index's required columns were built against, but only when it differs from the part's own declared type. It is kept in a new optional, checksummed file secondary_index_column_types.json, written by the mutation that (re)builds the index. The read-side staleness guards consult this record and use an index whose recorded built-against type matches the current metadata type, even though the column is still Dynamic on disk.

The record certifies the column type, not its values. A pending on-the-fly ALTER UPDATE still disables pruning: AlterConversions now tracks value_updated_columns separately from type changes, and canUseIndex rejects an index whose required column has a pending value update regardless of any recorded type override. The new file is additive and backport-safe — parts without it behave exactly as before, so a mismatched index is still refused; a required column the part does not physically carry is left unrecorded so its index is refused rather than certified against missing data.

Changelog category (leave one):

  • Improvement

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

A skip index materialized over a JSON subcolumn that was added as a lazy type hint (enable_json_lazy_type_hints) without rewriting the column data can now be used for query pruning.


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

Version info

  • Merged into: 26.11.1.1340-master (included in 26.11 and later)

With `enable_json_lazy_type_hints`, `ALTER MODIFY COLUMN j JSON(path Type)` is
metadata-only: existing wide parts keep the path on disk as `Dynamic` and cast to
the hinted type at read time. A skip index materialized over such a hinted
subcolumn (for example `j.a`) builds its granules against the hinted type, but the
read path refused to use it: the part's own column type (`Dynamic`) did not match
the index's built-against type, so `isPartTypeCompatibleImpl` and `canUseIndex`
treated the index as stale and disabled pruning.

Record, per part, the type each index's required columns were built against, but
only when it differs from the part's own declared type. This is kept in a new
optional, checksummed file `secondary_index_column_types.json`, written by the
mutation that (re)builds the index. The read-side staleness guards consult this
record: an index whose recorded built-against type matches the current metadata
type is used even though the column is still `Dynamic` on disk.

The record certifies the column type, not its values. A pending on-the-fly
`ALTER UPDATE` still disables pruning: `AlterConversions` now tracks
`value_updated_columns` separately from type changes, and `canUseIndex` rejects an
index whose required column has a pending value update regardless of any recorded
type override.

The new file is additive and backport-safe: parts without it behave exactly as
before (absent record = refuse a mismatched index). Hardlinked indices inherit
their source part's record unchanged; a required column the part does not
physically carry is left unrecorded, so the read path refuses its index instead of
certifying a granule whose data the part is missing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Avogar
Avogar force-pushed the allow-skip-index-pruning-lazy-json-hints branch from 0ae77c6 to eca85d9 Compare September 29, 2026 11:48
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3dae7b7]

Summary: ✅


AI Review

Summary

The PR enables skip-index pruning over lazy JSON type hints by recording index input types separately from part column types. One reproduced mixed-version compatibility bug allows stale type records to certify rebuilt indexes, silently discarding matching rows.

Findings
  • ❌ Blocker — recorded types are not bound to their index files (MergeTreeIndices.cpp:328). An older binary preserves the unknown secondary_index_column_types.json file during mutations, including index rebuilds. Its checksum remains valid, but the recorded types can describe the previous granules. The new read path trusts this stale record and enables incorrect pruning. This violates the PR's additive, backport-safe format contract.

    Reproduction using one persistent table:

    1. On the PR binary, insert 64 rows containing {"a":1577836800} into a wide part with j JSON; lazily alter to JSON(a DateTime('UTC')), then add and materialize a minmax index on toHour(j.a).
    2. On a pre-feature binary, change the hint to DateTime('Europe/Moscow'), run CLEAR INDEX idx IN PARTITION tuple() and MATERIALIZE INDEX idx synchronously, then restore DateTime('UTC').
    3. On the PR binary, SELECT count() FROM t WHERE toHour(j.a) = 0 returns 0, while the same query with SETTINGS use_skip_indexes = 0 returns 64. The rebuilt index contains hour 3, while the inherited record still certifies DateTime('UTC'); all 16 matching granules are pruned.

    Confirmed on fresh data using PR ARM release 1325f5f5318375a3cde341d003aa109ecdf33790 and pre-feature master fd1c83b13f5330b059d4e974a89896f25cd5aacf. The affected metadata, mutation, and index-eligibility code is unchanged at the reviewed head. The same failure is possible when an older replica mutates a part received from an upgraded replica. Bind overrides to the index-file checksums, or otherwise reject records preserved across older index rewrites; add a mixed-version regression.

Missing context / blind spots
  • ⚠️ The exact-head ARM CI artifact was unavailable. Runtime reproduction used the preceding PR artifact; the head only changes pending-rename invalidation and its regression test. Rerunning the reproduction on the exact-head binary would close this execution gap.
Final Verdict

❌ Block — Prevent older writers from leaving trusted type records attached to rebuilt index files, and cover the mixed-version sequence with a regression.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 29, 2026
The style check forbids `std::stringstream`. Serialize `SecondaryIndexColumnTypes`
straight to the `WriteBuffer` with `writeJSONString`/`writeChar`, matching
`SerializationInfoByName::writeJSON`. The JSON shape and `readJSON` are unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 29, 2026
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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 ⚠️

117 object files changed (+400.56 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/SecondaryIndexColumnTypes.cpp.o new 314.20 KiB +314.20 KiB

719 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.

Compile time of recompiled translation units

390 translation units recompiled, 3959 s compile time in total, 389 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Storages/MergeTree/SecondaryIndexColumnTypes.cpp: 6.2 s

Job report

When a mutation recomputes an empty secondary index column types record, the new
part must not inherit the source part's `secondary_index_column_types.json` checksum
entry. Add the empty-to-delete cleanup in `collectFilesForRenames`, mirroring
`serialization.json`, so `checksums.txt` never references a file the part does not
have.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@vdimir vdimir self-assigned this Oct 6, 2026
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Avogar and others added 2 commits October 21, 2026 14:13
…pruning-lazy-json-hints

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
#	src/Storages/MergeTree/AlterConversions.cpp
Address review: the comment now names `secondary_index_column_types.json` explicitly instead of saying "inherited checksum entry".

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A pending `DROP COLUMN` is a metadata mutation, so `AlterConversions` recorded it
only in `dropped_columns` and `canUseIndex` never saw it, while the reader returns
the replacement column's defaults. On master such an index was refused only by
the physical type mismatch in `isPartTypeCompatibleImpl`, but the recorded
built-against type bypasses that check, so after a pending
`DROP COLUMN j, ADD COLUMN j JSON(a UInt64)` the old granules pruned away rows.

Treat a pending drop as an on-the-fly value change: add the dropped column to
`value_updated_columns`, and make `canUseIndex` reject an index whose required
column overlaps that set regardless of the type record. Also check
`hasMetadataMutations` in the `partHasStaleTopKIndex` and
`supportsSkipIndexesOnDataRead` gates, so a pending drop reaches the per-part
check on the Top-K and data-read paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Direct reads from a text index decide eligibility from the query-wide
`getColumnsChangedOnFly`, which skipped metadata mutations, and the index-only
count checked only data mutations, patches and lightweight deletes. With the
recorded built-against type making `getDeserializedFormat` accept the old index,
a pending `DROP COLUMN j, ADD COLUMN j JSON(a String)` returned the old postings
although the reader returns defaults for the replaced column.

Collect columns of pending `DROP_COLUMN` commands in `getColumnsChangedOnFly`, and
bail out of the text-index count optimization when metadata mutations are pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Avogar and others added 2 commits October 23, 2026 13:28
… fly

An on-the-fly mutation recalculates the MATERIALIZED columns computed from an
updated column, but `canUseIndex` only compared the index's required columns with
the updated ones, so an index over such a column was used with stale granules.
This already gave wrong results for plain MATERIALIZED columns, and the recorded
built-against type exposed lazily hinted JSON columns to it as well, where the
physical type mismatch used to refuse the index.

`canUseIndex` now takes a context and rejects an index whose required column is a
MATERIALIZED column that `MaterializedColumnDependencies` reports as recalculated
from the updated columns, the same rule `AlterConversions::buildMutationChainForRead`
uses. This covers skip-index pruning, the index read pool, Top-K and direct reads
from text indexes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pruning-lazy-json-hints

# Conflicts:
#	src/Storages/MergeTree/IndexReadRangesRefiner.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.h
#	src/Storages/MergeTree/MergeTreeSelectProcessor.cpp
The per-part type record relaxes a pending MODIFY COLUMN type change when the
recorded built-against type still matches, but it only certifies the type, not the
column identity. A rename that swaps two names (so a column of the required name
still exists and ALTER validation accepts it) left the record matching while the
name now reads another column, so the stale granules were used.

Add the names touched by a pending RENAME COLUMN to value_updated_columns, the
never-relaxable set `canUseIndex` checks before the type-record exemption, next to
the dropped names already there.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Nov 4, 2026
Merged via the queue into master with commit 085dcbe Nov 4, 2026
185 checks passed
@Avogar
Avogar deleted the allow-skip-index-pruning-lazy-json-hints branch November 4, 2026 15:17
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. label Nov 22, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. pr-improvement Pull request with some product 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.

3 participants