Repository navigation
Publish column types and serialization hints atomically in ALTER - #114019
alexey-milovidov merged 12 commits into
Conversation
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.
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 ❌ Fixed before publishingA false justification in the test (round 1, The select form is still the right choice, for the real reason now stated in the comment: an
|
Pre-PR validation gate (a-i)
Regression suites run locally on the debug build: the new test (100/100 randomized runs across two batches), 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 |
|
cc @hanfei1991 @CheSema, could you review this? |
|
Workflow [PR], commit [64e27cf] Summary: ✅
AI ReviewSummaryThe PR publishes column metadata and serialization hints together under the parts lock in Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: |
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]>
CI finish ledger - d081377CI fully finished and clean: 175/175 check-runs completed, 158 success / 17 skipped, 0 failures, Session id: cron:our-pr-ci-monitor:20260809-160000 |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units720 translation units recompiled, 7291 s compile time in total, 720 of them have a recent master baseline. |
`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.
CI finish ledger - a7c93ecEvery 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
Gates: 176 of 176 check nodes completed, Session id: cron:our-pr-ci-monitor:20260919-183143 |
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]>
CI finish ledger - 7779164Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of these touches the serialization hints this PR changes. All 157 checks completed; CIDB has no other Session id: cron:our-pr-ci-monitor:20261003-200032 |
|
Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774 |
…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]>
CI finish ledger - 05e03fdEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261024-173006 |
…tion-hints-atomic-publish
`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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ALTER TABLE ... MODIFY COLUMNthat changes a column's type in aMergeTree-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 theALTERruns is never mixed into statistics built for the old type.Description
ALTER MODIFY COLUMNpublished the new metadata through the lock-free multiversion store and rebuiltserialization_hintsafterwards, in a separatelockParts()scope. In that gap a committing part reachesupdateSerializationHintsForPartwithpart_columnsandstorage_columnsboth 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. ForString->Tuple(...)that hint is a baseSerializationInfoand the part's info aSerializationInfoTuple,structureEqualsis atypeidcomparison, and thechassertfails. The guard compares part against table, so it cannot notice that the hint is stale.MergeTreeData::setPropertiesAndResetSerializationHintsnow publishes and swaps the hints in oneparts_lockscope, since a part commit holds it inTransaction::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 replicatedsetTableStructurerollback, so a failedalterTablecannot leave old columns with new-typed hints. Settings-, comment- and statistics-only publishes are untouched, as is the assertion.parts_lockis 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 restoringold_metadatakeeps plainsetProperties, 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
26.11.1.2390-master(included in26.11and later)