Skip to content

Publish column types and serialization hints atomically in ALTER - #114019

Merged
alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:fix-alter-serialization-hints-atomic-publish
Nov 15, 2026
Merged

alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:fix-alter-serialization-hints-atomic-publish

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

ALTER TABLE ... MODIFY COLUMN that changes a column's type in a MergeTree-family table now switches the column type and the table's serialization statistics (which choose between sparse and full serialization) in one step, so a part committed while the ALTER runs is never mixed into statistics built for the old type.

Description

ALTER MODIFY COLUMN published the new metadata through the lock-free multiversion store and rebuilt serialization_hints afterwards, in a separate lockParts() scope. In that gap a committing part reaches updateSerializationHintsForPart with part_columns and storage_columns both already NEW, so the "structure may change after alter" guard compares NEW against NEW and lets the part through, while the hint it mutates is still OLD-typed. For String -> Tuple(...) that hint is a base SerializationInfo and the part's info a SerializationInfoTuple, structureEquals is a typeid comparison, and the chassert fails. The guard compares part against table, so it cannot notice that the hint is stale.

MergeTreeData::setPropertiesAndResetSerializationHints now publishes and swaps the hints in one parts_lock scope, since a part commit holds it in Transaction::commit. It is prepare-then-commit: the metadata clone happens outside the lock, and inside it the new hints are built before anything is published, so a throw leaves both unchanged. Five column-type publishes use it, including the replicated setTableStructure rollback, so a failed alterTable cannot leave old columns with new-typed hints. Settings-, comment- and statistics-only publishes are untouched, as is the assertion.

parts_lock is hot, but the hints build already ran under it and the clone is kept out, so the net addition is two moves. The non-replicated rollback restoring old_metadata keeps plain setProperties, because the rejected new settings are still live there.

The new test parks an ALTER inside the window with a failpoint and commits an INSERT concurrently. It aborts with the expected assertion on the old ordering, and passes on the fix while observing the INSERT contend. Public CI has since hit the same assertion 3 times on 2 unrelated PRs (stress test), all in debug or sanitizer builds. The assertion is compiled out of release builds and no release-build misbehavior has been observed, hence Improvement.


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

Version info

  • Merged into: 26.11.1.2390-master (included in 26.11 and later)

ALTER MODIFY COLUMN published the new metadata through the lock-free
MultiVersionStorageMetadataPtr and only afterwards rebuilt the table-level
serialization_hints aggregate, in a separate lockParts() scope. A part
committing in that gap reached updateSerializationHintsForPart with
part_columns and storage_columns both already NEW, so the "structure may
change after alter" guard compared NEW against NEW and did not skip the part,
while the hint it went on to mutate was still built for the old column type.
The guard compares the part against the table, so it structurally cannot
detect that the hint is the stale party.

For String -> Tuple(...) the stale hint is a base SerializationInfo and the
part's info is a SerializationInfoTuple. SerializationInfo::structureEquals is
a typeid comparison, so chassert(new_hint->structureEquals(*info)) fails and
the server aborts in debug and sanitizer builds. A release build does not
abort; it folds the tuple part's top-level counters into a structureless hint,
so sparse-vs-full serialization is chosen from wrong statistics until the
ALTER's own rebuild lands. Reported against a ReplicatedMergeTree replica
applying ALTER_METADATA while fetching a part, but plain MergeTree has the
same split in StorageMergeTree::alter, where an INSERT is the carrier.

Add MergeTreeData::setPropertiesAndResetSerializationHints, which performs the
metadata publish and the hints swap in one parts_lock scope. parts_lock is the
lock the two sides genuinely share: a part commit holds it across
Transaction::commit, whereas the committer never takes alter_lock, so widening
the alter-lock scope would not exclude anything here.

The helper is prepare-then-commit. The metadata deep-clone (which clones
projections, keys and settings changes) happens outside the lock; inside the
lock the new aggregate is built first, so a throw there leaves metadata and
hints both at their old values. Publishing and only then rebuilding, as the old
code did, meant a throw mid-reset could leave new metadata paired with a
cleared or partial aggregate, and in the replicated path that happened before
the setTableStructure rollback, so the rollback republished old metadata over
already-clobbered hints. The tail is two moves, so the net time added inside
this hot lock is small; the hints build itself already ran under parts_lock.

