Skip to content

Resolve skip-index expression types in the global context, not the ALTER's session - #119799

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/skip-index-type-from-alter-session-context
Sep 19, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/skip-index-type-from-alter-session-context

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed a skip index recording the wrong expression type when ALTER TABLE ran in a session whose settings change how that expression resolves. toString(v) over a Dynamic column is Nullable(String) under cast_keep_nullable and String at the server baseline, so such an ALTER stored Nullable(String) while the writers resolved String, 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%29

What breaks. AlterCommands::apply re-derived every secondary index in the issuing session's context, on any metadata-changing ALTER. FunctionConvert::getReturnTypeImpl treats a Dynamic or Variant argument as nullable under cast_keep_nullable, so such an ALTER recorded Nullable(String) for toString(v). CREATE does not: it goes through StorageFactory::get, which asserts a global context, and the two rebuild producers reached here, the merge and the INSERT path, analyse through MergeTreeData's own context, also global. The next rebuild then produced a ColumnString for a ColumnNullable accumulator and aborted in MergeTreeIndexAggregatorSet::update. Release builds do not compile that assertion layer, so there the mismatch reaches ColumnNullable::insertRangeFrom with assert_cast degenerated to static_cast: undefined behaviour, not an abort.

The change. One call site: that loop now resolves index descriptions in the global context, so an ALTER records the type CREATE and a reload do, for every setting the analysis reads from that context.

Validation. ALTER ... SETTINGS cast_keep_nullable = 1 on a Dynamic column with INDEX idx toString(v) TYPE set(100), then OPTIMIZE FINAL, aborts on master and passes here. Measured both directions for Dynamic and Variant, Compact and Wide parts, the merge and INSERT producers, MODIFY SETTING and ADD 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_key validator 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

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

…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.
@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 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (three rounds; final state)

I reviewed this change cold before reading my own implementation notes, then ran an independent
second-model pass over the same diff, in each of three rounds. Every finding below has a verdict and
the evidence behind it. The last round's independent pass returned no findings, and the one changed
source line has been identical since the first round: rounds 2 and 3 corrected only comments and
prose.

❌ Blockers (fixed before publication)

  • The release-build consequence was stated wrongly. An earlier draft said a release build
    serializes the granule and prunes reads against the recorded type, i.e. wrong results. That is not
    what happens: outside DEBUG_OR_SANITIZER_BUILD, IColumn::insertRangeFrom is the pure virtual
    (src/Columns/IColumn.h:277-287), so the assertion layer is not compiled at all and the mismatch
    reaches ColumnNullable::insertRangeFrom, where assert_cast degenerates to static_cast
    (src/Common/assert_cast.h:45) and a ColumnString is reinterpreted as a ColumnNullable. That is
    undefined behaviour, not defined wrong results. Corrected everywhere. AGREE.

