Repository navigation
Reject a skip index whose expression cannot be evaluated - #118373
alexey-milovidov merged 5 commits into
Conversation
`IndexDescription::initExpressionInfo` records the index expression's sample block from `ExpressionActions::getSampleBlock`, which reports DAG result types and executes nothing, so `equals(String, Int8)` passes overload resolution with result type `UInt8` and a declaration like `INDEX i0 c0 = c1 TYPE set(0)` over a `String` and an `Int8` column is accepted. Merges and mutations build an `ExpressionStep` over that same DAG, whose header goes through `ActionsDAG::updateHeader`, a zero-row dry run of every function, where `getLeastSupertype` throws. The declaration therefore succeeded and afterwards every `INSERT` and every merge of the table failed with `NO_COMMON_TYPE`, while `MATERIALIZE INDEX` left a mutation retrying the same error. Ask that question where the index is declared, in the per-index loop of `MergeTreeData::checkProperties`, by calling `updateHeader` on the expression's own DAG over a zero-row header built from its required columns. This is the call `ExpressionTransform::transformHeader` makes on this DAG during every merge, so an expression a merge accepts cannot be rejected by the new check. Building the header from the expression's own required columns means every DAG input is present by construction. The probe is skipped unless every function node satisfies `isSuitableForConstantFolding`. A function that opts out may do context-dependent work, an access check or a remote call, before it inspects the row count, and this DAG is analyzed with the context of the user running the DDL rather than the storage's, so probing such an expression could answer a different question than a merge would. The check reports only a violation the statement introduces, comparing against the matching index in the old metadata. The pointer comparison against `new_metadata` is required rather than an optimisation, because the create path and the projection recursion both pass the same metadata object as both arguments, and without it a newly declared index would find itself in the old metadata and never be rejected. Together with the `attach` gate this keeps a table declared before this check loadable and alterable, with `ALTER TABLE ... DROP INDEX` as the repair, and stops a replica wedging its queue on an `ALTER_METADATA` entry it cannot skip. `MergeTreeIndexFactory::validate` was rejected as the site: it is already the `attach`-gated per-index expression validator, but it receives no old metadata, so that exemption is impossible there. `ExpressionActions::execute` with `dry_run` was rejected because `executeImplDryRun` may diverge from real execution in either direction, missing an error a merge raises or raising one it does not; `updateHeader` cannot diverge because it is the merge path's own call. The original exception is rethrown rather than wrapped in `BAD_ARGUMENTS` so the client sees the real cause, and the enclosing handler still prefixes `When validating secondary index`. A dry run decides type errors only. A failure that depends on data values cannot be decided where the index is declared. Co-Authored-By: Claude Opus 5 <[email protected]>
`IndexDescription::initExpressionInfo` records the index expression's sample block from `ExpressionActions::getSampleBlock`, which reports DAG result types and executes nothing, so `equals(String, Int8)` passes overload resolution with result type `UInt8` and a declaration like `INDEX i0 c0 = c1 TYPE set(0)` over a `String` and an `Int8` column is accepted. Merges and mutations build an `ExpressionStep` over that same DAG, whose header goes through `ActionsDAG::updateHeader`, a zero-row dry run of every function, where `getLeastSupertype` throws. The declaration therefore succeeded and afterwards every `INSERT` and every merge of the table failed with `NO_COMMON_TYPE`, while `MATERIALIZE INDEX` left a mutation retrying the same error. Ask that question where the index is declared, in the per-index loop of `MergeTreeData::checkProperties`, by calling `updateHeader` on the expression's own DAG over a zero-row header built from its required columns. This is the same dry run a merge performs: `MergeTask` rebuilds the index expressions from their ASTs under the storage context and hands the combined DAG to `ExpressionStep`, whose header goes through `ExpressionTransform::transformHeader`, which is `updateHeader`. Both DAGs come from the same AST, so they diverge only if a setting changes how a function resolves. Building the header from the expression's own required columns means every DAG input is present by construction. The probe is skipped unless every function node satisfies `isSuitableForConstantFolding`. A function that opts out may do context-dependent work, an access check or a remote call, before it inspects the row count, and this DAG is analyzed with the context of the user running the DDL rather than the storage's, so probing such an expression could answer a different question than a merge would. The check reports only a violation the statement introduces, comparing against the matching index in the old metadata. The pointer comparison against `new_metadata` is required rather than an optimisation, because the create path and the projection recursion both pass the same metadata object as both arguments, and without it a newly declared index would find itself in the old metadata and never be rejected. Together with the `attach` gate this keeps a table declared before this check loadable and alterable, with `ALTER TABLE ... DROP INDEX` as the repair, and stops a replica wedging its queue on an `ALTER_METADATA` entry it cannot skip. `MergeTreeIndexFactory::validate` was rejected as the site: it is already the `attach`-gated per-index expression validator, but it receives no old metadata, so that exemption is impossible there. `ExpressionActions::execute` with `dry_run` was rejected because `executeImplDryRun` may diverge from real execution in either direction, missing an error a merge raises or raising one it does not; `updateHeader` is the merge path's own dry run, so it cannot raise an error the merge's own header computation does not. The original exception is rethrown rather than wrapped in `BAD_ARGUMENTS` so the client sees the real cause, and the enclosing handler still prefixes `When validating secondary index`. A dry run decides type errors only. A failure that depends on data values cannot be decided where the index is declared. A zero-row dry run also decides less than execution does: `defaultImplementationForNulls` returns early for a nullable argument at zero rows (`IFunction.cpp:311-319`), and an expression containing a function that opts out of constant folding is not probed at all. Both stay accepted, exactly as before this change. Co-Authored-By: Claude Opus 5 <[email protected]>
The probe in `MergeTreeData::checkProperties` calls `ActionsDAG::updateHeader` on the index expression's own DAG over a zero-row header. That is the dry run a merge performs: `MergeTask` rebuilds the index expressions from their ASTs under the storage context (`getSingleExpressionForIndices(columns, global_ctx->data->getContext())`) and hands the combined DAG to `ExpressionStep`, whose header goes through `ExpressionTransform::transformHeader`, which is `updateHeader`. The two DAGs are built from the same AST under different contexts, so they diverge only if a setting changes how a function resolves. A zero-row dry run decides less than execution does, and the boundary was pinned nowhere. Cell G of `05080_ill_typed_skip_index_expression` pins it: `INDEX i0 c0 = c1 TYPE set(0)` over a `Nullable` operand stays accepted, because `defaultImplementationForNulls` returns before the comparison runs when no row survives, while the same declaration over `LowCardinality(String)` is rejected. So the boundary is `Nullable` specifically, not wrapped types in general: `LowCardinality(String)` has a non-nullable result type, so the nested comparison is executed even at zero rows, and I measured it rejected on both the `CREATE` and the `ALTER ADD INDEX` path. The rejected `LowCardinality(String)` line is also the cell's positive control, since it is what fails if the probe stops running at all. The gap is defended twice, which is worth recording next to the cell: removing the early return at `IFunction.cpp:311-319` alone does not open it, because `if (rows_without_nulls == 0)` immediately after (`IFunction.cpp:361-365`) reaches the same conclusion when `input_rows_count` is zero. Closing the gap would need a probe that evaluates synthesized values, which refuses valid expressions, so the boundary is documented rather than moved. No behaviour changes here. The only source edit is a comment: the pointer-identity guard is short-circuited by the projection recursion as well as by the create path, since `checkProperties(*projection.metadata, *projection.metadata, ...)` also passes one object in both positions. Co-Authored-By: Claude Opus 5 <[email protected]>
`ALTER TABLE ... RENAME COLUMN` rewrites every non-implicit index's expression AST in the new metadata (`AlterCommands.cpp:1294-1309`), and `IndexDescription`'s copy constructor and assignment deep-clone `definition_ast` (`IndicesDescription.cpp:53`, `:74`), so the old metadata keeps `c0 = c1` while the new one holds `c2 = c1`. Requiring the two definitions to hash equal therefore made a rename fail that comparison by construction, and the pre-existing violation was reported as if the rename had introduced it: a statement master accepts was refused, and the exemption broke its own rule of reporting only a violation the current operation introduces. There is no discriminator available here between a rename and a redeclaration. What separates them is which `ALTER` commands were issued, and `checkProperties` cannot see them: the definition ASTs differ in both cases, the operand types and the required-column types are identical in both cases, and the index expression alone is identical in both cases. So the choice is only between refusing the rename and not re-checking a redeclaration, and the more permissive side is taken. Dropping the comparison leaves the probe of the old index as the sole condition, which still restricts the exemption to an index that was already unevaluable, so an `ALTER MODIFY COLUMN` that breaks a previously valid index is still refused. A redeclaration under the name of an already-unevaluable index is consequently, and knowingly, not re-checked. It leaves the table exactly as broken as it already was, and `DROP INDEX` remains the repair. Cell D6 of `05081_ill_typed_skip_index_expression_attach` now pins that fail-open by asserting the redeclaration actually applies, reading the new type back from `system.data_skipping_indices` rather than only observing that no error was raised, and the new cell D7 pins the rename by asserting the rewritten operand. D7 was also run on the unmodified base binary and produces byte-identical output, which is the point of a regression fix. Both cells were shown able to redden by restoring the comparison, and a variant that drops the old-index probe instead reddens the `ALTER MODIFY COLUMN` cell, so each surviving condition is load-bearing. Co-Authored-By: Claude Opus 5 <[email protected]>
`add_minmax_index_for_numeric_columns` (and its string / temporal / block-number / block-offset siblings) makes the server generate an implicit minmax index per eligible column. For a non-trivial ALIAS column the generated index's expression is the ALIAS body, so `a UInt8 ALIAS c0 = c1` over `c0 String, c1 Int8` yields `auto_minmax_index_a`, whose expression cannot be evaluated. The user declared no index at all, yet the new probe reported that index and refused the statement in three places: * CREATE. `registerStorageMergeTree` adds implicit indices to `metadata.secondary_indices` before this constructor runs `checkProperties`, so the CREATE itself failed. * RENAME COLUMN on a table created before the probe existed. `AlterCommands` does not send an implicit index through the rename visitor, it rebuilds it under the new column's name, so after `RENAME COLUMN a TO b` the new metadata holds `auto_minmax_index_b` while the old metadata still holds `auto_minmax_index_a`. The name-only predecessor lookup found nothing, `inherited` stayed false, and the inherited violation was rethrown. * ADD COLUMN, which calls `addImplicitIndicesForColumn` while building the new metadata and hits the same shape as CREATE. The generator already settled the underlying question in the other direction: `StorageInMemoryMetadata::addImplicitIndicesForColumn` validates the index it has just generated and, on BAD_ARGUMENTS or INCORRECT_QUERY, sets `valid_index = false` and silently does not add it rather than failing the user's statement. Exempting implicit indices from the probe follows that, and covers all three routes at once; making the predecessor lookup rename-aware would only have addressed the second, and `checkProperties` cannot see which ALTER commands were issued. The exemption is per index, not per table: an explicitly declared ill-typed index is still rejected on a table that also carries an exempt implicit one. `is_implicitly_created` survives a restart, since implicit indices are regenerated at load and indices persisted by versions before 25.12 are re-marked there.
Internal second-model review: adjudication log (click to expand)Pre-publication review over four fix rounds: my own cold read of the resulting code each round, an
| 11 | ❌ | Severity: blocker / major / nit. DISAGREE verdicts carry recorded evidence and are terminal per Session id: cron:clickhouse-review-slot-9:20260906-032600 |
|
Workflow [PR], commit [70a6dd5] Summary: ✅
AI ReviewSummaryThis PR adds a dry-run Findings
Final VerdictNot ready yet. The new validation fixes the narrow direct-expression case, but it still leaves both a normal LLVM Coverage ReportMeasured on commit 70a6dd5.
Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260906-013700 |
|
cc @CurtizJ @KochetovNicolai, could you review this? A skip index expression is only type-checked through |
|
|
||
| for (const auto & node : index.expression->getActionsDAG().getNodes()) | ||
| if (node.type == ActionsDAG::ActionType::FUNCTION | ||
| && (!node.function_base || !node.function_base->isSuitableForConstantFolding())) |
There was a problem hiding this comment.
This isSuitableForConstantFolding() gate is broader than the side-effect concern in the comment. It suppresses the probe for pure wrappers like identity (src/Functions/identity.h:37-58) and materialize, but ActionsDAG::updateHeader() still evaluates their children bottom-up (ActionsDAG::evaluatePartialResult, ActionsDAG.cpp:1646-1712). So INDEX i0 identity(c0 = c1) TYPE set(0) is still accepted here and later hits the same NO_COMMON_TYPE during INSERT or merge. The original bug is still trivially bypassable through ordinary CREATE TABLE.
The predicate needs to distinguish truly side-effecting/context-sensitive functions from harmless wrappers, or probe child subexpressions even when the parent itself should not be executed.
There was a problem hiding this comment.
Confirmed at both ends, and not introduced here. On the published build (fc9db304), INDEX i0 identity(c0 = c1) TYPE set(0) and INDEX i0 materialize(c0 = c1) TYPE set(0) are accepted by CREATE TABLE and by ALTER TABLE ... ADD INDEX, and the first INSERT fails with Code: 386. The base build of the merge base (21de58f0, 03d2aea9486c95a) accepts the same statements and fails the same inserts, so these shapes keep master's behaviour exactly; 05080 cell F pins the class as accepted.
I am keeping the predicate, for two measured reasons.
Nothing in the tree separates a harmless wrapper from a context-sensitive function. aiEmbed reports isDeterministic() == true (aiEmbed.cpp:76), and its executeImpl builds the provider at :109, which runs context->checkAccess(AccessType::NAMED_COLLECTION, ...) (FunctionBaseAI.cpp:251), before the input_rows_count == 0 return at :115. The DAG probed here was analyzed with the context of the user running the DDL, so probing that expression would refuse an unrelated ALTER for a user who lacks that grant, and isSuitableForConstantFolding is the one predicate that covers every such function at once.
Probing children under a parent that must not run does not close this face either: INDEX i0 identity(c0) = c1 TYPE set(0) is accepted on the same build, and there the unevaluable node is the parent. Probing by execution cannot be complete while equals resolves String against Int8 to UInt8 at analysis time and computes the supertype only on the execution path (FunctionsComparison.h:1455, in executeGeneric). A complete answer belongs there, and it is much wider than this PR.
The residuals paragraph in the description now names the wrapper shape.
| /// An index the server generates from a setting is not the user's declaration, so it | ||
| /// must not be the reason a statement is refused; `addImplicitIndicesForColumn` drops | ||
| /// one it cannot validate instead of failing the statement. | ||
| if (!attach && !index.isImplicitlyCreated()) |
There was a problem hiding this comment.
attach is too coarse a gate here. MergeTreeData passes attach = true for every mode with sanity_checks == false, but LoadingStrictnessLevel::ATTACH with a full definition is still fresh user input (isFreshTableDefinition(...) returns true for that case). As a result, ATTACH TABLE t (...) ENGINE = MergeTree can still declare INDEX i0 c0 = c1 TYPE set(0) and leave the table failing on the first INSERT or merge, which is the same failure this PR is meant to move to DDL time.
Please thread the fresh-definition bit down instead of keying off attach alone, so replay/load paths stay exempt but full-definition ATTACH is validated the same way as CREATE TABLE.
There was a problem hiding this comment.
Confirmed, and also unchanged from master. On the published build (fc9db304), ATTACH TABLE t (c0 String, c1 Int8, INDEX i0 c0 = c1 TYPE set(0)) ENGINE = MergeTree ORDER BY c1 is accepted in an Ordinary database and in an Atomic one when a UUID is given (without a UUID it is Code: 80 INCORRECT_QUERY), and the first INSERT then fails with Code: 386. The base build 21de58f0 accepts the same statements. isFreshTableDefinition does classify that as fresh input.
I am not threading the bit in here, because that statement shape is also the shape a stored definition has: getObjectDefinitionFromCreateQuery writes every metadata file with create->attach = true (DatabaseOnDisk.cpp:191), so a full-definition ATTACH is how an existing data directory is put back under a table by hand. Validating it would refuse the by-hand re-attach of exactly the grandfathered tables the attach exemption keeps loadable, and it is the only way from SQL alone to reach a table carrying an index this probe rejects, so 05081's D1 to D7 cells could not be written at all (writing metadata or parts by hand belongs in an integration test).
The same attach bool gates the neighbouring validations in this function (MergeTreeData.cpp:1074, :1081, :1198, :1208, and it is passed into MergeTreeIndexFactory::validate at :1210), and the route the description lists as still exposed reaches checkProperties through setProperties(new_metadata, old_metadata) (StorageReplicatedMergeTree.cpp:1892), which has no create query to derive the bit from. So the mode belongs to the whole function rather than to this one check, and I would rather not make this check the only strict one. The description's residuals now name the full-definition ATTACH too.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 39 s compile time in total, 7 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
e3c7fcd
Closes: #69597
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
CREATE TABLEandALTER TABLE ... ADD INDEXnow reject a skip index whose expression cannot be evaluated, such asINDEX i c0 = c1 TYPE set(0)overStringandInt8, and anALTER TABLE ... MODIFY COLUMNthat would leave an existing index in that state is rejected too. Such a declaration used to be accepted, after which everyINSERTand merge failed withNO_COMMON_TYPE, andMATERIALIZE INDEXretried that error forever. Closes #69597.Description
IndexDescription::initExpressionInfotakes the expression'ssample_blockfromExpressionActions::getSampleBlock, which reports DAG result types and executes nothing, soequals(String, Int8)passes overload resolution and is accepted. A merge'sExpressionStepheaderthen goes through
ActionsDAG::updateHeader, a zero-row dry run wheregetLeastSupertypethrows.I ask it in the per-index loop of
MergeTreeData::checkProperties:updateHeaderon the index's DAGover a zero-row header, the dry run a merge performs (
ExpressionTransform::transformHeader).Three gates keep it narrow. The probe is skipped unless every function node satisfies
isSuitableForConstantFolding: such a function may do context-dependent work at zero rows, and thisDAG carries the altering user's context, not the storage's. Only a violation the statement
introduces is reported, compared against the old metadata's index of that name, so a table declared
before this check still attaches, still alters, and
DROP INDEXrepairs it. And an index the servergenerates itself (
add_minmax_index_for_*, off by default) is never probed: the user declared noindex there.
Residuals. A zero-row dry run decides type errors only: a data-dependent failure stays accepted, and
so does a
Nullableoperand, wheredefaultImplementationForNullsreturns an empty result first(
IFunction.cpp:311-319). So do an ill-typed generated index, an expression wrapped in a functionthat opts out of folding (
identity(c0 = c1)), and a full-definitionATTACH; master accepts allthree unchanged. Key expressions have the same hole (
KeyDescription.cpp:190). Like theneighbouring
!attachvalidations, it can still reject a grandfathered index where a routere-derives an existing table with
attach = false(setTableStructureapplying an older replica'sentry,
SYSTEM RESTORE DATABASE REPLICA); exempting those needs a flag threaded intocheckProperties.Workflow [PR]
Sync PR [sync-upstream/pr/118373]
Version info
26.10.1.243-master(included in26.10and later)