Repository navigation
Resolve skip-index expression types in the global context, not the ALTER's session - #119799
Conversation
…LTER's session A skip index's resolved expression type is persisted in `IndexDescription`'s `sample_block` and `data_types`, and `MergeTreeIndexSet::createIndexAggregator` allocates the accumulator from it. Every path that resolves an index expression uses the global context, so all of them agree: `CREATE` and `ATTACH` go through `StorageFactory::get`, which asserts `arguments.getContext() == arguments.getContext()->getGlobalContext()`, and the two rebuild producers reached here analyse in the global context as well, the merge at `MergeTask.cpp:3190` and the `INSERT` producer at `MergeTreeDataWriter.cpp:854` into `MergeTreeData.cpp:1557`. `AlterCommands::apply` was the single exception, re-deriving every secondary index in the issuing session's context on any metadata-changing `ALTER`. A session setting that changes an index expression's result type therefore recorded a type no writer agrees with. `FunctionConvert::getReturnTypeImpl` treats a `Dynamic` or `Variant` argument as nullable when `cast_keep_nullable` is on, so `toString(v)` over a `Dynamic` column resolves to `Nullable(String)` in such a session and to `String` at the server baseline. An `ALTER` issued there recorded `Nullable(String)`; the next skip-index rebuild resolved `String`, and a `ColumnString` met a `ColumnNullable` accumulator in `MergeTreeIndexAggregatorSet::update`, where `insertRangeFrom` takes `IColumn::assertTypeEquality`'s strict `typeid` branch because `getIndexBlockAndPermute` strips `Const`, `Sparse` and `Replicated` but no `Nullable`. Measured with a `Dynamic` column carrying `INDEX idx toString(v) TYPE set(100)`, an `ALTER` at `cast_keep_nullable = 1` and `OPTIMIZE FINAL`: the abort reproduces for `Dynamic` and for `Variant`, on Compact and on Wide parts, through the merge and through the `INSERT` producer, and for `MODIFY SETTING` as well as `ADD INDEX`. Two negative controls isolate the setting rather than the sequence as the trigger: dropping `cast_keep_nullable` completes, and keeping it while declaring `v UInt8` completes, since `toString(UInt8)` and `toString(Bool)` are both plain `String`. Release builds do not compile that assertion layer at all: outside `DEBUG_OR_SANITIZER_BUILD` `IColumn::insertRangeFrom` is the pure virtual, so the same mismatch reaches `ColumnNullable::insertRangeFrom`, where `assert_cast` degenerates to `static_cast` and a `ColumnString` is reinterpreted as a `ColumnNullable`. That is undefined behaviour rather than a clean abort. `ALTER ... ADD INDEX` needs no separate change: `apply` runs the per-command loop first, and this loop then replaces every description, including the one just inserted, before the metadata is committed. A third rebuild producer, the mutation path, is deliberately left alone. `MutateTask.cpp:3928` re-analyses the index-recalculation expression with a context built from `getBackgroundContext()`, which applies the `background` profile. No such profile exists in the default configuration, so the resolved values coincide there, and no carrier was measured for it. The key descriptions are deliberately left on the session context. The sampling key and the `parallel_replicas_custom_key` validator are re-analysed in the query context at read time, so pinning their declaration-time type can make validation accept a configuration the runtime filter then breaks; skip indices have no such read-time re-analysis, since the read side consumes `index.sample_block` and `data_types` themselves.
Internal second-model review (three rounds; final state)I reviewed this change cold before reading my own implementation notes, then ran an independent ❌ Blockers (fixed before publication)
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260913-125600 |
|
Workflow [PR], commit [a632889] Summary: ✅
AI ReviewSummaryThis PR fixes the concrete Findings
Final VerdictChanges requested. The LLVM Coverage ReportMeasured on commit a632889.
Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code |
The comment claimed that no session setting decides the recorded type. That is more than this change does. `FunctionFactory::tryGetImpl` takes the legacy `toTime` overload from `CurrentThread`'s query context rather than from the context it is handed, so an index over `toTime` still resolves by the issuing session's `use_legacy_to_time` here, and by the server default on a reload: passing the global context cannot reach that channel at all. It predates this branch and reproduces identically without it, and closing it needs the canonical-spelling treatment `replaceLegacyToTime` applies where such a definition is persisted, so it is left alone here. For the same reason the first commit's message overstates the invariant. The paths it enumerates do all pass the global context, but that on its own does not make an index expression resolve identically in all of them.
| const ColumnsDescription columns_with_virtuals = metadata_copy.getColumnsWithVirtuals(); | ||
| /// The resolved index type is persisted, so it must be the type a fresh reload resolves: analyse it | ||
| /// in the global context, not in the session that happens to issue the `ALTER`. | ||
| const ContextPtr index_context = context->getGlobalContext(); |
There was a problem hiding this comment.
AlterCommands::apply now pins the stored skip-index type to getGlobalContext(), but mutation-side skip-index rebuilds still analyze the expression in ctx->context (src/Storages/MergeTree/MutateTask.cpp:3930-3932), and that context is created from storage.getContext()->getBackgroundContext() (src/Storages/MergeTree/MutatePlainMergeTreeTask.cpp:207-208). background_profile is a supported mutation setting surface already covered by tests/integration/test_background_operations_config, so this is not just a theoretical mismatch: cast_keep_nullable = 1 there can still make toString(Dynamic) resolve as Nullable(String) while the metadata recorded here says String.
That leaves the same metadata-vs-aggregator drift reachable through MATERIALIZE INDEX and other mutation-driven skip-index rebuilds, because the accumulator still comes from the persisted index.sample_block while the mutation expression DAG is built under the background profile. I think this needs the mutation path to use the same canonical context as CREATE / reload / merge / INSERT, or a focused regression that proves background_profile cannot diverge here.
There was a problem hiding this comment.
The mechanism is right, and I confirmed it at source: MutateTask.cpp:3928-3932 analyses the index expression list with ctx->context, that context is Context::createCopy(storage.getContext()->getBackgroundContext()) (MutatePlainMergeTreeTask.cpp:205-211), and its profile is background_profile, or a profile named background (Context.cpp:4041-4058). The merge producer is not symmetric with it, which is worth stating precisely: MergeTask.cpp:3190 builds the index expression with global_ctx->data->getContext(), so a merge never reads that profile at all.
The consequence does not reproduce. All arms ran through clickhouse local on debug builds of master (6522B166) and of this branch (D089FD84), with each binary's buildId() asserted against the file on disk:
| # | arm | result |
|---|---|---|
| 1 | background_profile = background with cast_keep_nullable = 1, Wide part, INDEX idx CAST(x AS String) over Nullable(UInt8), ALTER TABLE ... MATERIALIZE INDEX idx |
mutation done, no abort; identical on both builds, and identical with the profile removed |
| 2 | arm 1 plus a system.events probe |
MutationSomePartColumns = 1, so the some-columns path that carries :3928 really ran. A Compact source part takes the full-rewrite path, which never calls updateIndicesToRecalculateAndDrop, so a Wide part is required to test this at all |
| 3 | toTypeName(CAST(x AS String)) over Nullable(UInt8) at cast_keep_nullable 0, then 1 |
String, then Nullable(String): arm 1 is not vacuous, that setting does move the recorded type of that index expression |
| 4 | master, drift placed on the metadata side instead: ALTER TABLE ... COMMENT COLUMN k 'c' SETTINGS cast_keep_nullable = 1, then OPTIMIZE TABLE ... FINAL |
abort in IColumn::assertTypeEquality from MergeTreeIndexAggregatorSet::update, MergeTreeIndexSet.cpp:289 |
| 5 | the same poisoned state, MATERIALIZE INDEX and no merge |
mutation done, no abort |
| 6 | negative control: arm 4 minus the setting on the ALTER |
clean end to end |
Arms 4 and 5 are the discriminating pair: on the exact state that aborts a merge, the mutation rebuild completes. I substituted CAST(x AS String) for your toString(Dynamic) so that arm 3 could establish the type flip by measurement instead of by reading FunctionConvert::getReturnTypeImpl.
So I am not widening this PR. Arm 4 is a second, independent carrier of the class the patch removes, with a different ALTER command and a different index expression from the one 05210 pins, and it is clean on D089FD84. For the mutation site you name I have no reachable consequence to fix, and a regression asserting that an absent divergence stays absent would need a server-config fixture while pinning nothing that a change here could break.
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, 16 s compile time in total, 7 of them have a recent master baseline. |
|
@alexey-milovidov, this fix is not on any release branch, and 26.9 now aborts on the bug it fixes: Stress test (arm_msan), 26.9 @ Same mechanism, different producer. On
The two changed lines are identical on 26.7, 26.8 and 26.9. Could you apply |
…e ALTER's session `AlterCommands::apply` re-derived the sorting, primary and partition keys and the `minmax_count` projection in the context of the session that issued the `ALTER`, while `CREATE`, a reload of the table and the part writers derive them in the global context. A session setting that changes key analysis therefore installed in-memory keys that the table does not really have. With `transform_null_in = 1`, `in` is rewritten to `nullIn`, which renames the key column and, for a `Nullable` argument, changes its type from `Nullable(UInt8)` to `UInt8`. After such an `ALTER` (even a comment-only one): - an INSERT into a table with a Nullable key under `IN` serialized the writer's `ColumnNullable` with the stored `UInt8` serialization: `Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>` in debug builds, a primary index of garbage bytes in release builds; - every merge failed with `NOT_FOUND_COLUMN_IN_BLOCK: Not found column in(x, ...)`; - a partition key wrote `partition.dat` with the session type, so after a restart the parts were detached as `broken-on-start`. Derive these keys in the global context, as ClickHouse#119799 already does for skip indices in the same function, and carry `isAnalyzingBackgroundExpressions` into it so that AI functions stay rejected in keys (ClickHouse#127057). The sampling key, projections and column TTLs keep the session context: the sampling key is re-analysed in the query context at read time, and projections and TTLs are separate derivations. Found by the targeted AST fuzzer on PR ClickHouse#130066 (STID 1499-5685). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a skip index recording the wrong expression type when
ALTER TABLEran in a session whose settings change how that expression resolves.toString(v)over aDynamiccolumn isNullable(String)undercast_keep_nullableandStringat the server baseline, so such anALTERstoredNullable(String)while the writers resolvedString, and the next index rebuild failed an internal type assertion.Description
Related: #119172
Reported by @ alexey-milovidov there, in an unrelated
Stress test (arm_asan_ubsan)run. No open issue tracks it. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119172&sha=384d1c15b59f619faaf42f0f2bfe5a26453e2b9c&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29What breaks.
AlterCommands::applyre-derived every secondary index in the issuing session's context, on any metadata-changingALTER.FunctionConvert::getReturnTypeImpltreats aDynamicorVariantargument as nullable undercast_keep_nullable, so such anALTERrecordedNullable(String)fortoString(v).CREATEdoes not: it goes throughStorageFactory::get, which asserts a global context, and the two rebuild producers reached here, the merge and theINSERTpath, analyse throughMergeTreeData's own context, also global. The next rebuild then produced aColumnStringfor aColumnNullableaccumulator and aborted inMergeTreeIndexAggregatorSet::update. Release builds do not compile that assertion layer, so there the mismatch reachesColumnNullable::insertRangeFromwithassert_castdegenerated tostatic_cast: undefined behaviour, not an abort.The change. One call site: that loop now resolves index descriptions in the global context, so an
ALTERrecords the typeCREATEand a reload do, for every setting the analysis reads from that context.Validation.
ALTER ... SETTINGS cast_keep_nullable = 1on aDynamiccolumn withINDEX idx toString(v) TYPE set(100), thenOPTIMIZE FINAL, aborts on master and passes here. Measured both directions forDynamicandVariant, Compact and Wide parts, the merge andINSERTproducers,MODIFY SETTINGandADD INDEX. Two negative controls isolate the setting, not the sequence.For the owner. I left the key descriptions alone: the sampling key and the
parallel_replicas_custom_keyvalidator are re-analyzed in the query context at read time, so pinning their declaration-time type is not always safe, and the sorting, primary and partition keys belong with #109196. Glad to fold them in if you prefer.Workflow [PR]
Sync PR [sync-upstream/pr/119799]
Version info
26.10.1.222-master(included in26.10and later)