Repository navigation
Conversation
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.
|
Workflow [PR], commit [8a54979] Summary: ❌
AI ReviewSummaryThis PR correctly threads the replay exemption through the replicated metadata paths and the new Missing context / blind spots
Findings❌ Blockers
Final VerdictLLVM Coverage ReportMeasured on commit 8a54979.
Changed lines: Changed C/C++ lines covered: 152/163 (93.25%) · Uncovered code |
|
The new check catches the mismatch at On Repro sketch (two builds needed, so stated rather than attached: pre-PR build, then this PR's head): create on the pre-PR build A fix shape that keeps the intent: enforce the check only for indexes that are new or changed relative to |
Build profile diff (arm_release)Comparing commit See the job log for details. |
|
A replication-replay residual worth considering before merge: the new mistyped- On a table that already carries the now-rejected index (created before this fix), that has two consequences:
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 |
`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.
This comment was marked as low quality.
This comment was marked as low quality.
| return {}; | ||
|
|
||
| std::set<String> referenced_aliases; | ||
| collectAliasColumnsInExpression(index_expression, columns, referenced_aliases); |
There was a problem hiding this comment.
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.
This comment was marked as low quality.
This comment was marked as low quality.
This comment was marked as low quality.
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.
This comment was marked as low quality.
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.
|
This PR is full of AI slop, sorry. |
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]>
Closes: #111643
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A text index over an
ALIAScolumn whose declared type differs from the type its expression produces is now rejected atCREATE/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
gives
with no
Indexessection at all - the index is not merely ineffective, it never enters the plan.Why. Reading the column applies an implicit
CASTto the declared type (QueryAnalyzer.cpp:4566), whileIndexDescription::initExpressionInfoexpands the alias without one. So the index is built overJSONExtractKeys(event)of typeArray(String), and the query asks about_CAST(JSONExtractKeys(event), 'String').MergeTreeIndexConditionText::hasIndexForColumnmatches predicate to index by column name; the two names never agree, the atom becomesFUNCTION_UNKNOWN,alwaysUnknownOrTrue()returns true, andReadFromMergeTreenever 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:Why the check is this narrow. The issue asks for an error on the
ALIAStype mismatch itself. That is not viable:create/table.mdxstates 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"system.metric_logdeclares its per-metricALIAScolumns asUInt64over anInt64-valued map (BucketedMetricLog.cpp), so it would fail to createx UInt32 ALIAS y + 1a mismatch alreadyNor does it apply to every index type.
KeyConditionrecognises_CASTas a pure type conversion, sominmaxandsetcan 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.attachis 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 inindex.column_nameshas the alias already expanded, so it is identical whether or not the declared type matched (system.data_skipping_indicesreportsJSONExtractKeys(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
ALIASstill converts as before, and the reference file was diffed byte-for-byte against real output.Workflow [PR]
Sync PR [sync-upstream/pr/118003]