Skip to content

Fix ALTER COLUMN on tables with implicit min-max index over virtual columns - #109428

Merged
Michicosun merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-alter-column-implicit-minmax-virtual-index
Jul 6, 2026
Merged

Michicosun merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-alter-column-implicit-minmax-virtual-index

Conversation

@groeneai

@groeneai groeneai commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: https://github.com/ClickHouse/ClickHouse/blob/master/tests/queries/0_stateless/01378_alter_rename_with_ttl_zookeeper.sql

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 UNKNOWN_IDENTIFIER error when running ALTER TABLE ... RENAME/ADD/MODIFY COLUMN on a MergeTree table that has an implicit min-max index over the persistent virtual columns _block_number or _block_offset (enabled by add_minmax_index_for_block_number_column / add_minmax_index_for_block_offset_column).

Description

When enable_block_number_column / enable_block_offset_column are on together with add_minmax_index_for_block_number_column / add_minmax_index_for_block_offset_column, the table gets an implicit min-max skip index over the persistent virtual columns _block_number / _block_offset (auto_minmax_index__block_number, auto_minmax_index__block_offset).

Any ALTER on a physical column (RENAME / ADD / MODIFY) then failed, e.g.:

Code: 47. DB::Exception: Cannot apply ALTER because it breaks skip index
auto_minmax_index__block_number: Missing columns: '_block_number' ...
available columns: 'value1' 'renamed_date1'. (UNKNOWN_IDENTIFIER)

AlterCommands::apply re-derives every secondary index from its AST during validation, but resolved them against physical columns only. The implicit indices over virtual columns could not resolve _block_number / _block_offset and threw, even though the ALTER did not touch those columns. This fix resolves implicitly-created indices against the persistent virtual columns as well, matching how they are created in StorageInMemoryMetadata::addImplicitIndicesForVirtualColumns. Explicit indices are unchanged and still resolved against physical columns only, so the guard against ALTERs that genuinely break a user-defined index is intact.

Added a regression test (04401_implicit_minmax_block_number_offset_alter_column) covering RENAME/ADD/MODIFY column with the _block_number/_block_offset implicit index, and asserting the index still prunes granules after the ALTER.

No related open GitHub issue was found; this surfaces as flaky failures of the public stateless test 01378_alter_rename_with_ttl_zookeeper in PR runs where CI randomization enables these settings, and will become reproducible on master once the virtual min-max index is enabled by default.

Version info

  • Merged into: 26.7.1.546 (included in 26.7 and later)

…olumns

When enable_block_number_column / enable_block_offset_column and the
corresponding add_minmax_index_for_block_*_column settings are on, the table
gets an implicit min-max skip index over the persistent virtual columns
_block_number / _block_offset (auto_minmax_index__block_number, etc.).

Any ALTER on a physical column (RENAME / ADD / MODIFY) then failed with
UNKNOWN_IDENTIFIER, e.g.

  Cannot apply ALTER because it breaks skip index auto_minmax_index__block_number:
  Missing columns: '_block_number' ... available columns: 'value1' 'renamed_date1'

AlterCommands::apply re-derives every secondary index from its AST during
validation, but resolved them against physical columns only. The implicit
indices over virtual columns could not resolve _block_number / _block_offset
and threw, even though the ALTER did not touch those columns.