⚠️ Majors (fixed before publication)

  • The regression test could silently stop detecting the regression. It relied on
    OPTIMIZE ... FINAL winning a race against the background merge selector: with a merge in flight
    canMergeAllParts fails (MergeTreeDataMergerMutator.cpp:390-396) and OPTIMIZE no-ops, and a
    merge that started before the ALTER rebuilds from consistent metadata. Now bracketed by
    SYSTEM STOP/START MERGES. AGREE.

  • The index never pruned a granule, so the read arm proved too little. Measured
    Granules: 32/32: with v = number % 2 and index_granularity = 4 every granule held both
    values, and MergeTreeDataSelectExecutor.cpp:2585-2589 returns unfiltered ranges when an index
    file is absent, so force_data_skipping_indices could not catch a degraded index either. The rows
    are now clustered and the pruned granule count is asserted through EXPLAIN indexes = 1. AGREE.

  • The writer enumeration over-claimed. "Both writers analyse in the global context" is true of
    the merge (MergeTask.cpp:3190) and the INSERT producer
    (MergeTreeDataWriter.cpp:854 -> MergeTreeData.cpp:1557), but there is a third rebuild producer
    that is not: MutateTask.cpp:3930-3932 analyses with a copy of getBackgroundContext()
    (MutatePlainMergeTreeTask.cpp:207-208, Context.cpp:4041-4062). In the default configuration the
    settings coincide, so it is not a hole in this fix; the text now names only what I verified. AGREE.

  • A dead defensive branch that failed open. The resolution guarded getGlobalContext() with
    hasGlobalContext() and fell back to the session context, silently restoring the defect. The false
    arm is unreachable: hasGlobalContext() tests the per-context weak pointer global_context
    (Context.h:1458), every Context::createGlobal site pairs with makeGlobalContext(), which sets
    it (Context.cpp:4031-4038), createCopy inherits it, and the static strong reference assigned
    there is never reset, so it cannot expire. MergeTreeData.cpp:770 already dereferences the global
    context unconditionally. It was the only such guard in src/Storages. Removed. AGREE.

  • The over-claim survived in the code, not just in the prose. The round-1 correction landed in
    the commit message but the source comment (AlterCommands.cpp:1825-1826) and the test preamble
    still said a fresh reload "and every writer" resolve in the global context. That is false for the
    mutation producer: MutatePlainMergeTreeTask::createTaskContext (MutatePlainMergeTreeTask.cpp:206-208)
    copies getBackgroundContext(), and Context::makeBackgroundContext (Context.cpp:4041-4063)
    applies the configured background settings profile, which can carry an ordinary session setting
    such as cast_keep_nullable (Settings.cpp:5527). Both comments now claim only the reload anchor
    and the two producers this change is about. AGREE.

