Skip to content

Add secondary_indices_materialized column to system.parts - #89350

Open
aryan32agrawal wants to merge 52 commits into
ClickHouse:masterfrom
aryan32agrawal:contribution
Open

aryan32agrawal wants to merge 52 commits into
ClickHouse:masterfrom
aryan32agrawal:contribution

Conversation

@aryan32agrawal

@aryan32agrawal aryan32agrawal commented Nov 1, 2025 •

Copy link
Copy Markdown

Changelog category:

  • New Feature

Changelog entry

[Users can now validate which secondary indices are fully materialized in a data part via the new “secondary_indices_materialized” column in the “system.parts” table.]

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

secondary_indices_materialized

Within the “/src/Storages/System/StorageSystemParts.cpp” code file, added a new column named “secondary_indices_materialized” to the “system.parts” system table to resolve issue #88576. This column provides an array of strings containing the specific names of all materialized secondary indices for each data part which was previously not possible if a given part had multiple secondary indices. The new column definition and its associated array output calculation are both placed in the correct order with respect to the existing column definition and calculation pairs.

Syntax

{"secondary_indices_materialized", std::make_shared(std::make_shared()), "The array of materialized secondary index names"},

...

if (columns_mask[src_index++])
{
Array materialized_indices;
auto secondary_indices_descriptions = part->storage.getInMemoryMetadataPtr()->secondary_indices;
for (const auto & index_description : secondary_indices_descriptions)
{
if (part->hasSecondaryIndex(index_description.name))
materialized_indices.push_back(index_description.name);
}
columns[res_index++]->insert(materialized_indices);
}

Arguments

Not applicable (no function added)

Implementation Details

The “secondary_indices_materialized” column is first defined; If run by a user query, the code retrieves all secondary index definitions for all existing parts from the overall metadata table using “part->storage.getInMemoryMetadataPtr()->secondary_indices”, then iterates through each of these secondary index definitions and validates if it is actually materialized in the current part, with “part->hasSecondaryIndex(index_description.name)”. This way, index names are only added to the resulting array if they exist for the specified part, before the result array is inserted into the output column.

Returned value

  • Returns {columns[res_index++]->insert(materialized_indices);}. Array

Example

Query:

```sql
SELECT 'name, secondary_indices_materialized FROM system.parts WHERE database = ‘ex_database' AND table = ‘ex_table’;
```

Response:

```response
┌──────name─────────────secondary_indices_materialized───────────┐
│ [part_number] │ [‘indexStr1’, ‘indexStr2’, ‘…’]
└─────────────────────────────────────────────── ┘
```


Additional fix (2026-07-27)

While adding the regression test for the escape_index_filenames semantics of the new column, CI (under the randomized MergeTree setting auto_statistics_types) exposed an unrelated pre-existing bug, fixed here as well:

In the settings-alter branch of StorageMergeTree::alter and StorageReplicatedMergeTree::alter, changeSettings is the sole writer of the setting-derived fields StorageInMemoryMetadata::escape_index_filenames and IndexDescription::escape_filenames. When the table carries an explicit auto_statistics_types setting, the subsequent setInMemoryMetadata call that re-commits the implicit statistics writes back a metadata copy that was taken before changeSettings (commands.apply never sets those fields), so ALTER TABLE ... MODIFY SETTING escape_index_filenames = ... did not take effect until the server was restarted. The committed escape fields are now carried into that copy, exactly as the areNonReplicatedAlterCommands branch of StorageReplicatedMergeTree::alter already does for the comment commit.

New test: 04650_alter_escape_index_filenames_with_auto_statistics.

Closes: #88576


