Skip to content

Reject a skip index whose expression cannot be evaluated - #118373

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:reject-ill-typed-skip-index-expression
Sep 20, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:reject-ill-typed-skip-index-expression

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #69597

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

CREATE TABLE and ALTER TABLE ... ADD INDEX now reject a skip index whose expression cannot be evaluated, such as INDEX i c0 = c1 TYPE set(0) over String and Int8, and an ALTER TABLE ... MODIFY COLUMN that would leave an existing index in that state is rejected too. Such a declaration used to be accepted, after which every INSERT and merge failed with NO_COMMON_TYPE, and MATERIALIZE INDEX retried that error forever. Closes #69597.

Description

CREATE TABLE t (c0 String, c1 Int8, INDEX i0 c0 = c1 TYPE set(0)) ENGINE = MergeTree ORDER BY c1;
INSERT INTO t VALUES ('a', 1); -- Code: 386 NO_COMMON_TYPE; so does every merge

IndexDescription::initExpressionInfo takes the expression's sample_block from
ExpressionActions::getSampleBlock, which reports DAG result types and executes nothing, so
equals(String, Int8) passes overload resolution and is accepted. A merge's ExpressionStep header
then goes through ActionsDAG::updateHeader, a zero-row dry run where getLeastSupertype throws.

I ask it in the per-index loop of MergeTreeData::checkProperties: updateHeader on the index's DAG
over 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 this
DAG 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 INDEX repairs it. And an index the server
generates itself (add_minmax_index_for_*, off by default) is never probed: the user declared no
index there.

Residuals. A zero-row dry run decides type errors only: a data-dependent failure stays accepted, and
so does a Nullable operand, where defaultImplementationForNulls returns an empty result first
(IFunction.cpp:311-319). So do an ill-typed generated index, an expression wrapped in a function
that opts out of folding (identity(c0 = c1)), and a full-definition ATTACH; master accepts all
three unchanged. Key expressions have the same hole (KeyDescription.cpp:190). Like the
neighbouring !attach validations, it can still reject a grandfathered index where a route
re-derives an existing table with attach = false (setTableStructure applying an older replica's
entry, SYSTEM RESTORE DATABASE REPLICA); exempting those needs a flag threaded into
checkProperties.


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

Version info

  • Merged into: 26.10.1.243-master (included in 26.10 and later)