💡 Noted, not blocking, deliberately not widened

  • The commit message's opening sentence is looser than the diff's own comment. It says every path
    that resolves an index expression uses the global context, while its fifth paragraph discloses the
    mutation path (MutateTask.cpp:3928, analysing on a copy of getBackgroundContext()) as a third
    rebuild producer deliberately left alone. The sentence is glossed by the enumeration that follows
    its colon, which names only the two producers this change is about, and the exception is stated
    explicitly with the reason it is benign in the default configuration, so the message is accurate
    read whole. Left as written rather than spending another round amending prose.

  • The test preamble's contrast with a table-level MODIFY SETTING is not exhaustive. The
    settings-only branch does install the new metadata when the implicit statistics change
    (StorageMergeTree.cpp:508-521). That cannot happen for MODIFY SETTING max_compress_block_size,
    so the comment holds for every case a reader would try, and its point (this test needs the
    column-level form) is right.

  • After this change all four index-expression analyses share the global context, but they still use
    four different column universes (AlterCommands.cpp:1824, MergeTask.cpp:3184-3188,
    MergeTreeData.cpp:1557, registerStorageMergeTree.cpp:1035). I could not construct a
    user-reachable divergence from that, so it stays out of scope.

  • Two return-type-affecting settings are read from CurrentThread::get().tryGetQueryContext() rather
    than from the context threaded into the resolution, so a context swap cannot close them:
    variant_throw_on_type_mismatch (TypeMismatchStrictness.cpp:33-40 ->
    FunctionVariantAdaptor.cpp:823) and use_legacy_to_time (FunctionFactory.cpp:154-162). CREATE
    is equally exposed, so this PR neither introduces nor is expected to fix it; the in-tree precedent
    for closing that channel is a thread-local pin (TTLDescription.cpp:1457-1460).

  • The sorting, primary and partition keys look like the same defect class as skip indices, since
    their persisted data_types drive primary.idx and partition.dat serialization
    (MergeTreeDataPartWriterOnDisk.cpp:133-137,236, MergeTreePartition.cpp:447). Only the sampling
    key and the parallel_replicas_custom_key validator have the read-time re-analysis that makes
    pinning unsafe. This is raised as a question in the description rather than changed here.

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (k UInt64, v Dynamic, INDEX idx toString(v) TYPE set(100) GRANULARITY 1) ENGINE = MergeTree ORDER BY k, two inserts, ALTER TABLE t MODIFY COLUMN k MODIFY SETTING max_compress_block_size = 16 SETTINGS cast_keep_nullable = 1, OPTIMIZE TABLE t FINAL. Aborts every run, no randomization or timing dependence. Verified on both the assertion text and the MergeTreeIndexSet.cpp:289 frame, since STID 2508-47c9 is a shared bucket (closed #97335 carries the same text for an unrelated mechanism).
b Root cause explained? Yes. AlterCommands::apply re-derived every secondary index in the issuing session's context. FunctionConvert::getReturnTypeImpl treats a Dynamic/Variant argument as nullable when cast_keep_nullable is on (FunctionsConversion.h:3212-3224), so the ALTER recorded Nullable(String) for toString(v), while CREATE (StorageFactory.cpp:224 asserts the global context) and the two rebuild producers reached here, the merge and the INSERT path (MergeTask.cpp:3190, MergeTreeData.cpp:1557, both through MergeTreeData.cpp:770), resolve String. The rebuild then inserted a ColumnString into a ColumnNullable accumulator at MergeTreeIndexSet.cpp:289. Measured directly: toString(Dynamic) is String at baseline and Nullable(String) at cast_keep_nullable = 1, while toString(UInt8) and toString(Bool) are String in both.
c Fix matches root cause? Yes. The root cause is one call site resolving persistent metadata in the session context; the fix makes that site use the storage context. Not a widened bound, a no-random-* tag, a reduced dataset, or a guard at the abort site. A write-site cast-or-reject was considered and rejected: it would leave the recorded metadata wrong, so the granule would still be serialized and pruned against the wrong type.
d Test intent preserved / new tests added? No existing test was edited or weakened. One new stateless test, 05210_skip_index_type_from_alter_session_setting. Its mutation arm is live: reverting the one changed line makes it abort and emit 1 of its 4 reference lines. The force_data_skipping_indices = 'idx' oracle was proved live by control (a non-existent index name raises Code: 277), so the pass is not vacuous.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (6522b166 master vs 782bf371 fixed), across seven arms: Dynamic, Variant, Compact part, Wide part, the merge producer, the INSERT producer, and ADD INDEX all abort on master and pass with the fix. Two negative controls (setting dropped; v UInt8) pass on master, isolating the setting rather than the sequence as the trigger.
f Fix is general across code paths? Yes. Carriers enumerated and each accounted for: CREATE/ATTACH already global (asserted); the metadata-changing-ALTER recompute loop fixed here; ALTER ... ADD INDEX covered without a separate change because this loop replaces the just-inserted description before commit (measured end to end, not assumed); the replicated initiator via the same site; the replica applying the log entry already global (StorageReplicatedMergeTree.cpp:6768), so this also removes an initiator/replica split; the replicated metadata diff already global; the merge and INSERT rebuild producers already global. The mutation producer (MutateTask.cpp:3928) analyses on a copy of the background context, so it is a third producer this change does not align; it is out of scope here and called out in the commit message. MergeTreeIndexSet is the only aggregator accumulating into index.sample_block.cloneEmptyColumns(), so minmax/bloom_filter/text/vector_similarity need no per-index work.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured, not argued: Dynamic and Variant(UInt8, String) (the two arms of the FunctionsConversion.h:3214 condition); Compact and Wide parts; merge and INSERT producers; MODIFY SETTING and ADD INDEX shapes. The fix is at the context level rather than per setting, so it covers any type-affecting session setting by construction. I claim no second measured setting carrier: use_variant_as_common_type was tried and is not one, since it now defaults to 1 and both binaries agree.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, no default changed, so no SettingsChangesHistory.cpp entry is due. The behaviour change is that an ALTER now records the baseline index type, which can only differ for a table whose recorded type already disagrees with what its own reload produces, so it makes an inconsistent state consistent rather than removing a working configuration.
i Invariants and contracts preserved? The invariant restored is the one StorageFactory.cpp:224 asserts for CREATE: a skip index's resolved expression type is whatever the server baseline resolves, identical across CREATE, ALTER, reload and the two rebuild producers reached here. No pre/postcondition of AlterCommands::apply changes; it still resolves every index and still rethrows an analysis failure as Cannot apply ALTER because it breaks skip index {}. No block structure, sort order, size or locking contract is touched. getGlobalContext() is called unconditionally, and that is safe rather than optimistic: every createGlobal() site pairs with makeGlobalContext(), which sets the weak pointer it locks, and a static strong reference keeps that context alive. A hasGlobalContext() guard would therefore be unreachable, and its false arm would have failed open by recording the session type again.

Session id: cron:clickhouse-impl-slot-5:20260913-125600

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a632889]