Additional fixes (2026-08-04 / 2026-08-12 / 2026-08-20)

  • A mixed ALTER that includes MODIFY SETTING escape_index_filenames (for example together with MODIFY COMMENT, or with a replicated command) republished a metadata copy taken before changeSettings and so reverted the index filename policy in memory until a server restart, in both StorageMergeTree::alter and StorageReplicatedMergeTree::alter. The policy is now re-applied from the committed escape_index_filenames setting through MergeTreeData::applyEscapeIndexFilenamesFromSettings. Test: 04700_alter_escape_index_filenames_mixed_alter.

  • The column no longer counts index files the part does not own. An index file left in the part directory but missing from checksums.txt is an orphan of the released bug Mutations via MutateAllPartColumnsTask write checksums.txt without hardlinked skip-index files #109595 and the index still has to be rebuilt, while a packed substream (a member of skp_idx.packed, which has no per-file entry of its own) does count. Tests: test_system_parts_secondary_indices (integration; test_orphan_index_file, test_packed_index).

  • The column now follows the read path exactly: it asks IMergeTreeIndex::getDeserializedFormat, the same call MergeTreeIndexReader makes, and requires the part to own every substream of the layout it returns, together with each substream's marks file (the reader loads marks for every stream it opens). A multistream index such as text is therefore not reported as materialized when a sibling stream is missing, and an index the reader refuses for another reason (an invalidated system column, or granules serialized under a column type the metadata no longer declares) is reported as absent too. Tests: 05023_system_parts_secondary_indices_text_index, test_system_parts_secondary_indices (integration; test_missing_marks_file).

  • The on-disk part surgery tests were moved from the stateless suite to the integration test test_system_parts_secondary_indices (2026-08-30): the style check server_data_manipulation_in_stateless_tests forbids modifying the server's data on disk in stateless tests, which run against arbitrary server configurations.


Additional fixes (2026-09-08)

  • The readiness check the column advertises is now shared with the read paths. IMergeTreeIndex::getDeserializedFormat - the gate MergeTreeDataSelectExecutor::filterMarksUsingIndex, MergeTreeReadTask::getIndexReadTaskForReadStep and MergeTreeIndexReader all go through - now requires the part to own every substream of the layout it returns together with each substream's marks file. A part that lost an index marks file, or a text index that kept only its base .idx, is therefore skipped by index analysis instead of being routed into the index and failing at query time; IMergeTreeDataPart::hasMaterializedSecondaryIndex is just that verdict, so secondary_indices_materialized cannot disagree with what a query can use. The missing-marks integration case now runs a real indexed query on the damaged part and asserts the index is skipped, with the intact part as the control.
  • ALTER TABLE ... MODIFY SETTING escape_index_filenames = 0 (and the RESET SETTING form) is now rejected while a skip index name contains /. Such a name can only be serialized with escaping on, so the previous behaviour left the table in a state where getIndexFileName threw BAD_ARGUMENTS from every read path and from a plain SELECT on system.parts. A table that reached that state before the check reports the index as absent instead of throwing. Test: 05137_alter_escape_index_filenames_slash_name.

Additional fixes (2026-09-16)

  • The escape_index_filenames rejection in MergeTreeData::checkAlterIsPossible applies to the initial ALTER only (ZooKeeperMetadataTransaction::isInitialQuery, like the sort-direction check next to it), so a replica of a Replicated database replaying an entry the initiator already committed applies it instead of wedging its DDL queue.
  • The packed fallback of indexFileExistsInChecksums requires actual skp_idx.packed membership (DataPartStorageOnDiskBase::isFileInPackedSkipIndicesArchive) instead of the generic existsFile, which falls back to a loose file on disk. A stray skp_idx_* file next to the archive that is in neither checksums.txt nor the archive is therefore not owned, neither for the column nor for the shared read gate. Test: test_system_parts_secondary_indices (integration; test_packed_orphan_file).

Additional fixes (2026-11-22)

  • A change of escape_index_filenames is rejected (for the initial ALTER) when the new file name of a surviving skip index equals the file name under which the data of another index is still stored in the parts - an index the table has, including one dropped in the same batch, or an index whose DROP INDEX mutation has not finished. Otherwise the files of that other index would be read as granules of the surviving one (for example a/b is stored as skp_idx_a%2Fb with escaping on, which is what a%2Fb resolves to with escaping off), giving wrong query results. Test: 05843_alter_escape_index_filenames_collision.

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

@CLAassistant

CLAassistant commented Nov 1, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov

Copy link
Copy Markdown
Member

Edit the title, please.

@antaljanosbenjamin antaljanosbenjamin self-assigned this Nov 3, 2025
@antaljanosbenjamin

Copy link
Copy Markdown
Member

