Skip to content

Reject a text index over an ALIAS column of a mismatched type - #118003

Closed
navneet83 wants to merge 18 commits into
ClickHouse:masterfrom
navneet83:fix-text-index-on-mistyped-alias
Closed

navneet83 wants to merge 18 commits into
ClickHouse:masterfrom
navneet83:fix-text-index-on-mistyped-alias

Conversation

@navneet83

@navneet83 navneet83 commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Closes: #111643

Changelog category (leave one):

  • Backward Incompatible Change

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

A text index over an ALIAS column whose declared type differs from the type its expression produces is now rejected at CREATE/ALTER. Such an index could never be used, so it was silently built and never read. Existing tables keep loading.

Documentation entry for user-facing changes

CREATE TABLE event_test
(
    event String,
    paths String ALIAS JSONExtractKeys(event),   -- expression is Array(String)
    INDEX fts_paths paths TYPE text(tokenizer = array)
) ENGINE = MergeTree ORDER BY tuple();

EXPLAIN indexes = 1 SELECT event FROM event_test WHERE hasAllTokens(paths, ['xoo']);

gives

Filter column: hasAllTokens(CAST(JSONExtractKeys(event) AS String), ['xoo'])
└──ReadFromMergeTree (default.event_test)
      Parts: 1 | Granules: 1

with no Indexes section at all - the index is not merely ineffective, it never enters the plan.

Why. Reading the column applies an implicit CAST to the declared type (QueryAnalyzer.cpp:4566), while IndexDescription::initExpressionInfo expands the alias without one. So the index is built over JSONExtractKeys(event) of type Array(String), and the query asks about _CAST(JSONExtractKeys(event), 'String'). MergeTreeIndexConditionText::hasIndexForColumn matches predicate to index by column name; the two names never agree, the atom becomes FUNCTION_UNKNOWN, alwaysUnknownOrTrue() returns true, and ReadFromMergeTree never adds the index. The index files are still written and merged, so the cost is paid and nothing reads them.

Declaring the column Array(String) makes the analyzer skip the cast and the index is used, which confirms the cast is the sole cause:

   Parts: 0 | Granules: 0
   Indexes:
     Skip
       Name: fts_paths
       Condition: (mode: All; tokens: ["xoo"])
       Parts: 0/1
       Granules: 0/1

Why the check is this narrow. The issue asks for an error on the ALIAS type mismatch itself. That is not viable:

  • it is documented behaviour - create/table.mdx states that when a type and a default expression are both given, "an implicit type casting function inserted which converts the expression to the specified type"
  • the server's own bucketed system.metric_log declares its per-metric ALIAS columns as UInt64 over an Int64-valued map (BucketedMetricLog.cpp), so it would fail to create
  • arithmetic widening makes the common x UInt32 ALIAS y + 1 a mismatch already

Nor does it apply to every index type. KeyCondition recognises _CAST as a pure type conversion, so minmax and set can see through it and may work today; rejecting those would break working schemas. Only the text index matches purely by name, so only it is checked.

attach is exempt so that tables already carrying such an index keep loading.

Implementation note. The alias has to be found through definition_ast: the expression stored in index.column_names has the alias already expanded, so it is identical whether or not the declared type matched (system.data_skipping_indices reports JSONExtractKeys(event) for both spellings) and cannot be used to detect this.

Verification. Built locally and checked by running: the repro reproduces, the counterfactual uses the index, the fix rejects the mismatched schema and accepts the matching one, an un-indexed ALIAS still converts as before, and the reference file was diffed byte-for-byte against real output.


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

A text index over an ALIAS column whose declared type differs from the type its
expression produces can never be used. Reading the column applies an implicit
`CAST` to the declared type, while `IndexDescription::initExpressionInfo` expands
the alias without one, so the index is built over `JSONExtractKeys(event)` of type
`Array(String)` while the query asks about `_CAST(JSONExtractKeys(event), 'String')`.
`MergeTreeIndexConditionText::hasIndexForColumn` matches by column name, the two
names never agree, the atom becomes `FUNCTION_UNKNOWN`, and `alwaysUnknownOrTrue`
keeps the index out of the plan entirely - `EXPLAIN indexes = 1` shows no `Indexes`
section at all. The index files are still written and merged, so the cost is paid
and nothing reads them.