Summary: ✅


AI Review

Summary

This PR fixes the concrete ALTER-session carrier behind the skip-index type drift by re-deriving secondary-index metadata in the global context instead of the caller's session. That direction is correct, but the same persisted-type invariant is still open for mutation-side skip-index rebuilds, so the bug remains reachable in supported background_profile configurations.

Findings

⚠️ Majors

  • [src/Storages/AlterCommands.cpp:1825] The new getGlobalContext() re-analysis only covers the metadata written by ALTER. Mutation-side skip-index rebuilds still analyze indices_recalc_expr_list under a query context copied from getBackgroundContext() (src/Storages/MergeTree/MutatePlainMergeTreeTask.cpp:207-208, src/Storages/MergeTree/MutateTask.cpp:3930-3932), and background_profile is an explicitly supported way to override mutation settings. That means cast_keep_nullable = 1 in the background profile can still resolve toString(Dynamic) as Nullable(String) while the persisted index.sample_block recorded here says String, recreating the same ColumnString/ColumnNullable mismatch through MATERIALIZE INDEX and other mutation-driven skip-index rebuilds. Suggested fix: run mutation-side skip-index analysis under the same canonical context as CREATE / reload / merge / INSERT, or add regression coverage that proves background-profile settings cannot diverge from stored skip-index types.
Final Verdict

Changes requested. The ALTER-side fix is directionally right, but the bug is still reachable through the mutation/background path.

LLVM Coverage Report

Measured on commit a632889.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · 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 13, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. label Sep 13, 2026
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();

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a6328899d with master b31464114 (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, 16 s compile time in total, 7 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 8e32203 Sep 19, 2026
176 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

@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 @ 821702f2.

Same mechanism, different producer. On t_stale_bool from 04870_skip_index_stale_type_metadata_only_alter, the fuzzer ran ALTER TABLE t_stale_bool MODIFY COLUMN v Dynamic(...) twice with cast_keep_nullable = 1 (query_log Settings of both the query and its ddl_entry execution), so AlterCommands::apply recorded idx toString(v) in that session. The mutation it scheduled rebuilt idx through MergeTreeData::getPrimaryKeyAndSkipIndicesExpression, which uses the table's global context, and MergeTreeIndexAggregatorSet::update hit assertTypeEquality (stack via MutateAllPartColumnsTask, not a merge). By the source, a release build has no such check, and ColumnNullable::insertRangeFrom then static_casts the column.

Branch Has this fix cast_keep_nullable makes toString(Dynamic) nullable Has 04870
26.9 no (cut 2026-09-16) yes yes
26.8 no yes yes
26.7 no yes no
26.3 no no no

The two changed lines are identical on 26.7, 26.8 and 26.9.

Could you apply v26.7-must-backport (26.7, 26.8 and 26.9, every active branch with the trigger), or v26.9-must-backport (only the branch that is red)?

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 9, 2026
…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]>
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.

4 participants