We need tests for sure.

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @antaljanosbenjamin, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@aryan32agrawal aryan32agrawal changed the title Contribution Secondary_Indices_Materialized Jun 9, 2026
The signature of IMergeTreeDataPart::hasSecondaryIndex changed on master
to take the StorageMetadataPtr as a second argument (commit 115d710).
Pass the metadata snapshot to the call and reuse it for iterating over
secondary_indices.
…ence

Add the new column to the system.parts and system.dropped_tables_parts
documentation (the latter shares the same column list via
StorageSystemDroppedTablesParts), and update the
02117_show_create_table_system reference accordingly.
@alexey-milovidov alexey-milovidov changed the title Secondary_Indices_Materialized Add secondary_indices_materialized column to system.parts Jun 29, 2026
alexey-milovidov and others added 5 commits June 29, 2026 09:14
On current master MergeTreeData::getInMemoryMetadataPtr requires the query
context and a bypass_metadata_cache flag and returns a StorageMetadataHandle.
Pass (context, false) and keep the handle in a named variable so it converts
to StorageMetadataPtr (the rvalue conversion is deleted) when calling
hasSecondaryIndex.
Verifies that the new column lists the materialized secondary index names,
that an index added with ALTER TABLE ... ADD INDEX is absent for existing
parts until it is materialized with ALTER TABLE ... MATERIALIZE INDEX, and
that a table without secondary indices reports an empty array.
Make the test independent of the session default so the secondary indices
are always materialized on insert.
Two other 04417_* tests landed on master, so rename the new stateless
test for `secondary_indices_materialized` to the next free number.

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

Copy link
Copy Markdown
Member

Rebased on current master and added the missing tests and documentation requested above.

  • Added stateless test 04498_system_parts_secondary_indices_materialized covering: a freshly inserted part (both declared indices materialized), a newly ADD INDEXed index that is not yet materialized in the existing part, the same index appearing after MATERIALIZE INDEX, and a table with no secondary indices (empty array).
  • Updated 02117_show_create_table_system.reference for the new column.
  • Documented the column in docs/en/operations/system-tables/parts.md and dropped_tables_parts.md (the latter shares the schema, since StorageSystemDroppedTablesParts derives from StorageSystemParts).

The implementation was also updated to the current getInMemoryMetadataPtr(context, ...) / hasSecondaryIndex(name, metadata) signatures after the merge with master.

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

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b63351]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR adds system.parts.secondary_indices_materialized, shares index-readiness checks with readers, and repairs escape_index_filenames updates. The latest collision validation still permits another index's granules to be used after mutation cancellation or on a lagging database replica, causing wrong results. A new stateless assertion also fails under DBReplicated.

Findings
❌ Blockers
  • MergeTreeData.cpp:6859: An unfinished-mutation list does not prove index-file ownership. In the new 05843 setup, cancel the pending DROP INDEX a/b with KILL MUTATION while merges remain stopped, then disable escape_index_filenames. Cancellation erases the mutation record without removing the files. The collision check therefore accepts the change, and surviving index a%2Fb resolves to skp_idx_a%2Fb.*, the dropped index's granules over another column. An indexed w = 1 count can return 0 rather than 100, and secondary_indices_materialized falsely certifies the index. The same failure is reachable on a populated Replicated-database follower whose drop is pending after an empty initiator finishes its own drop: the initial-query-only guard skips validation on replay. Preserve index identity independently of mutation-record lifetime and enforce correctness for every affected replica without rejecting committed DDL replay. This remains the existing blocker; the latest fix does not cover these paths.
⚠️ Majors
  • 05843_alter_escape_index_filenames_collision.sql:74: The mixed-batch assertion expects the wrong exception under DBReplicated. Combining replicated DROP INDEX with non-replicated MODIFY SETTING raises QUERY_IS_PROHIBITED in validateReplicatedDatabaseSegments, before collision validation, rather than the expected BAD_ARGUMENTS. Move this assertion into a separate test tagged no-replicated-database; retain the standalone collision cases in the existing test.
Tests
  • ⚠️ Add a stateless regression cancelling the pending drop before changing the filename policy and compare indexed and unindexed results. Cover a database follower whose pending drop outlives the initiator's drop; it must remain correct before its mutation finishes.
  • ⚠️ Run the retained collision cases under DBReplicated and the separated mixed-batch case in an ordinary database.