Resolve implicitly-created indices against the persistent virtual columns as
well, matching how they are created in
StorageInMemoryMetadata::addImplicitIndicesForVirtualColumns. Explicit indices
are unchanged and still resolved against physical columns only.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (date1 Date, value1 String) ENGINE=MergeTree ORDER BY tuple() SETTINGS enable_block_number_column=1, add_minmax_index_for_block_number_column=1; INSERT ...; ALTER TABLE t RENAME COLUMN date1 TO renamed_date1; throws Code 47 UNKNOWN_IDENTIFIER every time. Same with _block_offset, and with ADD/MODIFY COLUMN.
b Root cause explained? The implicit index auto_minmax_index__block_number is created (in addImplicitIndicesForVirtualColumns) by resolving _block_number against the table's virtual columns. AlterCommands::apply re-derives every secondary index from its AST during validation, but passed only metadata_copy.columns (physical) to getIndexFromAST — unlike the sorting/primary/partition keys just above, which also pass metadata_copy.virtuals. So _block_number cannot be resolved and validation throws, even though the ALTER never touched it.
c Fix matches root cause? Yes. The fix resolves implicitly-created indices against physical columns + persistent virtual columns during that validation loop, mirroring how the index is created. No symptom-masking, no widened bounds, no no-random-* tag.
d Test intent preserved / new tests added? New test 04401_implicit_minmax_block_number_offset_alter_column added. It covers RENAME/ADD/MODIFY column with the _block_number/_block_offset implicit index, and asserts (via SELECT count()>0 FROM (EXPLAIN indexes=1 ...) WHERE explain ILIKE '%auto_minmax_index__block_number%') that the index still PRUNES after the ALTER — so it verifies the optimization is preserved, not just that the ALTER stops throwing. Existing tests 04229/04230 cover the feature but not column ALTERs.
e Both directions demonstrated? Yes. Without the fix (Build 857b8060) the test FAILS with the exact Code 47 ... Missing columns: '_block_number' signature. With the fix (Build 34567d97) it PASSES and the reference matches on a real server.
f Fix is general across code paths? The secondary-index validation loop is the single site that re-derives ALL implicit indices, so the fix covers _block_number, _block_offset, both, and every ALTER type in one place. It is not a per-call-site guard. (A distinct, separate bug in the mutation read pipeline — part_minmax_index_columns='with_block_number_offset' surfacing as Code 341 — is a different feature/code path and is out of scope for this focused skip-index fix; tracked separately.)
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified across the input matrix: _block_number index, _block_offset index, both together; ALTER RENAME / ADD / MODIFY column. The implicit index only ever covers the two fixed UInt64 persistent virtual columns, so datatype/wrapper variance (Nullable/LowCardinality/Array) does not apply. Regression-checked that explicit indices are unaffected and physical-column implicit indices still rename correctly.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, on-disk/wire format, or validation-on-existing-data change. It only makes previously-failing ALTERs succeed. No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. Only implicitly-created indices get virtual columns added to their resolution ColumnsDescription; explicit indices are still resolved against physical columns only, so the "ALTER breaks a user-defined index" guard is intact (verified: dropping a column an explicit index depends on still throws Code 47). The augmented ColumnsDescription is a local copy built lazily; metadata_copy and the stored index set are otherwise unchanged.

