Skip to content

Skip statistics and skip index pruning for parts with pending mutations - #117320

Open
zoomxi wants to merge 10 commits into
ClickHouse:masterfrom
zoomxi:fix-statistics-part-pruning-pending-alter-mutation
Open

zoomxi wants to merge 10 commits into
ClickHouse:masterfrom
zoomxi:fix-statistics-part-pruning-pending-alter-mutation

Conversation

@zoomxi

@zoomxi zoomxi commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #116627
Closes: #117323

Statistics- and skip-index-based part pruning look up a part's min/max by the queried column name. That is only valid while the part's data behind that name is what a read of the name returns. Three pending on-the-fly mutations break this assumption, and the original guard covered just the first one:

  • ALTER MODIFY COLUMN converts values on read, so the stored min/max describe the old type.
  • ALTER RENAME COLUMN re-points the name at a different column, so the statistics describe another column.
  • ALTER DROP COLUMN makes the part's data for the name invisible on read. The name is only visible to the query because it was re-added after the drop, so the statistics describe a column the query cannot see.

RENAME and DROP do not enter all_updated_columns, and pure metadata mutations do not set hasAlterMutations(), so the two extra forms slipped through every pruning path built on those checks.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix silently missing rows when pruning parts by statistics or skip indexes on a column with a pending ALTER.


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

@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The per-part guard here structurally misses the rename shape of the same bug, which I have just filed as #117323 (verified on 26.8 and a current master build): with a pending ALTER TABLE t DROP COLUMN x, RENAME COLUMN y TO x, reads already return the renamed data while filterPartsByStatistics evaluates the dropped column's statistics under the name x and prunes the part — WHERE x = 100 returns 0 instead of 1 at default settings.

Two reasons the fix as written cannot catch it:

  1. RENAME_COLUMN/DROP_COLUMN are metadata mutations (AlterConversions::isSupportedMetadataMutation), so mutations_snapshot->hasAlterMutations() is false and the new per-part loop never engages (the outer hasDataMutations || hasAlterMutations || hasPatchParts gate does not fire either — that is the pre-existing hole).
  2. AlterConversions::addMutationCommand records renames only in rename_map; they never enter all_updated_columns, so anyColumnOverlaps would see nothing even if the loop ran.

Since the guard machinery is being introduced here, it may be worth widening it in the same change: also skip pruning for a part when alter_conversions->isColumnRenamed(<stats column>) (or gate on pending metadata mutations as a whole), so both siblings of #116627 close together.

@zoomxi
zoomxi force-pushed the fix-statistics-part-pruning-pending-alter-mutation branch from ddcfc6e to 2dc59d9 Compare September 1, 2026 03:34
@zoomxi zoomxi changed the title Skip statistics-based part pruning for parts with a pending ALTER MODIFY COLUMN Skip statistics-based part pruning for parts with pending mutations Sep 1, 2026
@zoomxi

zoomxi commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

The per-part guard here structurally misses the rename shape of the same bug, which I have just filed as #117323 (verified on 26.8 and a current master build): with a pending ALTER TABLE t DROP COLUMN x, RENAME COLUMN y TO x, reads already return the renamed data while filterPartsByStatistics evaluates the dropped column's statistics under the name x and prunes the part — WHERE x = 100 returns 0 instead of 1 at default settings.

Thanks for catching this — the rename shape was indeed outside the per-part guard.

@zlareb1 zlareb1 added the can be tested Allows running workflows for external contributors label Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [80a2a76b]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Cannot alter table A metadata doesn't have structure (STID: 3623-38a4) FAIL cidb

AI Review

Summary

This PR broadens the stale-part fail-open handling across statistics pruning, skip-index pruning, text-index direct reads, trivial-count defaultness stats, and the query condition cache for pending ALTER/metadata mutations. The main holes I previously raised are fixed in the current code, but one sibling runtime-filter path still trusts the physical primary key under read-time masking rewrites, so I do not think the change is ready to merge yet.

Findings
  • ❌ Blocker [src/Storages/MergeTree/MergeTreeIndexReadResultPool.cpp:189] The new canUseIndex(..., alter_conversions) guard fixes runtime skip indexes, but the adjacent prune_primary_key branch still prunes marks from the physical PK without checking whether read-time rewrites changed what the user-visible column means. Under Cloud masking policies, buildReadTaskInfo already converts the policy into synthetic READ_COLUMN mutations, so skip indexes now fail open while markRangesFromPKRange still sees the unmasked key. A table ORDER BY x with a masking policy rewriting x to 0 plus a join runtime filter x IN (0) will therefore drop the whole part even though every visible row matches after masking. Suggested fix: disable runtime_prune_primary_key when part->storage.hasEnabledMaskingPolicies(context) is true, or thread the same stale-column/masked-column contract into the runtime PK path before markRangesFromPKRange.