Missing context / blind spots
  • ⚠️ Findings are verified against the current source and prior discussion, including the cancellation and DDL replay callees. The reproductions were not executed locally; no local build was available. Runtime results for the cases above would close this verification gap.
Final Verdict

Status: ❌ Block

Prevent index-file misattribution after cancellation and across database replicas, add focused regression coverage, and separate the incompatible DBReplicated assertion.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 3, 2026
…econdary_indices_materialized`

The AI review asked to make the presence check in `secondary_indices_materialized`
tolerant to both index filename policies, so that a part written before
`ALTER TABLE ... MODIFY SETTING escape_index_filenames ...` still lists its index.

A tolerant lookup would be wrong: the read path resolves the skip index file
through the very same `getIndexFileName` with the table's current
`escape_index_filenames` policy, so an index file written under the other policy
is not usable at all - `tests/integration/test_index_filename_upgrade` shows the
index dropping zero granules and the server logging
`File for index ... does not exist` until the policy is flipped back. Reporting
such an index as materialized would be a false positive that hides the fact that
the index is dead weight for that part, and would point the user away from the
fix (`ALTER TABLE ... MATERIALIZE INDEX`, which rewrites the file under the
current policy).

So keep the policy-aware check and make the behavior explicit instead: add a
comment at the call site and spell the rule out in the column description, which
is the source the system table docs are generated from.
…d `secondary_indices_materialized`

Pins the behavior the review asked about: an index written into a part under one
`escape_index_filenames` policy stops being reported in
`system.parts.secondary_indices_materialized` after the setting is flipped, and
comes back once `ALTER TABLE ... MATERIALIZE INDEX` rewrites it under the current
policy. This mirrors what the read path can use - with the escaped name in place
the `minmax` index prunes 12 of 13 granules, and after flipping the setting it
prunes none - so the column stays truthful about whether the index is usable for
that part.
…re-committed

The new test `04647_system_parts_secondary_indices_escape_filenames` failed in CI under the
randomized MergeTree setting `--auto_statistics_types basic,countmin`: after
`ALTER TABLE ... MODIFY SETTING escape_index_filenames = 0` the column still reported the index as
materialized.

Root cause: in the settings-alter branch of `StorageMergeTree::alter` and
`StorageReplicatedMergeTree::alter`, `changeSettings` commits the setting-derived fields
`StorageInMemoryMetadata::escape_index_filenames` and `IndexDescription::escape_filenames`, but when
the table carries an explicit `auto_statistics_types` setting the following
`setInMemoryMetadata(new_metadata)` re-commits a metadata copy taken before `changeSettings`
(`commands.apply` never sets those fields), reverting the index filename policy until the server
restarts.

Carry the committed escape fields into that metadata copy, exactly as the
`areNonReplicatedAlterCommands` branch of `StorageReplicatedMergeTree::alter` already does for the
comment commit.

Adds the test `04650_alter_escape_index_filenames_with_auto_statistics`.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=89350&sha=0204166cac29d481402c51451bc565718ce2eb3e&name_0=PR
Related: ClickHouse#89350
@groeneai

Copy link
Copy Markdown
Collaborator

No separate PR is needed. The fix is already on master, and it is in the tree you just pushed: #114777, merged 2026-09-10T07:41:08Z (d8d2f99). That is why there is no open issue for it.

Root cause: readUniqueKeyColumns inserts pipeline chunks straight into a dense accumulator (UniqueKeyDenseIndexOps.cpp:412 on 36ba194), so a sparsely serialized UNIQUE KEY column reaches ColumnVector<T>::doInsertRangeFrom and its assert_cast aborts (ColumnVector.cpp:750). The same defect has a second carrier one step later: ColumnSparse has no comparable serialization, so the SST encode raises NOT_IMPLEMENTED from batchSerializeAsComparable even once the insert succeeds. #114777 covers both, with convertToFullColumnIfSparse() on each reader chunk column (now :362) and on the accumulated block before the encode in ensureValidDenseIndex (:243), and it adds tests/integration/test_unique_key_sst/.

It cannot recur on fb4d706b: that sha's copy of the file carries both calls, 36ba194 carries neither, and d8d2f99 is an ancestor of fb4d706b (compare d8d2f99...fb4d706b reports behind_by: 0).

CIDB matches: the run you linked is the only occurrence of this abort on any ref since 2026-08-01, none after the merge, and test_unique_key_sst has been green on master since it landed.

alexey-milovidov and others added 4 commits September 26, 2026 03:10
The example output in `docs/reference/system-tables/parts.mdx` lies inside the
generated region and failed the "No direct edits to generated or read-only docs"
check. The column is documented through its description in `StorageSystemParts`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=89350&sha=eabe40c9ef72b361799d4e879ac620c1decd25d0&name_0=PR&name_1=Docs%20check%20%28Mintlify%29
ClickHouse#89350

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…filenames` check