Reject that at `CREATE` and `ALTER` instead. `attach` is exempt so that tables
already carrying such an index keep loading.

The check is deliberately narrow. Making the declared/expression mismatch an error
in general is not possible: the implicit conversion is documented behaviour for
`DEFAULT`, `MATERIALIZED` and `ALIAS` alike, the server's own bucketed
`system.metric_log` declares `UInt64` aliases over an `Int64` map, and arithmetic
widening makes `x UInt32 ALIAS y + 1` a mismatch already. Nor does it apply to all
index types: `KeyCondition` recognises `_CAST` as a pure type conversion, so
`minmax` and `set` indexes can see through it. Only the text index matches purely
by name, so only it is checked.

The alias has to be found through `definition_ast`, because the expanded expression
stored in `index.column_names` is identical whether or not the declared type matched.
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8a54979]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR correctly threads the replay exemption through the replicated metadata paths and the new Shared Catalog replay checks, but the final narrowing in findMistypedAliasColumnsOfIndex reopens the same silent unusable-index shape one alias hop away. I would not merge it in the current form.

Missing context / blind spots
  • ⚠️ The new #if CLICKHOUSE_CLOUD Shared Catalog replay branches were only validated by code inspection here; this PR does not add runtime coverage for that path.
Findings
❌ Blockers
  • [dismissed by author -- https://github.com/Reject a text index over an ALIAS column of a mismatched type #118003#discussion_r3938378856] [src/Storages/MergeTree/MergeTreeData.cpp:1153-1155] Accepting only "direct" mistyped aliases still leaves a dead exact-name index reachable through a well-typed alias that expands through a mistyped one. IndexDescription::initExpressionInfo expands the full alias chain before filling expression_list_ast and sample_block (src/Storages/IndicesDescription.cpp:175-194), while alias columns are still lowered through their resolved expressions and get a CAST on any mistyped link (src/Analyzer/Resolve/QueryAnalyzer.cpp:4648-4654, src/Planner/PlannerActionsVisitor.cpp:843-852). In a String ALIAS JSONExtractKeys(event), b String ALIAS toJSONString(a), INDEX i b TYPE tokenbf_v1(...), the stored index key is built from the expanded expression, but hasToken(b, ...) still resolves through the inner cast on a, so the exact-name matcher misses for the same reason as the original bug. The new t_indirect acceptance in 05077 therefore bakes a silent unusable index back in. Suggested fix: keep the tuple exemption if you want it, but follow referenced aliases through their ALIAS bodies again and restore a regression that proves EXPLAIN indexes = 1 on hasToken(b, ...) only succeeds when every alias in the expanded chain is type-consistent.
Final Verdict

⚠️ Changes requested.

LLVM Coverage Report

Measured on commit 8a54979.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 152/163 (93.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Sep 4, 2026
@navneet83 navneet83 added the can be tested Allows running workflows for external contributors label Sep 4, 2026
@zlareb1

zlareb1 commented Sep 4, 2026

Copy link
Copy Markdown
Member

The new check catches the mismatch at CREATE / ALTER ADD INDEX time, but because it runs inside checkProperties gated only on attach, it also re-validates indexes that already exist and are untouched by the operation. checkAlterIsPossible calls checkProperties with attach = false (MergeTreeData.cpp:5975 at current master), and the new block iterates every index in new_metadata without comparing against old_metadata. So a table that already carries a mismatched-ALIAS text index — exactly the pre-existing population the attach exemption grandfathers — keeps loading after the upgrade, but every subsequent ALTER on it is rejected with BAD_ARGUMENTS, including operations that do not touch the index at all (ADD COLUMN, MODIFY TTL, ...). On plain MergeTree this is loud and recoverable: DROP INDEX passes, since the index is no longer in new_metadata.

On ReplicatedMergeTree the same re-validation runs on the replica side of a committed ALTER_METADATA entry: StorageReplicatedMergeTree::setTableStructure calls setProperties(new_metadata, old_metadata) (StorageReplicatedMergeTree.cpp:1892), setProperties defaults attach to false (MergeTreeData.h:1893), and setProperties funnels straight into checkProperties (MergeTreeData.cpp:1447). In a rolling upgrade, a replica still on the old version can validate and commit an unrelated ALTER to the replication log; the upgraded replica then throws an exception while applying the entry and retries forever, and since ALTER_METADATA entries apply in metadata-version order, the fixing DROP INDEX queues behind the stuck entry — replication for that table wedges on the upgraded replica until manual intervention. The changelog statement that existing tables keep loading is true but incomplete: they load, and then cannot be altered.

Repro sketch (two builds needed, so stated rather than attached: pre-PR build, then this PR's head): create on the pre-PR build CREATE TABLE t (event String, paths String ALIAS JSONExtractKeys(event), INDEX fts_paths paths TYPE text(tokenizer = array)) ENGINE = MergeTree ORDER BY () with allow_experimental_full_text_index = 1; restart into the PR build — the table attaches; then ALTER TABLE t ADD COLUMN x UInt8 fails with the new BAD_ARGUMENTS. For the replicated variant, run the ALTER from a not-yet-upgraded replica and watch the ALTER_METADATA entry stick in system.replication_queue on the upgraded one.

A fix shape that keeps the intent: enforce the check only for indexes that are new or changed relative to old_metadata.secondary_indices (the parameter is already in scope), or allow the case where an identical index declaration already existed in old_metadata.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 8a54979d3759729aa724d31c830b15feeccfcd3b with master failed: RuntimeError: CI logs cluster query failed: SELECT file, quantileExactWeightedInterpolated(0.5)(pr_….

See the job log for details.

@zlareb1

zlareb1 commented Sep 4, 2026

Copy link
Copy Markdown
Member

A replication-replay residual worth considering before merge: the new mistyped-ALIAS check consults only new_metadata and fires whenever attach == false (MergeTreeData.cpp:1206-1234 at 2bc9ec1), so it also fires when a replica applies a replicated ALTER_METADATA queue entry — StorageReplicatedMergeTree::setTableStructure (StorageReplicatedMergeTree.cpp:1874-1893) calls setProperties(new_metadata, old_metadata) with the default attach = false (MergeTreeData.h:1890-1894).

On a table that already carries the now-rejected index (created before this fix), that has two consequences:

  1. Any unrelated ALTER (e.g. ADD COLUMN) is rejected with the new BAD_ARGUMENTS until the user drops the index or fixes the column type. Fail-closed and actionable — presumably intended given the Backward Incompatible Change label.
  2. Sharper: during a mixed-version rolling upgrade, a not-yet-upgraded replica can still initiate any ALTER on such a table (its own checks pass) and commit the new metadata to ZooKeeper; an upgraded replica then throws inside setTableStructure while applying the ALTER_METADATA entry, and the entry retries indefinitely. Because alter application is ordered, the fixing ALTER ... DROP INDEX queues behind the stuck entry, so the upgraded replica is wedged until manual intervention.

The adjacent one-text-index-per-column check just above has the same replay property, so this widens an existing class rather than creating a new one — but this check is much easier to hit retroactively, since the broken schema loads fine today and the mismatch is otherwise silent.

Both residuals disappear if the check rejects only newly introduced mismatches — e.g. skip it when old_metadata already contains an identical index definition, so existing tables keep altering (and keep paying only the dead-index cost) while new definitions are rejected everywhere.

@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 4, 2026
`checkProperties` is not only the create path. `checkAlterIsPossible` calls it for
every `ALTER` with `attach = false`, and `StorageReplicatedMergeTree::setTableStructure`
reaches it through `setProperties`, whose `attach` defaults to false, when applying a
committed `ALTER_METADATA` entry. Validating every index in `new_metadata` therefore
re-checked indexes the operation does not touch: a table grandfathered by the `attach`
exemption kept loading but then rejected unrelated `ALTER`s such as `ADD COLUMN`, and on
a replicated table an upgraded replica would fail to apply an entry committed by an
older one and retry it forever, with the `DROP INDEX` that would fix it queued behind.

Skip any index that is unchanged relative to `old_metadata`, compared by name and by
`definition_ast->getTreeHash(ignore_aliases = true)`.

The create path needs care: `MergeTreeData`'s constructor calls
`setProperties(metadata_, metadata_, ...)` with the same object as both arguments, so
"present in `old_metadata`" is only meaningful when the two differ. Without that guard
the exemption swallowed the check entirely and a mismatched index was accepted again.

Test the grandfathered contract directly rather than only asserting it: `ATTACH` a table
carrying such an index, then run an unrelated `ALTER` on it.
…ration

Skipping any index whose own declaration is unchanged was too coarse. `ALTER TABLE ...
MODIFY COLUMN` retypes the ALIAS column without touching the index, so it introduces
exactly the mismatch this check exists to reject while the index declaration hashes
identically - and the previous commit let it through. Verified against the built binary:
`MODIFY COLUMN paths String ALIAS JSONExtractKeys(event)` on a table with a matching
`Array(String)` alias silently produced the unusable index.

Extract the detection into `findMistypedAliasColumnOfTextIndex` and compare its result
between `new_metadata` and `old_metadata`. The exemption now means what the grandfathering
contract actually needs - "this operation inherited the violation rather than introducing
it" - and no longer depends on which half of the (index, column) pair was edited.

Cover both directions in the test: `MODIFY COLUMN` into a mismatch is rejected, and on a
table that already carries one an unrelated `ADD COLUMN` still succeeds and `DROP INDEX`
remains available as the escape hatch.
Keying the exemption on the index name plus the offending column name was too loose in
the opposite direction to the previous commit. Both halves of the pair can be rewritten
while those two names stay put:

    ALTER TABLE t MODIFY COLUMN paths String ALIAS splitByChar(',', event);
    ALTER TABLE t DROP INDEX fts_paths, ADD INDEX fts_paths paths TYPE text(tokenizer = splitByNonAlpha);

On a table grandfathered by the `attach` exemption both were accepted, and each leaves
behind a freshly built unusable index - the outcome the check exists to prevent, reached
through the exemption meant to protect tables that already had one.

A violation is produced by three things together: the index declaration, the column's
declared type, and the alias expression. Compare all three, so the exemption covers
exactly the case it is for - metadata carried over untouched - and editing any one of
them is caught.

Both statements above are now in the test, alongside the unrelated `ADD COLUMN` and the
`DROP INDEX` escape hatch that must keep working on the same table.
The check only recognised `INDEX idx alias_col`, so any wrapper over a mistyped ALIAS
introduced the same dead index unnoticed:

    m Map(String, String),
    a Map(String, FixedString(3)) ALIAS m,
    INDEX idx mapValues(a) TYPE text(tokenizer = array)

The mismatch belongs to the column rather than to the index expression. `a` is unusable
under a text index however it is spelled: `initExpressionInfo` expands the ALIAS so the
index is built on `mapValues(m)`, while query analysis reads `a` through a `CAST` to the
declared type and asks for `mapValues(_CAST(m, ...))`, and the two names never meet.

So every identifier in the index expression is examined, and for each ALIAS among them the
declared type is compared against the type its own expression produces, resolved through
the `TreeRewriter` / `ExpressionAnalyzer` path `IndexDescription::initExpressionInfo` uses.
Two consequences worth naming:

  * The create path has no context of its own - `setProperties` defaults `local_context`
    to null and the constructor takes that default - so it falls back to `getContext()`.
    Without that the check silently did nothing on `CREATE`, the path that matters most.
  * It fails open. A type that cannot be resolved is not reported. This check is a
    convenience and must never be the reason a legitimate statement fails.

The inherited-violation test grew two comparisons to match: the resolved `data_types`,
which `MODIFY COLUMN` on a column the ALIAS is written in terms of changes while every AST
stays put, and the offending column's own declared type and alias expression, which can be
rewritten while the resolved types stay identical.

Verified against the built binary, thirteen cases: the six from before, a wrapped
expression over a mistyped ALIAS, retyping a dependency of a grandfathered ALIAS, and four
negative controls - a wrapper over a correctly typed ALIAS, a bare correctly typed ALIAS, a
plain column, and a wrapped expression with no ALIAS at all - none of which may be rejected.
`check_catch_all` in the style job rejects a `catch (...)` that neither rethrows, logs,
saves the exception nor explains itself. This one does swallow deliberately: a type the
check cannot resolve is simply not reported, matching the null returns above it, so that
a text index this code fails to reason about never becomes the reason a legitimate
statement fails. Said so in the comment the check looks for.
@navneet83

This comment was marked as low quality.

return {};

std::set<String> referenced_aliases;
collectAliasColumnsInExpression(index_expression, columns, referenced_aliases);

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 still only checks aliases that appear in the original index AST, not mistyped aliases hidden inside another ALIAS definition. A minimal case is

CREATE TABLE t
(
    event String,
    a String ALIAS JSONExtractKeys(event),
    b String ALIAS toJSONString(a),
    INDEX idx b TYPE text(tokenizer = splitByNonAlpha)
) ENGINE = MergeTree ORDER BY tuple();

collectAliasColumnsInExpression sees only b, and tryGetAliasExpressionType("b") returns String, so the new check accepts this schema. But IndexDescription::initExpressionInfo still builds the index over toJSONString(JSONExtractKeys(event)), while query analysis reads b through the inner alias cast, i.e. toJSONString(CAST(JSONExtractKeys(event) AS String)). MergeTreeIndexConditionText matches by the full column name, so this index stays unreachable for the same reason as the direct paths case.

To close the invariant, the check needs to follow chained ALIAS bodies and reject the index if any alias in that expanded dependency tree is mistyped, not just the aliases named in the top-level index expression.

`bugprone-inc-dec-in-conditions` is enabled and fatal in the tidy build, and it fires on
the plain indexed loop this comparison was written as: the loop variable is both
incremented and read in the condition, which the check flags regardless of the loop being
an ordinary one. Expressing the comparison as `std::ranges::equal` with a predicate drops
the index, the separate size check and the diagnostic together.

All thirteen cases still behave as before against the rebuilt binary.
Two holes on either side of the check, both in what it considered an ALIAS reference.

It walked the index expression without regard for scope, so a lambda parameter that
happened to share a name with an ALIAS column was read as a reference to it:

    x String ALIAS JSONExtractKeys(event),
    arr Array(String),
    INDEX idx arrayMap(x -> lower(x), arr) TYPE text(tokenizer = array)

is an index over `arr` and perfectly usable, and it was rejected because the walk saw the
lambda's own `x`. Lambda parameters are now masked while the body is visited, the way
`ReplaceAliasByExpressionMatcher` masks them for the same reason.

The other way round, it only looked at the ALIAS columns named in the index expression,
while the index is built over the chain fully expanded. With

    a String ALIAS JSONExtractKeys(event),
    b String ALIAS toJSONString(a),
    INDEX idx b TYPE text(tokenizer = splitByNonAlpha)

`b` is typed consistently with its own expression, so nothing was reported, but the index
is built over `toJSONString(JSONExtractKeys(event))` while a query reads `b` through the
cast on `a` - unreachable for exactly the original reason. The referenced aliases are now
followed through their own definitions, with a visited set for a cycle.

Sixteen cases run against the built binary. The two above are the new ones, alongside a
chain of correctly typed aliases that must still be accepted.
The inherited-violation test proved the index declaration, the resolved types and the
mistyped ALIAS columns were unchanged, which says nothing about a correctly typed ALIAS
sitting between the index and the mistyped one. On a grandfathered table

    a String ALIAS JSONExtractKeys(event),
    b String ALIAS toJSONString(a),
    INDEX idx b TYPE text(tokenizer = splitByNonAlpha)

`ALTER TABLE ... MODIFY COLUMN b String ALIAS toString(a)` left all three identical - `b`
is typed consistently with its own expression either way, and `a` never moved - while the
index was rebuilt over `toString(JSONExtractKeys(event))` instead.

`IndexDescription::expression_list_ast` is the expression with every ALIAS already
expanded, so comparing it settles the whole chain at any depth in one place, and replaces
the per-alias comparison of declared types and definitions. The index declaration is still
compared beside it: the expanded expression carries no index type, so replacing the index
under its own name with a different tokenizer leaves it untouched - which the test caught
when this comparison was first written on its own.

Eighteen cases against the built binary, the two new ones being the retyped middle link
and an unrelated `ADD COLUMN` on the same table.
A violation is decided by six things: the index name, its declaration, the expression it
resolves to with ALIASes expanded, the types that expression produces, which ALIASes among
them are mistyped, and the declared type of each of those. The predicate compared the first
five, and the sixth is reachable on its own: `MODIFY COLUMN a Array(FixedString(3)) ->
Array(FixedString(2))` over the same expression leaves the declaration, the expanded
expression, the resolved types and the offending column name all identical, while the column
is now read through a different `CAST` - a fresh unusable index, not an inherited one.

That list is now written down beside the predicate, because comparing a subset of it is what
made this check wrong in each of the previous rounds; every omission turned out to be
reachable by an `ALTER` that leaves the rest alone.

Twenty-one cases against the built binary. The three new ones follow the list rather than the
reported example: retyping the offending ALIAS is rejected, an unrelated `ADD COLUMN` on the
same table still works, and retyping it to the type its expression produces is accepted,
since that removes the violation instead of replacing it.
@navneet83

This comment was marked as low quality.

@zlareb1

This comment was marked as low quality.

…istyped

The helper already returns each offending ALIAS with the type its expression produces, and
the predicate compared only the names. An index expression can normalise a change to that
type away: with `INDEX idx arrayMap(x -> lower(x), a)` over `a Array(FixedString(3)) ALIAS
mapValues(m)`, retyping `m` to `Map(String, FixedString(2))` leaves the index declaration,
the expanded expression, the resolved index types and the declared type of `a` all equal,
because `lower` maps `FixedString` back to `String` - while the `CAST` the column is read
through has changed. Comparing the map rather than its keys closes it, using a value that
was already in hand.

That makes seven inputs, and the enumeration beside the predicate now says so.

Twenty-three cases against the built binary; the new one is the normalised dependency
retype, with the unrelated `ADD COLUMN` beside it.
@navneet83

This comment was marked as low quality.

The reject was gated to TYPE text, but the defect belongs to the matching mechanism, not
the type: any index condition that matches a query predicate to the indexed expression by
its exact column name is defeated by the CAST a mistyped ALIAS is read through. That is
MergeTreeIndexConditionText (text), MergeTreeConditionBloomFilterText (tokenbf_v1,
ngrambf_v1, sparse_grams) and MergeTreeIndexConditionBloomFilter (bloom_filter), and the
reject now covers all five. minmax stays allowed because KeyCondition traverses the cast
and the index works whenever the cast is monotonic; set stays allowed because it matches
the expression DAG through the cast.

The reject must also not run while applying an already-committed ALTER_METADATA entry: a
replica running a version without the check can commit the violation, entries execute in
version order, and an upgraded replica rejecting the entry wedges its replication queue
behind it. setTableStructure is only reached from executeMetadataAlter, which applies a
committed entry by construction, and outside a Replicated database it has no query context
that could carry that fact, so setProperties gains an explicit is_metadata_replay that only
this check consumes. The create-side replays were already exempt - attach here means
mode > LoadingStrictnessLevel::CREATE, which covers lost-replica recovery and RESTORE - with
one exception: SYSTEM RESTORE DATABASE REPLICA re-creates tables at mode CREATE with only
isRecoveryFromStoredMetadata() set, so the constructor's sanity_checks derivation now
consults that flag too, the same way registerStorageMergeTree already does.

The integration test commits the violating ALTER from a release image and asserts the
upgraded replica applies it, keeps replicating, and still rejects a fresh user ALTER.
The index conditions strip LowCardinality before matching (removeLowCardinality in
MergeTreeIndexBloomFilterText and the KeyCondition chain), so an ALIAS declared
LowCardinality(T) over an expression of type T is read through a CAST the index still
matches - the index is not dead. Comparing the declared and expression types with
recursiveRemoveLowCardinality removed keeps rejecting a real type change (String vs
Array(String)) while accepting the LowCardinality wrapper. Without this, a table like
04612_key_condition_nested_cast_lowcardinality (LowCardinality(UInt64) ALIAS over a
numeric key, carrying a bloom_filter skip index) is wrongly refused at CREATE.
Three of the checks around the reject were wider than the mechanism they guard.

The `LowCardinality` exemption is removed. It rested on `removeLowCardinality` appearing in
the matchers, but those calls sit on the value path, not the name-matching path: with a
`LowCardinality(String)` ALIAS over a `String` expression, the query reads
`CAST(lower(event) AS LowCardinality(String))`, none of `text`, `tokenbf_v1`, `ngrambf_v1`,
`sparse_grams` or `bloom_filter` look through it, and `EXPLAIN indexes = 1` shows no skip index
applied at all. The types are now compared by name, exactly as `QueryAnalyzer` decides whether
to insert the `CAST`. `04612` only appeared to need the exemption; its pruning comes from the
primary key, and its `bloom_filter` index over a well-typed ALIAS is left alone by the next
change instead.

Only the ALIAS columns named directly in the index expression are examined; their bodies are
no longer followed. Chasing a mistyped ALIAS through the definition of a well-typed one rejected
indexes that still work, and the indirect case is rarer and harder to characterise. The two
chain-following cases leave `05076` with the behaviour.

Only a single-expression index is examined. A tuple index matches each member independently
(`MergeTreeConditionBloomFilterText` builds `key_tuple_mapping` per member), so a mistyped
member leaves predicates on the others usable and the index is not dead.

`checkAlterIsPossible` now passes the already computed `is_replay_on_another_replica` as
`is_metadata_replay`. A `Replicated` database re-runs an ALTER on every replica and reaches
the reject through this path, not `setTableStructure`, so a follower on a newer version kept
failing an entry an older replica had already committed. The integration test gains that
scenario.

`05077` gains the direct `LowCardinality` rejects for `tokenbf_v1` and `bloom_filter`, an
accepted tuple index with one mistyped member, and an accepted index over a well-typed ALIAS
written in terms of a mistyped one.
…S index check

A Shared Catalog secondary re-executes the initiator's CREATE or ALTER
without a ZooKeeper metadata transaction, so the txn-based replay marker
never fires there and the reject would run against a definition the
initiator already accepted. Detect it through the client-info marker the
statistics check and registerStorageMergeTree already use, both in the
constructor's sanity_checks and in checkAlterEligibility.
@rschu1ze

Copy link
Copy Markdown
Member

This PR is full of AI slop, sorry.

@rschu1ze rschu1ze closed this Sep 17, 2026
@navneet83
navneet83 deleted the fix-text-index-on-mistyped-alias branch September 18, 2026 00:42
ringerc pushed a commit to ringerc/ClickHouse-patches that referenced this pull request Nov 9, 2026
05076 and 05077 are already taken by open pull requests ClickHouse#118128 and ClickHouse#118003,
and 05081/05082 by ClickHouse#117314/ClickHouse#117318, so a merge of any of them would collide.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FTS doesn't work in case of (not checked) wrong type in ALIAS column

3 participants