Session id: cron:clickhouse-worker-slot-1:20260705-043700

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @CurtizJ — could you review this? It fixes UNKNOWN_IDENTIFIER on any ALTER ... RENAME/ADD/MODIFY COLUMN when the table has the implicit min-max index over _block_number/_block_offset: AlterCommands::apply re-validated secondary indices against physical columns only, so the virtual-column implicit index could not resolve. This blocks enabling the virtual min-max index by default (#109281) and shows up as flaky failures of 01378_alter_rename_with_ttl_zookeeper.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [15a6faf]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Logical error: Invalid state transition, expected A, got B (STID: 3913-4579) FAIL cidb

AI Review

Summary

This PR fixes ALTER ... RENAME/ADD/MODIFY COLUMN on MergeTree tables that carry the implicit skip indices over _block_number / _block_offset by re-resolving secondary indices against a column set that includes virtuals. The implementation and regression coverage look sound, but the changelog/PR body currently overstate the affected feature surface.

PR Metadata
  • Changelog category: Bug Fix matches the actual behavior change.
  • Changelog entry: specific and user-readable, but it currently claims the fix also applies when the table is configured via part_minmax_index_columns = 'with_block_number_offset'. This patch only revalidates secondary_indices; the part-level min-max path is separate and is not touched here.
  • Exact replacement text:
Fix `UNKNOWN_IDENTIFIER` error when running `ALTER TABLE ... RENAME/ADD/MODIFY COLUMN` on a `MergeTree` table that has an implicit min-max index over the persistent virtual columns `_block_number` or `_block_offset` (enabled by `add_minmax_index_for_block_number_column` / `add_minmax_index_for_block_offset_column`).
Findings

💡 Nits

  • [src/Storages/AlterCommands.cpp:1418] The code change only affects metadata_copy.secondary_indices, so the release note should not mention part_minmax_index_columns = 'with_block_number_offset' unless there is a separate reproducer showing that path also fails here.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: narrow the changelog/PR description to the secondary_indices / implicit skip-index path, or add evidence that the part_minmax_index_columns = 'with_block_number_offset' case really goes through this fix.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 5, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
@Michicosun Michicosun self-assigned this Jul 5, 2026
groeneai and others added 3 commits July 5, 2026 11:31
Address review: the previous check matched only the index name in
EXPLAIN indexes = 1 output, which prints the index name even when it reads
every granule (Granules: N/N). A regression that kept the index attached but
stopped pruning would still have passed.

Assert on the Granules line instead: after the ADD/MODIFY/RENAME COLUMN
sequence, _block_number = 1 must read 10/20 granules and _block_offset = 0
must read 2/20 (index_granularity = 1, 20 rows in two blocks). A stopped-pruning
regression reads 20/20 and fails these. Also RENAME the added column to widen
the ALTER coverage.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Per review feedback:
- Resolve implicit indices against getSampleBlockWithVirtuals instead of
  building a std::optional<ColumnsDescription> and merging virtual columns by
  hand. Explicit indices are still resolved against the physical columns only,
  so the "ALTER breaks explicit index" guard is unchanged.
- Restore the original one-line comment above the loop.
- Simplify the test to a single table exercising RENAME / ADD / MODIFY with
  both implicit indices, instead of three tables.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…column set

The previous fixup switched the secondary-index re-validation pool from
metadata_copy.columns (+ deduped virtuals) to getSampleBlockWithVirtuals(),
which is built from getAllPhysical() + virtuals appended unconditionally. That
introduced two regressions:

- getAllPhysical() drops ALIAS/EPHEMERAL columns, so an implicit min-max index
  over an ALIAS column (auto_minmax_index_<alias>) could no longer resolve its
  expression after an ALTER, throwing UNKNOWN_IDENTIFIER
  (03768_rename_alias_column_implicit_index).
- Appending virtuals without a dedup produced a block with both a physical and a
  virtual column of the same name (e.g. a physical _part_offset plus the virtual
  _part_offset), yielding AMBIGUOUS_COLUMN_NAME on ALTER ADD/analysis
  (04040_alter_ephemeral_column_conflicts_with_virtual,
  03401_normal_projection_with_part_offset).

Restore the original approach: start from the full metadata_copy.columns (which
includes alias/ephemeral) and add each virtual only if a column of that name is
not already present (physical shadows virtual). Explicit indices are still
resolved against metadata_copy.columns only, so the "ALTER breaks explicit
index" guard is unchanged.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 0bd7dcc fixing a regression the previous fixup (029ff8b, the getSampleBlockWithVirtuals simplification) introduced. Three pre-existing tests went red on Fast test:

  • 03768_rename_alias_column_implicit_index
  • 04040_alter_ephemeral_column_conflicts_with_virtual
  • 03401_normal_projection_with_part_offset

Root cause: getSampleBlockWithVirtuals() is built from getAllPhysical() + virtuals appended unconditionally, which

  1. drops ALIAS/EPHEMERAL columns, so an implicit index over an ALIAS column can't resolve after ALTER (Code 47 UNKNOWN_IDENTIFIER), and
  2. yields a block with both a physical and a virtual column of the same name when a physical _part_offset exists, giving AMBIGUOUS_COLUMN_NAME on ALTER.

Fix: start the resolution pool from the full metadata_copy.columns (keeps alias/ephemeral) and add each virtual only if not already present (physical shadows virtual). Explicit indices still resolve against metadata_copy.columns only, so the existing "ALTER breaks explicit index" guard is unchanged.

Verified locally against a fresh build (buildId 831ddc63): all three previously-red tests plus 04401 and 03401_..._no_sorting pass (5/5). The 04401 Granules assertions you asked for are unchanged.

Comment thread src/Storages/AlterCommands.cpp Outdated
Comment on lines +1417 to +1424
/// Changes in columns may lead to changes in secondary indices.
/// Implicit indices may reference persistent virtual columns (e.g. `_block_number`); resolve them
/// against the full column set (incl. alias/ephemeral) plus virtuals, a physical column shadowing
/// a virtual of the same name.
ColumnsDescription columns_with_virtuals = metadata_copy.columns;
for (const auto & virtual_column : metadata_copy.virtuals.toColumnsDescription(VirtualsKind::All, VirtualsMaterializationPlace::All))
if (!columns_with_virtuals.has(virtual_column.name))
columns_with_virtuals.add(virtual_column);

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.

introduce method StorageInMemoryMetadata::getColumnsWithVirtuals

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done — added StorageInMemoryMetadata::getColumnsWithVirtuals() (next to getSampleBlockWithVirtuals) and the call site now just uses it.

Comment thread src/Storages/AlterCommands.cpp Outdated
Comment on lines +1417 to +1420
/// Changes in columns may lead to changes in secondary indices.
/// Implicit indices may reference persistent virtual columns (e.g. `_block_number`); resolve them
/// against the full column set (incl. alias/ephemeral) plus virtuals, a physical column shadowing
/// a virtual of the same 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.

do not change any comments in this pr

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Restored the original comment verbatim.

Comment thread src/Storages/AlterCommands.cpp Outdated
Comment on lines +1431 to +1433
index.definition_ast,
index.isImplicitlyCreated() ? columns_with_virtuals : metadata_copy.columns,
index.isImplicitlyCreated(), index.escape_filenames, context);

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.