Shared Catalog secondaries replay an ALTER without a `ZooKeeperMetadataTransaction`,
so the check treated them as the initial ALTER and could reject an entry the
initiator already committed. Recognize them via the client info, the same way
the other replay guards in `checkAlterEligibility` do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 10, 2026 08:47
# Conflicts:
#	src/Storages/System/StorageSystemParts.cpp
…med index state

`hasMaterializedSecondaryIndex` reports an index whose name contains `/` on a
table with `escape_index_filenames = 0` as absent, but the read path still
throws `BAD_ARGUMENTS` from `getFileName` for that state instead of skipping
the index. Say so in the comment and in the `secondary_indices_materialized`
column description rather than claiming the column matches the read path there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed b60b7b9:

  • 04700_alter_escape_index_filenames_mixed_alter is now tagged no-replicated-database. Its second half runs replicated and non-replicated ALTER commands in one query, and a Replicated database rejects that with QUERY_IS_PROHIBITED, which is why the DBReplicated job failed.
  • Merged the latest master (no conflicts). The changed translation units build, and all six new stateless tests pass locally.

The Stateless tests (arm_asan_ubsan, azure, sequential) red is not caused by this PR. The job ran into its 9000 s job timeout while every test it finished was OK, and #123849 (splitting that lane into 2 batches) is the fix for it.