Five publishes that can change column types now use it, including the
replicated setTableStructure rollback, which is required rather than optional:
once the forward path rebuilds hints before alterTable, an alterTable throw
would otherwise leave old metadata with new-typed hints. That is safe because
setTableStructure never calls changeSettings. The redundant outer reset in
executeMetadataAlter is removed.

Two publishes stay on plain setProperties deliberately. The non-replicated
old-state rollback publishes old_metadata while the rejected new settings are
still live, since changeSettings(old_metadata...) runs only after the durable
rollback, so rebuilding hints there would build them from settings about to be
undone. Construction and attach run before parts are loaded, and loadDataParts
does the authoritative rebuild.

Publishes that change only settings, comments, statistics or a metadata version
cannot make a hint stale against a column type and are untouched. The assertion
itself is unchanged: it encodes the invariant this change actually establishes.

Extract buildSerializationHints so the aggregate can be constructed without
publishing it; resetSerializationHints keeps its behaviour and callers.

The new test parks the ALTER inside the window with a pauseable failpoint and
commits an INSERT concurrently. The failpoint sits between the publish and the
swap, inside the lock, so on the fixed ordering the INSERT provably blocks on
parts_lock; a pause placed before the lock would let the INSERT commit against
old metadata and pass for the wrong reason. The test also asserts the INSERT is
observed contending, so a green result cannot be explained by it finishing
before the ALTER reached the window. It aborts with the target assertion when
the critical section is split back apart.

The INSERT is a select-insert rather than an inline-data one so that the table
hints are never handed to an input format, where a stale base-class hint would
trip DataTypeTuple::getSerialization's assert_cast in the parser instead. Two
gates make that hold: InterpreterInsertQuery::execute routes any query with a
SELECT to buildInsertSelectPipeline, which never reads the hints, and the
handover in buildInsertPipeline is additionally conditional on
ASTInsertQuery::hasInlinedData(), false for a select-insert.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 2 rounds, 4 findings adjudicated (1 fixed, 3 disagreed with evidence)

Before opening this PR I ran an independent reviewer over the diff twice, then adjudicated
every finding against the source. Round 1 found one real defect in the test's justification and
sent it back for a fix; round 2 came back with one finding, disagreed below. Verdicts and the
evidence behind each are recorded here so the reasoning is auditable rather than asserted.

❌ Fixed before publishing

A false justification in the test (round 1, major). The test originally passed
--enable_parsing_to_custom_serialization 0, and both the test comment and a commit-message
paragraph claimed this stopped DataTypeTuple::getSerialization from assert_casting a stale
hint in the parser. That cannot happen on this test's path, so the flag was inert and the stated
reason was wrong. The only hint handover is
InterpreterInsertQuery.cpp:1041,
which lives in buildInsertPipeline; execute() sends any query carrying a SELECT to
buildInsertSelectPipeline instead, and the handover is gated a second time on
ASTInsertQuery::hasInlinedData() (data || tail), false for a plain select-insert.

The select form is still the right choice, for the real reason now stated in the comment: an
inline-data insert would relocate the pre-fix failure into the parser's assert_cast and make
the negative control ambiguous. So the flag was dropped, the comment and commit message
corrected, and the load-bearing check was re-measured rather than argued: with the flag gone,
the pre-fix ordering still aborts on the intended assertion at MergeTreeData.cpp:11944, reached
through Transaction::commit <- MergeTreeSink::commitPart, with zero parser frames anywhere in
the log. The test then ran 20/20 and 100/100 randomized, plus 14/14 across the neighbouring
02662_sparse_columns_mutations_* and 01780_column_sparse* tests.

⚠️ Disagreed, with evidence

