Repository navigation
Add secondary_indices_materialized column to system.parts - #89350
aryan32agrawal wants to merge 52 commits into
Conversation
…rialized secondary indices in a part.
|
Edit the title, please. |
|
We need tests for sure. |
|
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. |
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.
secondary_indices_materialized column to system.parts
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]>
|
Rebased on current
The implementation was also updated to the current |
|
Workflow [PR], commit [8b63351] Summary: ❌
AI ReviewSummaryThe PR adds Findings❌ Blockers
|
…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
|
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 ( Root cause: It cannot recur on 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 |
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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]>
# 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]>
…licated` database The test mixes replicated and non-replicated `ALTER` commands in a single query, which `DatabaseReplicated` rejects with `QUERY_IS_PROHIBITED`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=89350&sha=408fa1f388cf9bfa451c49701cfbca4fcc34cc63&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%202%2F2%29 ClickHouse#89350 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed b60b7b9:
The |
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]>
# 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]>
… 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]>
| /// 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`). |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
[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.
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]>
|
🕵 Pushed 8b63351:
The only red on the previous head was the review-threads gate in |
| 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 } |
There was a problem hiding this comment.
[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.
Changelog category:
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
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
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_filenamessemantics of the new column, CI (under the randomized MergeTree settingauto_statistics_types) exposed an unrelated pre-existing bug, fixed here as well:In the settings-alter branch of
StorageMergeTree::alterandStorageReplicatedMergeTree::alter,changeSettingsis the sole writer of the setting-derived fieldsStorageInMemoryMetadata::escape_index_filenamesandIndexDescription::escape_filenames. When the table carries an explicitauto_statistics_typessetting, the subsequentsetInMemoryMetadatacall that re-commits the implicit statistics writes back a metadata copy that was taken beforechangeSettings(commands.applynever sets those fields), soALTER 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 theareNonReplicatedAlterCommandsbranch ofStorageReplicatedMergeTree::alteralready 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
ALTERthat includesMODIFY SETTING escape_index_filenames(for example together withMODIFY COMMENT, or with a replicated command) republished a metadata copy taken beforechangeSettingsand so reverted the index filename policy in memory until a server restart, in bothStorageMergeTree::alterandStorageReplicatedMergeTree::alter. The policy is now re-applied from the committedescape_index_filenamessetting throughMergeTreeData::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.txtis an orphan of the released bug Mutations viaMutateAllPartColumnsTaskwritechecksums.txtwithout hardlinked skip-index files #109595 and the index still has to be rebuilt, while a packed substream (a member ofskp_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 callMergeTreeIndexReadermakes, 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 astextis 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 checkserver_data_manipulation_in_stateless_testsforbids modifying the server's data on disk in stateless tests, which run against arbitrary server configurations.Additional fixes (2026-09-08)
IMergeTreeIndex::getDeserializedFormat- the gateMergeTreeDataSelectExecutor::filterMarksUsingIndex,MergeTreeReadTask::getIndexReadTaskForReadStepandMergeTreeIndexReaderall 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 atextindex 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::hasMaterializedSecondaryIndexis just that verdict, sosecondary_indices_materializedcannot 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 theRESET SETTINGform) 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 wheregetIndexFileNamethrewBAD_ARGUMENTSfrom every read path and from a plainSELECTonsystem.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)
escape_index_filenamesrejection inMergeTreeData::checkAlterIsPossibleapplies to the initialALTERonly (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.indexFileExistsInChecksumsrequires actualskp_idx.packedmembership (DataPartStorageOnDiskBase::isFileInPackedSkipIndicesArchive) instead of the genericexistsFile, which falls back to a loose file on disk. A strayskp_idx_*file next to the archive that is in neitherchecksums.txtnor 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)
escape_index_filenamesis rejected (for the initialALTER) 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 whoseDROP INDEXmutation has not finished. Otherwise the files of that other index would be read as granules of the surviving one (for examplea/bis stored asskp_idx_a%2Fbwith escaping on, which is whata%2Fbresolves to with escaping off), giving wrong query results. Test:05843_alter_escape_index_filenames_collision.Workflow [PR]
Sync PR [sync-upstream/pr/89350]