alexey-milovidov and others added 3 commits October 19, 2026 21:15
Conflicts: `StorageSystemParts.cpp` keeps both the skip-index cache and the new
`DeleteBitmapStore`; `MergeTreeIndices` takes master's archive-only membership
check for packed substreams (it never asks the disk, matching the PR's intent).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-index virtual columns

`hasMaterializedTextIndex` in `MergeTreeBlockReadUtils.cpp` still used the
presence-only `hasSecondaryIndex`. A part that keeps the base `.idx` file of a
`text` index but lost another substream was then planned as if the
`__text_index_*` virtual column could be read directly, so the indexed column
was not injected. `MergeTreeReadTask::getTextIndexReadTaskForStep` refuses the
index for that part (`getDeserializedFormat` fails) and falls back to the
default expression, which had nothing to evaluate: with another part holding a
complete copy of the index, a `hasToken` filter silently returned no rows from
the damaged part.

Instantiate the index and ask `hasMaterializedSecondaryIndex`, the same
predicate as `system.parts.secondary_indices_materialized` and the reader.
Add a regression to the integration test module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 2 commits November 5, 2026 10:03
# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndices.cpp
…-named index is being dropped

A `DROP INDEX` mutation names the files to remove with the `escape_index_filenames`
policy of the metadata snapshot it runs against (`MutateTask`), and `getIndexFileName`
throws for a name with '/' when escaping is off. So reject disabling escaping when such
an index is dropped in the same `ALTER` batch (it is only in the old metadata) or an
earlier `DROP INDEX` mutation for it is still unfinished.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 13, 2026 09:42
… regardless of the policy

The previous fix rejected disabling `escape_index_filenames` while an index named with '/'
was being dropped, but that check runs only for the initial `ALTER`. A replica of a
`Replicated` database with independent `MergeTree` data could replay the setting change
before its own `DROP INDEX` mutation finished, and that mutation then failed forever in
`getIndexFileName`.

An index named with '/' can only have been written with escaping on, so the `DROP INDEX`
paths in `MutateTask` now resolve its files with `getDroppedIndexFileName`, which always
escapes such a name. The drop mutation no longer depends on the current policy, and the
pending-drop rejection in `checkAlterEligibility` is removed.

The same-batch `DROP INDEX` + `MODIFY SETTING` case moves to a separate test tagged
`no-replicated-database`, because a `Replicated` database prohibits mixing replicated and
non-replicated `ALTER` commands (`QUERY_IS_PROHIBITED`), which failed the `DBReplicated` job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +6650 to +6653
/// An index dropped in this batch, or earlier with its `DROP INDEX` mutation still
/// pending, does not block the change: that mutation resolves the files of an index
/// named with '/' with escaping regardless of the current policy
/// (`getDroppedIndexFileName`).

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.

[Blocker] A policy change can reassign the dropped index's files to a surviving index and produce wrong results

The new pending-drop allowance also admits this sequence (both index definitions are valid and have distinct filenames when escaping is enabled):

CREATE TABLE t_policy_collision
(
    k UInt64,
    v UInt64,
    w UInt64,
    INDEX `a/b` v TYPE minmax GRANULARITY 1,
    INDEX `a%2Fb` w TYPE minmax GRANULARITY 1
)
ENGINE = MergeTree ORDER BY k
SETTINGS escape_index_filenames = 1, index_granularity = 8,
         min_bytes_for_wide_part = 0, packed_skip_index_max_bytes = 0,
         add_minmax_index_for_numeric_columns = 0;
INSERT INTO t_policy_collision
SELECT number, 0, 1 FROM numbers(100)
SETTINGS materialize_skip_indexes_on_insert = 1;
SYSTEM STOP MERGES t_policy_collision;
ALTER TABLE t_policy_collision DROP INDEX `a/b`
SETTINGS alter_sync = 0, mutations_sync = 0;
ALTER TABLE t_policy_collision MODIFY SETTING escape_index_filenames = 0;
SELECT count() FROM t_policy_collision WHERE w = 1 SETTINGS use_skip_indexes = 1;
SELECT count() FROM t_policy_collision WHERE w = 1 SETTINGS use_skip_indexes = 0;

Source trace: the dropped index's files are skp_idx_a%2Fb.*, while the surviving index was written as skp_idx_a%252Fb.*. After the setting change, the survivor resolves to skp_idx_a%2Fb.*. Those files and marks are in the part's checksums, and the UInt64 type check passes, so getDeserializedFormat accepts the dropped index's [0, 0] granules as an index over w. Consequently w = 1 can prune all 100 matching rows, and secondary_indices_materialized incorrectly certifies the survivor. The surviving-file protection in collectFilesForRenames also preserves the misattributed files when the drop mutation runs.

Please ensure that changing the filename policy cannot assign an existing index's files to another logical index, including files of pending drops, and add a regression comparing indexed and unindexed results for this case. This reproduction was traced through the current sources, not executed locally.

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.

🕵 Fixed in 8b63351. MergeTreeData::checkAlterEligibility now rejects (for the initial ALTER) a change of escape_index_filenames when the new file name of a surviving index equals the file name under which the data of another index is still stored: an index the table has now (including one dropped in the same batch) or an index whose DROP INDEX mutation has not finished. Once the drop mutation has removed the files, the change is allowed.

This covers your sequence (a/b pending drop, a%2Fb surviving, escaping turned off) and the same collision in the other direction without any pending drop (a b and a%20b with escaping turned on, which was reachable before this PR too). The regression test 05843_alter_escape_index_filenames_collision checks both, comparing use_skip_indexes = 1 against use_skip_indexes = 0 before and after.

Verified locally: 05843, 05508, 05509, 05137 and 04650 pass on a build of the merged tree; 04700 was only run up to its replicated half, which needs ZooKeeper.

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.

[Blocker] The original collision remains reachable after cancelling the drop mutation on 8b63351d7945.

Using the first table/setup from 05843_alter_escape_index_filenames_collision.sql, stop after its DROP INDEX at line 28 and run:

KILL MUTATION
WHERE database = currentDatabase() AND table = 't_policy_collision'
FORMAT Null;
ALTER TABLE t_policy_collision MODIFY SETTING escape_index_filenames = 0;
SELECT count() FROM t_policy_collision WHERE w = 1 SETTINGS use_skip_indexes = 1;
SELECT count() FROM t_policy_collision WHERE w = 1 SETTINGS use_skip_indexes = 0;

StorageMergeTree::killMutation erases the entry from current_mutations_by_version at src/Storages/StorageMergeTree.cpp:1905 and removes the mutation file; it does not remove the index files or restore the dropped definition. Merges are still stopped, so the original part still owns skp_idx_a%2Fb.*. However, src/Storages/MergeTree/MergeTreeData.cpp:6859-6864 can no longer discover a/b, and the remaining metadata contributes only skp_idx_a%252Fb to the map. The settings change consequently passes, and a%2Fb reads the dropped index's [0, 0] granules over w, allowing the indexed count to be 0 instead of 100. The new column also reports that misattributed index as materialized.

There is a second gap in the same ownership guarantee on Replicated-database followers: the entire check is initial-query-only at MergeTreeData.cpp:6811, while unfinished mutations are local. With ordinary MergeTree tables, an empty initiator can finish the drop and accept the setting change while a populated follower has merges stopped and still owns the dropped index's files. The follower replays the setting change without the collision check and reaches the same wrong-result state. Simply rejecting the replay would instead strand an already-committed DDL entry.

Please base the safety guarantee on ownership that remains valid after cancellation and across replicas, rather than treating the initiator's unfinished-mutation list as proof that colliding files are gone. These are source-level traces; I did not execute them locally.

@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
alexey-milovidov and others added 2 commits November 22, 2026 06:18
Conflicts in `StorageMergeTree.cpp` and `StorageReplicatedMergeTree.cpp`: master replaced
`StorageInMemoryMetadata::settings_changes` with `getSettingsChanges` next to the lines where
this PR calls `applyEscapeIndexFilenamesFromSettings`. Both are kept; the check in
`MergeTreeData::checkAlterEligibility` is adapted to `getSettingsChanges` as well.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…gns index files

Changing `escape_index_filenames` changes the file name of every skip index whose name needs
escaping. If the new file name of one index is the name under which the files of another index
are still stored in the parts, those files (owned by the part, with marks) pass
`getDeserializedFormat` and are read as granules of the wrong index: wrong query results, and
`system.parts.secondary_indices_materialized` reports an index that was never built.

For example, with escaping on, `a/b` is stored as `skp_idx_a%2Fb` and `a%2Fb` as
`skp_idx_a%252Fb`. After `DROP INDEX \`a/b\`` with the mutation still pending, disabling
escaping made `a%2Fb` resolve to `skp_idx_a%2Fb`. The same happens in the other direction
between two existing indices, `a b` and `a%20b`, when escaping is enabled.

`MergeTreeData::checkAlterEligibility` now rejects (for the initial `ALTER`) a change of the
policy when the new file name of a surviving index equals the stored file name of another index
of the table - including the ones dropped in the same batch - or of an index whose `DROP INDEX`
mutation has not finished.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 8b63351:

  • Merged the latest master and resolved the conflicts in StorageMergeTree.cpp and StorageReplicatedMergeTree.cpp (master replaced StorageInMemoryMetadata::settings_changes with getSettingsChanges next to the lines this PR adds).
  • Addressed the open review thread: a change of escape_index_filenames is rejected when it would make one skip index resolve to the files of another one (details in the thread reply), with the new test 05843_alter_escape_index_filenames_collision.

The only red on the previous head was the review-threads gate in Finish Workflow, which skipped the full CI suite because of that thread.

ALTER TABLE t_policy_collision_enable MODIFY SETTING escape_index_filenames = 1; -- { serverError BAD_ARGUMENTS }

-- Dropping the other index in the same batch does not remove its files yet.
ALTER TABLE t_policy_collision_enable DROP INDEX `a%20b`, MODIFY SETTING escape_index_filenames = 1; -- { serverError BAD_ARGUMENTS }

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.

[Major] This assertion fails in the DBReplicated stateless runs: the test has no no-replicated-database tag, but the batch mixes replicated DROP INDEX with non-replicated MODIFY SETTING. validateReplicatedDatabaseSegments rejects it with QUERY_IS_PROHIBITED at src/Interpreters/InterpreterAlterQuery.cpp:401, before the collision validation can produce the expected BAD_ARGUMENTS.

Please move this mixed-batch assertion to a separate test tagged no-replicated-database, following 05509_alter_escape_index_filenames_drop_slash_index_same_batch.sql. Keep the separate-statement collision cases here so they retain DBReplicated coverage.

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-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add status to reflect if secondary indices in a part are fully materialized

7 participants