"The MergeTree-family claim is not verified for SharedMergeTree" (round 2, major).
A fair ask, and the standing review guidance does say to check symmetric subsystems. It is not
actionable in this repository, though: src/Storages/StorageSharedMergeTree.* does not exist
here, every reference to that engine is behind #if CLICKHOUSE_CLOUD, and CMakeLists.txt:26
sets CLICKHOUSE_CLOUD 0 - so its publish and commit paths cannot be read, let alone tested.
The finding's primary citation (registerStorageMergeTree.cpp:4443-4445) is also inside a
R"DOCS_MD( documentation string for the ReplicatedMergeTree registration, not a rewrite
implementation.

Within this repository the family is fully covered: StorageMergeTree and
StorageReplicatedMergeTree are the only classes deriving from MergeTreeData, both final,
so Replacing/Summing/Collapsing/Aggregating/Graphite/VersionedCollapsing are those
same two classes parameterised by MergingParams, and all five column-type publishes in them now
go through the new helper.

I also picked the fix shape that covers a Cloud sibling most cheaply, which is the substance of
the concern: the helper is a protected member of the shared MergeTreeData base and serialises on
data_parts_mutex - the mutex any subclass already holds across Transaction::commit - so
adopting it there is a call-site change, not a redesign. If someone who can see that engine
would confirm its column-type publish and part-commit go through the same lock, I would
appreciate it; if they do not, that is a one-line follow-up on the Cloud side.
The test's
no-shared-merge-tree tag is a requirement rather than an evasion: failpoints are process-local
and named globally, so under an SMT rewrite the ALTER would apply unpaused.

"Consumers can still pair an old metadata snapshot with new hints" (round 1, blocker).
The split read it describes is real - a consumer captures the metadata snapshot at
InterpreterInsertQuery.cpp:774 and reads hints later at :1041 - but it is pre-existing and
this change is strictly monotone with respect to it. Before this PR the same
(metadata OLD, hints NEW) pairing was reachable, because the hints were rebuilt after the
publish; the only interval this change removes is the (metadata NEW, hints OLD) window that
produces the failure. Closing the split read properly means versioning the hints against the
metadata, which is a different change from the one this changelog entry promises. Noted, not
blocking.

"The test does not prove the INSERT waited for parts_lock" (round 1, major).
Sequencing already excludes the false green: the INSERT is started only after
SYSTEM WAIT FAILPOINT ... PAUSE returns, and that wait checks pause state rather than an
event, so it cannot race past an early pause. insert contending: 1 is pinned in the
.reference, so the anti-false-green assertion is load-bearing rather than decorative, and
reversion detection is demonstrated by the archived stack trace above rather than inferred. I
declined the suggested PartsLockWaitMicroseconds-delta oracle (a server-wide counter, so a
flake source in a parallel suite) and the suggested "release-observable assertion" (no such
introspection surface exists - in release builds the symptom is a silently wrong sparse/full
choice). One sub-claim in this finding was correct, and that is the flag issue fixed above.

💡 Also applied

The changelog entry was rewritten present-tense and user-facing per
docs/changelog_entry_guidelines.md, and a sentence was added stating plainly that there is no
public CI signal for this - the defect is code-proven with a deterministic test, not an observed
failure. The body was condensed to stay inside the concision budget.