we can always use extended columns set to simplify this

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done — dropped the isImplicitlyCreated() ternary; all indices now resolve against the extended set. Safe because the set is the full columns (incl. alias/ephemeral) + virtuals with physical shadowing virtual, so a dropped physical column an explicit index needs is still absent (guard still throws) and there is no duplicate _part_offset. Verified: DROP COLUMN under an explicit index still throws Code 47; physical _part_offset + projection ALTER no longer ambiguous; 04401/03768/04040/03401(+no_sorting) all pass.

…uals

Factor the implicit-index column resolution into a named method
StorageInMemoryMetadata::getColumnsWithVirtuals and always resolve
secondary indices against it, dropping the isImplicitlyCreated ternary.
The extended set is the full column list (incl. alias/ephemeral) plus
virtual columns, a physical column shadowing a virtual of the same name,
so explicit indices still fail an ALTER that removes a column they need
and no _part_offset ambiguity is introduced. Original comment restored.
@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

@Michicosun addressed all three — getColumnsWithVirtuals() method, original comment restored, and the extended set is now used for all indices (ternary dropped). The call site is a single line. Guards verified intact (explicit-index DROP still throws; no _part_offset ambiguity; the alias/ephemeral/projection regression tests + 04401 all pass). Pushed as 15a6faf.

metadata_copy.sampling_key.recalculateWithNewAST(metadata_copy.sampling_key.definition_ast, metadata_copy.columns, metadata_copy.virtuals, context);

/// Changes in columns may lead to changes in secondary indices
const ColumnsDescription columns_with_virtuals = metadata_copy.getColumnsWithVirtuals();

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.

AlterCommands::apply only rebuilds metadata_copy.secondary_indices, so this fix covers the implicit skip-index path from add_minmax_index_for_block_*_column. The PR body/changelog currently also mention part_minmax_index_columns = 'with_block_number_offset', but that is a separate per-part min-max path in MergeTreeData::getMinMaxColumns and never reaches this loop. Please drop that setting from the release note unless you have a failing repro that goes through secondary_indices here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Corrected — dropped part_minmax_index_columns = 'with_block_number_offset' from the changelog entry. Confirmed the reasoning: the fix rebuilds only metadata_copy.secondary_indices, and part_minmax_index_columns resolves entirely through MergeTreeData::getMinMaxColumns (per-part min-max, used in the partition/write/merge pipeline) — it has no reference to secondary_indices and never reaches this loop. That per-part path surfaces as a separate NOT_FOUND_COLUMN_IN_BLOCK '_block_number' (Code 341), out of scope for this skip-index fix and tracked in #106780.

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

The AST fuzzer (amd_debug) LOGICAL_ERROR on this PR's CI (Invalid state transition, expected WRITING_BLOCKS, got JOINING_BLOCKS in GraceHashJoin::FileBucket, STID 3913-4579) is a pre-existing trunk bug, not caused by this PR. Root cause: ColumnObject::computeHashInto hashed the physical dynamic/shared_data path split, so a JSON grace_hash join key could re-hash to an earlier bucket across a spill and trip the FileBucket state-machine assertion. Fixing PR: #109450.

@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 15a6faf

CI is fully finished. Every failure has an owner; none is caused by this PR.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Invalid state transition WRITING_BLOCKS/JOINING_BLOCKS in GraceHashJoin::FileBucket (STID 3913-4579) trunk bug (split-dependent ColumnObject hash; not caused by this PR) #109450 (ours, open)
Mergeable Check / PR rollup of the above owned via #109450

Root cause and fixing-PR detail: see #109428 (comment)

Session id: cron:our-pr-ci-monitor:20260705-193000

@Michicosun
Michicosun added this pull request to the merge queue Jul 6, 2026
Merged via the queue into ClickHouse:master with commit c739ffd Jul 6, 2026
173 of 175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 6, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…mplicit-minmax-virtual-index

Fix ALTER COLUMN on tables with implicit min-max index over virtual columns
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 pr-bugfix Pull request with bugfix, not backported by default 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.

5 participants