Tests
  • ⚠️ Add a focused Cloud regression for a join runtime filter on a masked PK column. The smallest proof is a table ordered by x, a masking policy that rewrites x, and a join/filter that should match on the masked value while runtime pruning is enabled.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 80a2a76b.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 168/175 (96.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 80a2a76b1 with master 794800200 (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

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

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -154.9 s (-4%) in total before that adjustment.

Job report

@zoomxi
zoomxi force-pushed the fix-statistics-part-pruning-pending-alter-mutation branch from 2dc59d9 to 404e524 Compare September 1, 2026 08:37
…t path

The read-time top-k path (`use_skip_indexes_for_top_k` + `use_skip_indexes_on_data_read`,
both on by default) fills `MergeTreeIndexReadResult::min_max_index_for_top_k` unconditionally
in `MergeTreeSkipIndexReader::read` and lets `canSkipMark` drop granules against the running
threshold. A pending ALTER that touches the indexed column leaves the part's minmax stale, so
the granule holding the live top rows can be silently dropped once another part establishes
the threshold.

Reuse `MergeTreeDataSelectExecutor::canUseIndex` — the same per-part staleness check the
upfront top-k path (`partHasStaleTopKIndex`) and the regular skip-index path in the same
function already use — to skip the minmax build for stale parts. Without a minmax,
`canSkipMark` leaves the part alone and the read returns correct results.

Covers the two-command pending ALTER shape `(DROP COLUMN x), (RENAME COLUMN y TO x)`,
where the read-time path would otherwise return the live part's smaller value instead of
the decoy's true top value.

Regression test: 05056_skip_index_stale_top_k_pending_alter.
@zoomxi zoomxi changed the title Skip statistics-based part pruning for parts with pending mutations Skip statistics and skip index pruning for parts with pending mutations Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
`filterPartsByQueryConditionCache` consulted entries primed before a
pending ALTER because its gate only covered data mutations and patch
parts. A pending metadata mutation (DROP / RENAME / ADD reusing a name)
rewrites the rows a part holds under an unchanged name, so a stale
verdict could erase parts before the live read path sees the new rows.

Gate the index-analysis consult and both `reader_settings` enables in
`ReadFromMergeTree` on any pending mutations, mirroring the existing
data-mutation handling. The reader-side gate also stops priming new
entries during the pending window.

Covered by 05077: priming the cache with the pre-ALTER predicate, then
rerunning it under a pending (DROP + re-ADD) and (DROP + RENAME).
The gate added in the previous commit disabled cache reads and writes for
any pending mutation, including data mutations. Priming under a pending
mutation of an unread column must keep working: `filterMutationCommands`
drops UPDATE commands touching none of the columns the query reads, so
such a mutation produces no on-fly mutation steps and the per-part write
gate (`appliesMutationsBeforePrewhere`) correctly allows cache writes.
The broad gate broke that contract and failed
04669_query_condition_cache_lightweight_delete.

Keep the write-side gate (both `reader_settings` sites in
`ReadFromMergeTree`) to metadata and alter mutations only: DROP / RENAME
/ ADD reuse names without producing on-fly mutation steps, so the
per-part gate never fires for them. The consult gate in
`filterPartsByQueryConditionCache` keeps bailing out on any pending
mutation.

Verified: 04669 5/5 OK (failed 5/5 before the fix, same diff as CI),
05077 5/5 OK, 05045 / 05055 / 05056 / 05058 / 05076 OK.

CI: https://github.com/ClickHouse/ClickHouse/actions/runs/34188868167/job/101942890874
PR: ClickHouse#117320
if (dynamic_skip_index_filter && !dynamic_skip_index_filter(*index_helper))
continue;
if (auto can_use = MergeTreeDataSelectExecutor::canUseIndex(index_helper, metadata_snapshot, all_updated_columns); !can_use)
if (auto can_use = MergeTreeDataSelectExecutor::canUseIndex(index_helper, metadata_snapshot, alter_conversions); !can_use)

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.

This new canUseIndex(..., alter_conversions) check hardens the runtime skip-index branch, but the sibling prune_primary_key block just above still prunes on the physical PK without consulting alter_conversions.

That leaves a wrong-result path for Cloud masking policies. buildReadTaskInfo already turns those policies into synthetic READ_COLUMN conversions, so the dynamic skip-index path now correctly fails open here, but markRangesFromPKRange still sees the unmasked key. A concrete trace is a table ORDER BY x with a masking policy rewriting x to 0 for the querying user and a join runtime filter x IN (0): the query should keep every row, but the runtime PK pruning drops the part because the stored PK contains only the original non-zero values.

Please either disable runtime_prune_primary_key when part->storage.hasEnabledMaskingPolicies(context) is true, or teach the PK path to apply the same stale-column contract before calling markRangesFromPKRange.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

4 participants