Gate spend across both phases: $78.26.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Check Answer
a Deterministic repro? Yes. tests/queries/0_stateless/04840_alter_modify_column_serialization_hints_atomic.sh parks the ALTER inside the publish/reset window with a pauseable failpoint and commits an INSERT concurrently. On-demand, not probabilistic: 100/100 randomized runs.
b Root cause explained? Yes. The new column types are published through the lock-free multiversion metadata store, and serialization_hints is rebuilt afterwards in a separate lockParts() scope. A part committing in that gap makes the updateSerializationHintsForPart guard compare NEW columns against NEW columns, so it does not skip the part, while the hint it mutates is still built for the old type. structureEquals is a typeid comparison, so String -> Tuple(...) trips the assertion.
c Fix matches root cause? Yes. The publish and the hints swap are made atomic under parts_lock, which is the lock a part commit actually holds (Transaction::commit). No widened bound, no no-random-* tag, no relaxed assertion: the chassert that detects the condition is deliberately left in place.
d Test intent preserved / new test added? Yes. No existing test weakened or removed. One new regression test that aborts on the pre-fix ordering.
e Demonstrated in BOTH directions? Yes. Reverting only the member's critical section to the pre-fix split-scope shape reproduces Logical error: 'new_hint->structureEquals(*info)' with the stack MergeTreeData.cpp:11944 -> updateSerializationHints -> Transaction::commit:9970 -> MergeTreeSink::commitPart:414, i.e. the intended assertion rather than an assert_cast in DataTypeTuple. Restoring the fix reproduces the fixed Build ID byte-identically and the test passes.
f General across CODE paths? Yes. Every metadata publish in the MergeTree family was enumerated: the five that can change column types now go through the atomic helper (including the replicated setTableStructure rollback, needed so a failed alterTable cannot leave old columns with new-typed hints). The rest publish only settings, comments, statistics or a metadata version, so no hint can go stale against a column type there. Construction/attach is excluded because loadDataParts does the authoritative rebuild; the non-replicated old-state rollback is excluded because the rejected settings are still live at that point.
g Generalizes across INPUTS? Yes. Drove the window with target types Tuple(UInt64, UInt64, String), Nullable(String), Array(UInt64) and LowCardinality(String): all green, no logical errors. The mechanism is type-agnostic (it is about when the aggregate is swapped); the regression test pins String -> Tuple because that is the direction whose typeid mismatch trips the assertion.
h Backward compatible? Yes. No format change, no setting change, no metadata change, so no SettingsChangesHistory.cpp entry. Verified behaviour-preserving: the same workload against this branch and against a pristine master build of the same base commit produces byte-identical system.parts_columns serialization kinds.
i Invariants and contracts preserved? Yes. serialization_hints is documented as protected by the data-parts mutex; this change makes the ALTER path honour that for the publish too. Exception safety improves: the allocating hints build happens before anything is published, so a throw leaves metadata and hints both at their old values, whereas previously a throw mid-reset could leave new metadata paired with a cleared or partial aggregate (and in the replicated path the rollback then republished old metadata over it). The jemalloc arena convention of both replaced functions is preserved, and the reader side takes a shared lock on the same mutex, so it is excluded as well.

Regression suites run locally on the debug build: the new test (100/100 randomized runs across two batches), 02662_sparse_columns_mutations_*, 01780_column_sparse*, 02235_check_table_sparse_serialization, 02179_sparse_columns_detach, 02733_sparse_columns_reload, and 03716_mutations_parts_* in both MergeTree and ReplicatedMergeTree variants: 22/22 passed. The replicated setTableStructure path was additionally exercised by hand with two chained type-changing ALTERs plus a post-ALTER INSERT.

Rows (a), (d) and (e) were re-measured after a later revision of the test's INSERT invocation (the sources are unchanged by it): another 100/100 randomized runs plus 02662_sparse_columns_mutations_* and 01780_column_sparse* 14/14, and the both-directions check re-run to confirm the assertion reached is still the one in updateSerializationHintsForPart on the part-commit path.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @CheSema, could you review this? ALTER MODIFY COLUMN published the new column types through the lock-free multiversion metadata store and rebuilt the table's serialization_hints aggregate afterwards in a separate lockParts() scope, so a part committing in that gap saw new column types paired with old-typed hints and hit the structureEquals assertion; this makes the publish and the hints swap atomic under parts_lock, the lock a part commit actually holds.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64e27cf]

Summary: ✅


AI Review

Summary

The PR publishes column metadata and serialization hints together under the parts lock in MergeTree and ReplicatedMergeTree, including replicated rollback. The earlier replicated-coverage finding is addressed. One acknowledged reader-side safety issue remains; it needs a linked tracking issue if deliberately left outside this change. Reviewed head: 64e27cfdd2b1c6e7532804d81fbc0387d79c8ff6.

Findings