groeneai and others added 5 commits September 5, 2026 17:10
`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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
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
independent model (engine: codex, five runs), and an independent scan of the existing skip-index
corpus. 13 findings carried here, 9 AGREE and 4 DISAGREE; the final round returned zero findings from
either reviewer.

# Sev Finding Verdict Evidence / action
1 ❌ A Nullable operand is not caught: at zero rows defaultImplementationForNulls returns before the nested call, so INDEX i0 c0 = c1 over Nullable(String) and Int8 is still accepted (IFunction.cpp:311-319) AGREE, scope stated and pinned Measured on both binaries: both declarations accepted, both first INSERTs fail Code: 386, and master behaves identically, so this change does not reach the case rather than regressing it. The limit is stated in the description and pinned by a test cell shown able to redden. Raised in both rounds, and I refuted only the proposed remedy: reaching the comparison at zero rows requires all-constant arguments (IFunction.cpp:311-319), and all-constant arguments are intercepted first by defaultImplementationForConstantArguments (:139-190), which executes the function with one row of the constant values. Covering the case therefore means evaluating synthesised values, which rejects valid DDL (intDiv by a default 0) and gives up the property that this probe is the merge path's own call
2 ❌ updateHeader evaluates children regardless of the parent's foldability (ActionsDAG.cpp:1704-1715, :1376-1425), so a merge does dry-run throwIf(c0 = c1, 'x'); the test cell claiming otherwise was wrong AGREE, fixed Relabelled the cell to what it proves. Raised independently by both reviewers. Declined the alternative of probing foldable sub-DAGs: updateHeader cannot be asked for a subset, so that means a bespoke evaluator and loses the merge-parity property
3 ❌ Reversing the metadata arguments on the alter rollback path (StorageMergeTree.cpp:700, StorageReplicatedMergeTree.cpp:1901) can make restoration throw for a table that predates this check DISAGREE The rollback setProperties is wrapped in a handler that only logs (StorageMergeTree.cpp:698-704), and six pre-existing !attach checks in the same loop already throw there for legacy metadata: MergeTreeIndexFactory::validate(index, attach=false) rejects a removed index type, a non-deterministic expression and a constant expression (MergeTreeIndices.cpp:524-545), plus checkSuspiciousIndices, checkMinMaxIndexForJSON, the lossy-codec key check and both UNIQUE KEY rejections. checkTTLExpressions throws on the same replica path (StorageReplicatedMergeTree.cpp:1891). This change adds an instance, not a failure mode. Worth stating explicitly: the same holds for setTableStructure (:1892), so in a mixed-version cluster an ALTER_METADATA written by an older replica that declares such an index is refused here too
4 ⚠️ A full-definition ATTACH is treated as fresh input elsewhere (registerStorageMergeTree.cpp:689, :895-908) yet reaches checkProperties with attach=true, so it bypasses the new check DISAGREE True, and shared: checkProperties takes one attach bool, so a full-definition ATTACH already bypasses all six other !attach validations above. Plumbing the fresh-definition distinction into checkProperties changes ATTACH semantics for all of them and is not this change's contract. The test fixture is still sound, because the metadata-loading path passes exactly the same attach=true (MergeTreeData.cpp:806, :822)
5 ⚠️ The justification comment said the merge runs updateHeader on "this same DAG", which is false: MergeTask rebuilds a combined expression from the ASTs under the storage context (MergeTask.cpp:3135-3142, IndicesDescription.cpp:299-308), and the insert path runs ExpressionActions::execute instead (MergeTreeData.cpp:1553-1568) AGREE, fixed Reworded the comment and the description to the claim that holds: the same dry run, over a DAG rebuilt from the same AST, so the two diverge only if a setting changes how a function resolves
6 ⚠️ The false-rejection sweep (526 tests) omitted the two .sql.j2 skip-index tests over JSON and named-tuple subcolumns AGREE, fixed Ran 03276_subcolumns_in_skipping_indexes and 03278_json_subcolumns_in_skipping_indexes on both binaries; outcomes identical. I also checked that the probe actually runs there rather than treating a pass as evidence: the ill-typed counterpart of each shape is rejected. On JSON(a UInt32) an explicit ::String resolves the Dynamic away, so those two tests exercise the probe; the foldability gate fires on genuinely Dynamic operands, which I measured separately
7 💡 The linked issue used Related: where a fixing PR should use Closes:, and the Closes: line was then left inside an HTML comment, where it neither renders nor auto-closes AGREE, fixed Raised twice: my first pass changed the keyword but left the line commented, and the second pass caught that. The full link is now a visible line of the description
8 💡 The changelog entry did not name the ALTER ... MODIFY COLUMN rejection that the tests assert AGREE, fixed Entry now names it
9 ❌ ALTER TABLE ... RENAME COLUMN was rejected on a table that already carried such an index, because renaming rewrites the index AST (AlterCommands.cpp:1294-1309) and the exemption compared definition hashes AGREE, fixed Measured against a pristine binary: master accepted the rename, this change refused it, so a table predating the check became un-renamable. IndexDescription deep-clones definition_ast (IndicesDescription.cpp:53), so the hashes could never match. The exemption now asks only whether the index of that name already failed, which is the question it meant to ask; a redeclaration of an already-unevaluable index under its own name is knowingly no longer re-checked, and a new index name on such a table is still rejected. Both directions pinned by test cells, each shown able to redden
10 💡 The ORDER BY / PARTITION BY key expressions have the identical hole (KeyDescription.cpp:190) noted, not addressed here Measured: ORDER BY (c1, c0 = c1) and PARTITION BY (c0 = c1) are accepted and every INSERT then fails. Disclosed in the description rather than widened into this change

| 11 | ❌ | CREATE TABLE, ALTER RENAME COLUMN and ALTER ADD COLUMN were newly rejected on a table where the SERVER generates the ill-typed index: with add_minmax_index_for_numeric_columns = 1, a column a UInt8 ALIAS c0 = c1 yields auto_minmax_index_a, whose expression cannot be evaluated, and the user declared no index at all | AGREE, fixed | Reached the same mechanism independently at source: an implicit index enters metadata.secondary_indices before checkProperties runs (registerStorageMergeTree.cpp:1015-1019, AlterCommands.cpp:737, :799), and on RENAME COLUMN it is REBUILT under a derived name rather than AST-visited (AlterCommands.cpp:1298-1306), so the name-only predecessor lookup finds nothing. The probe now skips an index the server generated (isImplicitlyCreated()), which is the layering the generator itself uses: StorageInMemoryMetadata::addImplicitIndicesForColumn drops an implicit index it cannot validate instead of failing the statement. Five routes measured accepted on base, refused before the fix, accepted again after; the exemption is per index, so an explicitly declared ill-typed index on that very table is still rejected. Consequence stated in the description: an ill-typed generated index stays accepted, as on master |
| 12 | ❌ | A route that re-derives an existing table with attach = false can still reject a grandfathered index. SYSTEM RESTORE DATABASE REPLICA re-creates each table from the CREATE query in Keeper without a metadata transaction, so mode resolves to CREATE and this check runs | DISAGREE, defect conceded and disclosed | The defect is real; the location is not this change. Five neighbouring validations in this same function share the exposure verbatim through the one attach bool (MergeTreeData.cpp:1082 lossy codec on key columns, :1157 checkSuspiciousIndices, :1167 checkMinMaxIndexForJSON, :1178 MergeTreeIndexFactory::validate, and both UNIQUE KEY rejections), and setTableStructure reaches them all the same way, so an ALTER_METADATA written by an older replica is already refused by those. Exempting the recovery route needs setRecoveryFromStoredMetadata threaded to a call site where local_context is null, which is a change to ATTACH semantics for all of them, not to this one. Backup RESTORE and recoverLostReplica are NOT exposed: both resolve to SECONDARY_CREATE, checked. Disclosed in the description rather than left in an internal log |
| 13 | 💡 | 05080 cells C1-C4 are four arms of one scenario (a well-typed index expression is still accepted) | DISAGREE, noted-not-blocking | Kept deliberately. Over-rejection of DDL that works today is this change's principal risk, these cells are its only in-test regression guard, and finding 11 was itself an over-rejection, which is the empirical argument for keeping them. If a reviewer prefers fewer, fold C2 and C3 and keep C4, the only wrapper-stripping guard |

Severity: blocker / major / nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding. I never edited source in the review lane; every AGREE against the code was executed as a
prescribed fix by the implementation step and re-verified afterwards, and each fix round re-ran the
50/50 randomized runs and the mutation arms rather than trusting the previous round's.

Session id: cron:clickhouse-review-slot-9:20260906-032600

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [70a6dd5]

Summary: ✅


AI Review

Summary

This PR adds a dry-run updateHeader check so many ill-typed skip-index expressions fail during CREATE TABLE or ALTER TABLE instead of later during INSERT or merges. The main reported c0 = c1 case is covered, but two supported declaration paths still admit the same broken metadata, so the fix is not ready yet.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeData.cpp:1016] The new probe is skipped for any expression that contains a function with isSuitableForConstantFolding() == false, even when that function is only a harmless wrapper such as identity or materialize. ActionsDAG::updateHeader() still walks into those children during merge-time header construction, so INDEX i0 identity(c0 = c1) TYPE set(0) can still be created and later fail with NO_COMMON_TYPE. Suggested fix: make the gate distinguish actually side-effecting/context-sensitive functions from benign wrappers, or probe child subexpressions even when the parent itself must not be executed.
  • [src/Storages/MergeTree/MergeTreeData.cpp:1215] The !attach guard exempts full-definition ATTACH TABLE ... (...) ENGINE = MergeTree, even though that path is still fresh user input (isFreshTableDefinition(...) returns true for LoadingStrictnessLevel::ATTACH without short syntax). That means a user can still create a new table with the same ill-typed skip index through supported SQL. Suggested fix: thread the fresh-definition bit into checkProperties and keep the exemption only for replay/loading paths.
Final Verdict

Not ready yet. The new validation fixes the narrow direct-expression case, but it still leaves both a normal CREATE TABLE bypass via non-foldable wrappers and a fresh-definition ATTACH TABLE bypass, so the same broken table state is still reachable.

LLVM Coverage Report

Measured on commit 70a6dd5.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%: CREATE TABLE t (c0 String, c1 Int8) ENGINE = MergeTree ORDER BY c1; INSERT ... ; ALTER TABLE t ADD INDEX i0 c0 = c1 TYPE set(0); OPTIMIZE TABLE t FINAL;. On master the ALTER is accepted and OPTIMIZE fails Code: 386 ... (NO_COMMON_TYPE). The CREATE TABLE spelling fails on every INSERT instead.
b Root cause explained? IndexDescription::initExpressionInfo takes sample_block from ExpressionActions::getSampleBlock, which reports DAG result types and executes nothing, so equals(String, Int8) resolves to UInt8 and the declaration is accepted. Merges and mutations build an ExpressionStep over the index expressions, rebuilt from the same ASTs under the storage context, and its header goes through ActionsDAG::updateHeader, a zero-row dry run of every function, where getLeastSupertype throws. The error is statically decidable at declaration time and was never asked for.
c Fix matches root cause? Yes. It asks the same question at declaration time using the same dry run a merge performs, updateHeader on the index expression's DAG over a zero-row header, and rethrows the original exception so the client sees the real cause. No bound was widened and no check was suppressed. The probe's scope is limited to indices the user actually declared: an index the server generates from add_minmax_index_for_* is skipped, matching the generator's own policy in StorageInMemoryMetadata::addImplicitIndicesForColumn, which drops an implicit index it cannot validate instead of failing the user's statement.
d Test intent preserved / new tests added? Two new SQL-based stateless tests, no no-* tags: 05080_ill_typed_skip_index_expression (declaration rejected on the CREATE, ALTER ADD INDEX and ALTER MODIFY COLUMN paths; four well-typed indexes and one wrapper type still accepted; the constant-folding gate; and the zero-row Nullable boundary, which pins LowCardinality(String) as rejected against Nullable(String) and LowCardinality(Nullable(String)) as accepted) and 05081_ill_typed_skip_index_expression_attach (a table declared before this check still attaches, an unrelated ALTER on it still works, DROP INDEX repairs it, a new index name on it is still rejected, a redeclaration of an already-unevaluable index under that same name is not re-checked, and renaming a column such an index references is still allowed). Cell H of 05080 pins that an index the server generates itself never fails a user statement, on the CREATE, RENAME COLUMN and ADD COLUMN routes, and its third arm keeps asserting that an explicitly declared ill-typed index on that very table is still rejected, so the exemption is per index and not a whole-table bypass. Each named cell was shown able to redden against fifteen Build-ID-verified variant binaries, thirteen of them deliberately broken.
e Both directions demonstrated? Yes, statement by statement on two Build-ID-verified binaries. Pristine 21de58f08a19: ALTER ADD INDEX OK, OPTIMIZE FINAL Code: 386, inline-index CREATE OK, its INSERT Code: 386. With the fix 9095b20fa0b1: ALTER ADD INDEX Code: 386 ... When validating secondary index 'i0', OPTIMIZE FINAL OK, inline-index CREATE rejected. The error moves to the declaration and the merge then succeeds. (9095b20fa0b1 is the first fix build; the shipped binary is fc9db304407f8286, which reproduces these rows identically and additionally restores the three implicit-index routes to their master behaviour.)
f Fix is general across code paths? The check sits in the one per-index loop that all declaration paths reach (CREATE, ALTER, and the projection recursion), before any per-index-type dispatch, so it is type-agnostic across set, minmax, bloom_filter, tokenbf, ngrambf, text and vector_similarity by construction. One predicate at that single site therefore covers every route an implicit index can reach it by (CREATE via registerStorageMergeTree, RENAME COLUMN and ADD COLUMN via AlterCommands), and the load path was already exempt through the attach gate. Key expressions have the identical hole at KeyDescription.cpp:190; I measured it and disclosed it in the PR body rather than widening this PR.
g Fix generalizes across inputs? The check writes no type predicate of its own, so it cannot strip one wrapper and mis-route the rest. It does inherit one limit from the evaluator it calls, and I measured it rather than assuming: at zero rows defaultImplementationForNulls returns early for a nullable argument (IFunction.cpp:311-319, before executeWithoutLowCardinalityColumns), so getLeastSupertype is never reached and an index expression with a Nullable operand is not probed. Measured on the fix binary: INDEX i0 c0 = c1 over Nullable(String)/Int8 and over LowCardinality(Nullable(String))/Int8 is still accepted on the CREATE and ALTER paths and its INSERT still fails Code: 386 -- identical to master, so this change does not reach that case rather than regressing it. The boundary is Nullable specifically and not wrapped types in general: the same declaration over LowCardinality(String)/Int8, whose result type is not nullable, is rejected on both paths, and both facts are now pinned as cell G of 05080. A const or one-row probe would catch the Nullable case but would execute functions against synthesised values and invent DDL-time rejections (intDiv by a default 0); I built that probe and measured it changing this very defect's error from NO_COMMON_TYPE to Code: 53 (TYPE_MISMATCH), so it was rejected. Verified accepted where well-typed: plain column, comparison against a literal of the column type, arithmetic, bloom_filter over LowCardinality(Nullable(String)), tuple subcolumns (a.b.c || a.b.d, i.e. concat(UInt32, String)) and JSON subcolumns (json.a || json.b::String) -- the last two are the in-tree tests 03276/03278, which pass identically on both binaries. Verified still rejected under cast_keep_nullable=1, transform_null_in=1 and enable_analyzer=0; those settings flip no verdict in either direction.
h Backward compatible? No setting is added, so SettingsChangesHistory.cpp is not involved. updateHeader 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, and a table that merges today keeps loading and altering. A table already carrying such an index is exempt twice, by the attach gate and by reporting only a violation the statement introduces, with DROP INDEX as the repair. Index definitions are not compared when deciding that, because RENAME COLUMN rewrites an index's AST without redeclaring it: renaming a column such an index references still succeeds and still rewrites the index, byte-identically to master (test cell D7, measured on both binaries). The price is that redeclaring an already-unevaluable index under its own name is not re-checked, which leaves the table exactly as broken as it already was. An index the server generates from add_minmax_index_for_* is exempt on every route, so a table whose non-trivial ALIAS column yields an unevaluable generated index still creates, renames and gains columns exactly as on master; is_implicitly_created survives a restart, since implicit indices are regenerated at load and ones persisted before 25.12 are re-marked there. One intended behaviour change: an ALTER MODIFY COLUMN that would make an existing index unevaluable is now refused, which is the fail-fast behaviour asked for on the issue.
i Invariants and contracts preserved? The probe is read-only: it builds a throwaway zero-row Block from the expression's own required columns, so no DAG input can be missing and NOT_FOUND_COLUMN_IN_BLOCK is unreachable for a legitimate index. It runs after MergeTreeIndexFactory::validate, which has already refused array joins and non-deterministic expressions, and it is skipped entirely unless every function node satisfies isSuitableForConstantFolding, so no side-effecting or access-checking function is evaluated on the DDL path. Nothing on the read, write or merge path changes. The second probe runs only on the failure path. Skipping an implicit index narrows a validation predicate and so cannot introduce a new throw, and it is per index: the duplicate-name and one-text-index-per-column checks below it still run for every index, implicit ones included.

Session id: cron:clickhouse-impl-slot-6:20260906-013700

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai, could you review this? A skip index expression is only type-checked through ExpressionActions::getSampleBlock, which reports DAG result types and executes nothing, so INDEX i0 c0 = c1 TYPE set(0) over String and Int8 is accepted and every later INSERT and merge fails NO_COMMON_TYPE inside ActionsDAG::updateHeader. This asks for that same zero-row dry run at declaration time, only for an index the user declared and only for a violation the statement introduces.

@clickhouse-gh clickhouse-gh Bot added the comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. label Sep 6, 2026

for (const auto & node : index.expression->getActionsDAG().getNodes())
if (node.type == ActionsDAG::ActionType::FUNCTION
&& (!node.function_base || !node.function_base->isSuitableForConstantFolding()))

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 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 70a6dd514 with master 319bfd73f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 39 s compile time in total, 7 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

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
  • StressHouse run: 17cd9e68-cc33-4680-93ac-616430d36748
  • MIRAI run: 025d2d22-efa3-427e-b328-af982828db7b
  • PR check IDs:
    • clickbench_121603_1788983851
    • clickbench_121705_1788983856
    • clickbench_121807_1788983862
    • tpch_adapted_1_official_121908_1788983876
    • tpch_adapted_1_official_121970_1788983879
    • tpch_adapted_1_official_122171_1788983927

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mutation keeps failing in the background when it shouldn't

3 participants