❌ Blockers

  • src/Storages/MergeTree/MergeTreeData.cpp:15416: Readers can still combine a metadata snapshot with incompatible serialization hints. [dismissed by author -- https://github.com/Publish column types and serialization hints atomically in ALTER #114019#issuecomment-5230555941]. The author correctly identifies this as pre-existing, but the invalid downcast remains reachable. With ratio_of_defaults_for_sparse_serialization = 0.9, a synchronous inline JSONEachRow insert can capture a Tuple(UInt64) column at InterpreterInsertQuery.cpp:987, overlap an ALTER ... MODIFY COLUMN ... String, and then obtain the new base SerializationInfo at line 1137. IRowInputFormat::setSerializationHints passes that hint through Block::getSerializations to DataTypeTuple::getSerialization, whose downcast at DataTypeTuple.cpp:356 is invalid; release builds use an unchecked cast and subsequently access nonexistent tuple-element storage. The parts lock protects the hint fetch but does not bind it to the retained metadata snapshot. Return hints associated with the requested metadata version, or validate their structure against the consumer's types. Alternatively, link a dedicated tracking issue to preserve the explicitly chosen scope; no such issue is linked in the discussion. This point is retained only in the summary, without another inline comment.
Missing context / blind spots
  • ⚠️ Current-head debug-build and focused/sequential stateless jobs are still PENDING in the underlying Praktika report. The report helper's “all-green” wording means no failures were found, not that these jobs completed. Current-head CI results would close this execution-evidence gap; no local build was available.
Final Verdict

Status: ⚠️ Request changes. Fix the acknowledged reader-side mismatch or link a dedicated issue tracking it. No genuinely new inline findings were identified; the addressed bot-authored thread remains resolved.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 9, 2026
The regression test drove only the plain MergeTree carrier
(StorageMergeTree::alter), leaving the ReplicatedMergeTree site
(setTableStructure, reached from an ALTER_METADATA queue entry) unproven
even though the fix converts it too.

Parameterise the case over the engine and run it for both. A single
replica is enough: ALTER MODIFY COLUMN on ReplicatedMergeTree always
goes through executeMetadataAlter -> setTableStructure, so the paused
window is reachable without a second replica, and the process-local
failpoint keeps working. The concurrent INSERT pins
insert_keeper_fault_injection_probability itself, since the setup
client's SET does not reach that separate session and the test profile
otherwise defaults it to 0.01, which would let injected Keeper faults
perturb the contention oracle.

Verified in both directions on a debug build. Restoring the pre-fix
split-scope ordering aborts on the replicated arm at
MergeTreeData.cpp:11944 via Transaction::commit <-
ReplicatedMergeTreeSink::commitPart, with no parser frames in the log;
the fix is green 20/20 with randomization, and the neighbouring
02662_sparse_columns_*, 01780_column_sparse* and 03716_mutations_parts*
suites are 19/19.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d081377

CI fully finished and clean: 175/175 check-runs completed, 158 success / 17 skipped, 0 failures, Finish Workflow success. No failure needs an owner.

Session id: cron:our-pr-ci-monitor:20260809-160000

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
Conflict in src/Storages/IStorage.h: master added setInMemoryMetadataComment at
the same insertion point as this branch's setInMemoryMetadata(unique_ptr&&)
overload. Both are independent additions, so both are kept.

setPropertiesAndResetSerializationHints also picked up the second responsibility
setProperties gained on master in 162e31c: clearing
patch_parts_sorting_keys_cache under patch_parts_sorting_keys_mutex together with
the metadata publish. Without it the three converted alter paths would publish new
metadata while getPatchPartSortingKey kept serving sorting keys derived from the
old metadata, so patch parts would be read with a stale effective sorting key.

No lock-order risk: the only other holder of patch_parts_sorting_keys_mutex,
getPatchPartSortingKey, takes no parts lock, and getEffectivePatchSortingKey and
getEffectivePatchSortingKeySize in PatchPartsUtils.cpp take none either.
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 64e27cfdd with master d88a8f123 (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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
`setPropertiesAndResetSerializationHints` promises that a caller never observes new
column types paired with old serialization hints: the hints are built before the
publish so that a throw leaves both unchanged.

The failpoint call in the middle of that window took `const String &` and was passed
the `extern const char[]` name directly, so a 37-character `std::string` temporary was
constructed at the call site, after the metadata had been published and before the
hints swap. That is past libc++'s 22-character small-string capacity, so it heap
allocates, and ClickHouse's operator new can throw MEMORY_LIMIT_EXCEEDED. On that path
the window closes with new metadata and stale hints, which is the state the assertion
in `updateSerializationHintsForPart` catches; the replicated caller reaches the helper
before its rollback block, so nothing restores the old metadata.

Materialise the name before the publish. The remaining tail is the failpoint call
itself, which now only binds an existing string, and a `std::map` move-assignment,
which transfers nodes without allocating.

Passing the name array directly is the idiom at the other call sites; only this one
sits inside a window that must not throw, so the fix is local rather than a change to
the failpoint API.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a7c93ec

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 6/6) / test_storage_kafka/test_multi_consumer_quota.py::test_multi_consumer_with_partition_affinity flaky: kafka_aff_s1_r2 never acquired any partition within 240s at wait_for_shard_partitions (23 rows over 19 unrelated PRs and 2 true-master runs in 30 days; this PR touches MergeTree serialization hints and no Kafka path) #120556 (external, open), which replaces that exact pytest.fail with upper-bound-only assertions

Gates: 176 of 176 check nodes completed, Finish Workflow success, 22.5 min since the last job finished. One ownable failure, one owner, none ownerless.

Session id: cron:our-pr-ci-monitor:20260919-183143

groeneai and others added 3 commits October 3, 2026 12:25
The new `failpoint_tests_are_isolated` style check (67965ab) requires
every stateless test that arms a fail point on the server to be tagged both
`no-parallel` and `no-fasttest`. This test arms
`mt_alter_pause_after_metadata_publish`, already had `no-parallel`, and was not
on master when that commit added the tag to the existing tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since `async_insert_select_as_async_insert` (90dac34) defaults to true,
the single-block `INSERT ... SELECT` that the test races against the paused
ALTER goes through the asynchronous insert queue. The client then waits in the
queue while a flush thread performs the part commit later, so seeing the INSERT
in `system.processes` no longer means its commit is waiting on `parts_lock`,
and a flush that starts after the failpoint is disabled lets a reverted fix
pass. Measured: every concurrent INSERT had `AsyncInsertQuery = 1`, and the
reverted-fix abort came from `AsynchronousInsertQueue`'s batch flush.

With `async_insert_select_as_async_insert = 0` the INSERT commits in its own
query again (`AsyncInsertQuery = 0` for all 60 inserts of 30 runs), the
reverted fix aborts on the target assertion 8/8 (replicated) and 3/3 (plain
MergeTree) from the INSERT's own query, and the fixed tree passes 20/20 and
10/10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7779164

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the same job is red on master and on 116 PRs in 24h; the clickhouse_fuzzer link outgrows the 2 GiB reach of the small code model #122521 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04266_text_index_tokens_cardinality_order not from this PR: a follower replica reads the text index tokens again and its log lines reach the client, so the test sees extra Reading tokens lines; 19 PRs in 48h #123688 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04819_dynamic_aggregate_function_state_version not from this PR: the test's Native fetch with binary-encoded types fails because a replica writes binary type names that the initiator reads as text; 24 PRs in 48h #123649 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05213_timeseries_metric_families_target not from this PR: a replica resolves the unqualified timeSeriesMetricFamilies(ts_new) argument in default (UNKNOWN_TABLE); 47 PRs in 48h #118518 (external, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05257_sql_security_view_sealed not from this PR: a replica cannot run the SQL SECURITY DEFINER view's read as the definer, so the row policy check fails with ACCESS_DENIED; 58 PRs in 48h #123729 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database: the replicated CREATE VIEW qualifies a nested WITH alias with the database, so the view reads the same-named table; 124 PRs in 48h a fix task is created (fix in progress, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #122521, #123688, #123649, #118518, #123729 and the fix task above

None of these touches the serialization hints this PR changes. All 157 checks completed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-200032

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

groeneai and others added 2 commits October 24, 2026 12:01
…path

Master gave `setProperties` two new steps after the metadata publish: it
invalidates the columns cache when column identity changes (`48ee9a51b08`,
`b9bfa53ad77`), and it refreshes the filename regexp for cache prewarming
from the table settings (`708d34e18e8`). `setPropertiesAndResetSerializationHints`
replaces `setProperties` on the ALTER paths of both engines, so after the
master merge those paths would have published new column types without
dropping the table's columns cache entries. Measured on the merge alone:
five master tests fail (`04201_columns_cache_rename_column`, `04230_*`,
`04238_*`, `04830_*`, `05099_*`; after `RENAME COLUMN` the old column's
entries stay in `system.columns_cache`). With this commit they pass.

Move everything `setProperties` does after the publish into
`updateCachesAfterMetadataPublish` and call it from both functions, so the
two publish paths cannot drift apart again. `setProperties` keeps its exact
behaviour; the atomic path additionally gets the two steps it was missing.
Both call it outside `parts_lock`, as `setProperties` already did.

In `setPropertiesAndResetSerializationHints` the call runs after both the
metadata and the hints are published, so it goes into `NOEXCEPT_SCOPE`, as
the post-commit part of `MergeTreeData::Transaction::commit` does. Its
callers treat an exception as "nothing was published": the plain
`MergeTree` rollback in `StorageMergeTree::alter` republishes the old
metadata with `setProperties` and keeps the new hints, which is the
(old types, new hints) pair `updateSerializationHintsForPart` asserts on.
These steps allocate through `operator new`, which throws
`MEMORY_LIMIT_EXCEEDED` when `min_allocation_size_to_throw_on_memory_limit`
is set (the fuzzers' server config randomizes it up to 1 MiB). Measured
with a forced 200 MB allocation in that spot, a 100 MB query limit and the
setting at 1 MiB: without the scope the ALTER failed after the commit, the
column was rolled back to `String`, and the next `INSERT` aborted on
`new_hint->structureEquals(*info)`; with it the ALTER and the `INSERT`
succeed.

Also shorten the comments this PR added on that path to the invariants a
reader needs at each spot (the clone-outside-the-lock and test-purpose
explanations are dropped; the publish-atomicity contract, the no-allocation
window and the two rollback-site rules stay).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 05e03fd

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) / Segmentation fault (STID: 2844-3993) crash, not from this PR (it changes ALTER serialization hints, not aggregate functions): CrossTabCountsState::merge on a cramersV window state read from a deserialized query plan; it reproduces on a master build #119401 (mine, open)
Stress test (arm_release) / Logical error: Unexpected return type from A. Expected B. Got C. Action: (STID: 1611-45e7) not from this PR: Unexpected return type from plus. Expected UInt64. Got Int64 when a lambda argument shadows an outer column; 8 PRs and 1 master run in the last 30 days #121230 (external, open)
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable ships use_query_condition_cache_for_time_conditions = false after #127632, while master's settings history says its default became true in 26.10; 94 PRs show the same row today #127687 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #119401, #121230, #127687 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261024-173006

alexey-milovidov and others added 2 commits November 15, 2026 01:54
`StorageSharedMergeTree::setTableStructure` in the private repository applies
replicated `ALTER` metadata with `setProperties(..., /*attach = */ true)` and
rebuilds `serialization_hints` later in a separate `lockParts` scope, the same
window this PR closes for `StorageReplicatedMergeTree`. It hit the
`new_hint->structureEquals(*info)` assertion in the stress test of the sync of
ClickHouse#131099. To switch it to the new
helper it must keep skipping the query-time checks, so the helper takes
`attach` like `setProperties` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 15, 2026
Merged via the queue into ClickHouse:master with commit 78b9f01 Nov 15, 2026
192 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 15, 2026
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-improvement Pull request with some product improvements 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