Skip to content

Route every comment ALTER on a KeeperMap table in a Replicated database through replicated DDL - #118011

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-map-mixed-comment-alter-routing
Sep 6, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-map-mixed-comment-alter-routing

Conversation

@groeneai

@groeneai groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #111957
Related: #107142

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 comment ALTER on a KeeperMap table in a Replicated database being applied only to the local replica. Keeper kept the pre-ALTER CREATE statement and digest, so other replicas never saw the change and the next start declared the replica lost, reverting the ALTER and, if no other table shared its KeeperMap path, dropping its data.

Description

DatabaseReplicated::shouldReplicateQuery gates the replicated path for a KeeperMap ALTER on ASTAlterQuery::isCommentAlter, which requires every command to be the same AST type. The storage accepts more: StorageKeeperMap inherits IStorage::checkAlterIsPossible, which accepts AlterCommand::isCommentAlter per command, covering a comment-only MODIFY COLUMN too. Anything in that gap runs locally with no ZooKeeperMetadataTransaction and still reaches DatabaseReplicated::commitAlterTable. Both are ordinary SQL; the second is a single command, so the trigger is the classification, not the count:

ALTER TABLE t MODIFY COMMENT 'a', COMMENT COLUMN c 'b';
ALTER TABLE t MODIFY COLUMN c COMMENT 'a';

chassert and assertDigest compile away outside debug and sanitizer builds, so a release build completes the ALTER: local metadata and digest advance while Keeper keeps the old ones. At the next start local_digest != zk_digest makes DatabaseReplicatedWorker declare the replica lost (check_consistency defaults to true) and run recoverLostReplica, which drops any table not storing data on disk. Measured on a single replica: the KeeperMap table came back empty, 50 rows to 0, while a MergeTree control kept all of its rows. The drop branch is the existing heuristic in #111957; this removes one of its triggers.

The fix uses ASTAlterQuery::isSettingsOrCommentAlter, added in #107142 for this class and already wired at DDLWorker.cpp:842; that site was fixed and this one missed. isCommentAlter implies it, so the change only widens the replicated set. It also accepts MODIFY/RESET SETTING, which KeeperMap can never apply (same base check); those still fail with the same code and message, except on a replica that cannot enqueue, which now gets the enqueue error rather than NOT_IMPLEMENTED. The cloud-only SharedDatabaseCatalog::shouldReplicateQuery may need the same change.

05076_keeper_map_mixed_comment_alter covers both carriers plus a single-type control; it aborts the server on master.

Found by BuzzHouse (arm_asan_ubsan), STID 2508-2c1e: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117591&sha=1520bd2704e60296068431f9f1144b2112ec03ff&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29


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

Version info

  • Merged into: 26.9.1.865 (included in 26.9 and later)

…tabase

`DatabaseReplicated::shouldReplicateQuery` gated the replicated path for an
`ALTER` on a `KeeperMap` table on `ASTAlterQuery::isCommentAlter`, which
requires every command in the query to be the same single AST type. The
storage accepts a strictly larger set: `StorageKeeperMap` inherits the base
`alter`, so `IStorage::checkAlterIsPossible` accepts
`AlterCommand::isCommentAlter` per command, which also covers a comment-only
`MODIFY COLUMN`. Anything in that gap ran locally with no
`ZooKeeperMetadataTransaction` and still reached
`DatabaseReplicated::commitAlterTable`, whose first statement asserts a
transaction is present while the DDL worker is active.

Two user-reachable carriers, both against a `KeeperMap` table in a
`Replicated` database:

    ALTER TABLE t MODIFY COMMENT 'a', COMMENT COLUMN c 'b';
    ALTER TABLE t MODIFY COLUMN c COMMENT 'a';

The second is a single command, so the trigger is the type classification and
not the command count; a single-type comment `ALTER` was always routed
correctly.

`chassert` and `assertDigest` both compile away outside debug and sanitizer
builds, so on a release build the `ALTER` completes: local metadata and the
local digest advance while Keeper keeps the pre-`ALTER` `CREATE` statement and
digest. Other replicas therefore never receive the change, and at the next
start `local_digest != zk_digest` makes `DatabaseReplicatedWorker` declare the
replica lost (`check_consistency` defaults to true) and run
`recoverLostReplica`, which reverts the `ALTER`. Measured on a single-replica
database holding 50 rows, that recovery logged "Will DROP TABLE km, because it
does not store data on disk and can be safely dropped" and the table came back
empty with its Keeper data children going from 50 to 0, while a `MergeTree`
control table in the same database kept all 77 of its rows. That drop branch is
the pre-existing heuristic tracked in
ClickHouse#111957 and is unchanged here;
this commit removes one deterministic trigger of it.

The fix uses `ASTAlterQuery::isSettingsOrCommentAlter`, added in
ClickHouse#107142 for exactly this class and
already wired into `DDLWorker.cpp`, whose comment there names mixed batches
"that match neither single-type predicate". That routing site was fixed and
this one was missed. `isCommentAlter` implies `isSettingsOrCommentAlter`, so the
change can only widen the set of queries that take the replicated path: nothing
replicated before stops being replicated. The predicate also accepts
`MODIFY SETTING` and `RESET SETTING`, which `KeeperMap` has none of; those
still fail with an identical error code and message before and after, verified
by comparing both binaries, at the cost of one extra DDL log entry.

Found by the BuzzHouse fuzzer on the arm_asan_ubsan build:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117591&sha=1520bd2704e60296068431f9f1144b2112ec03ff&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29
ClickHouse#117591

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 2 findings, 0 blockers

⚠️ SharedDatabaseCatalog::shouldReplicateQuery unverified. It is the symmetric routing site
(InterpreterAlterQuery.cpp:502) and has no implementation in this repository, so I could not check
whether it carries the same isCommentAlter gate. Noted in the description; it needs someone with
cloud access.

💡 Critical Bug Fix suggested; I kept Bug Fix. I do not select the critical category unless a
maintainer asks for it. The conditionality that finding flagged is real and the changelog entry now
carries it: the Keeper data is dropped only when no other table shares the KeeperMap path, since
StorageKeeperMap.cpp:1148-1153 returns early while another registration exists.

💡 Also noticed, not changed: with this routing fix in place, the alter->isCommentAlter() ||
disjunct at DDLWorker.cpp:842 is a strict subset of the isSettingsOrCommentAlter() beside it.
Pure cleanup, in a file this PR does not touch.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [735aabd]

Summary: ✅


AI Review

Summary

This PR widens DatabaseReplicated::shouldReplicateQuery for KeeperMap so mixed comment ALTERs and comment-only MODIFY COLUMN go through replicated DDL instead of updating only local metadata. The new stateless test checks the previously missing carriers against both system.tables and the replicated metadata stored in Keeper, and I do not see a remaining OSS-side correctness issue in the current diff.

Missing context / blind spots
  • ⚠️ I could not validate the Cloud-only SharedDatabaseCatalog::shouldReplicateQuery mirror reached from InterpreterAlterQuery.cpp:502, because that implementation is not present in this checkout. A Cloud-side source review or test is still needed to confirm the same KeeperMap routing gap is not open there.
Final Verdict

✅ No new OSS-side inline findings on the current head.

LLVM Coverage Report

⚠️ No coverage measurement for commit 735aabd: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

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

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach @antonio2368, could you review this? DatabaseReplicated::shouldReplicateQuery gated the replicated path for a KeeperMap ALTER on the parser-level ASTAlterQuery::isCommentAlter, which matches only a single-type command list, while IStorage::checkAlterIsPossible accepts comment alters per command, so a mixed comment ALTER ran locally with no metadata transaction and left Keeper holding the pre-ALTER CREATE statement.

Comment thread src/Databases/DatabaseReplicated.cpp Resolved
@PedroTadim PedroTadim self-assigned this Sep 4, 2026
…he storage's set

`isSettingsOrCommentAlter` also admits `MODIFY`/`RESET SETTING`, which `KeeperMap` can
never apply: it inherits `IStorage::checkAlterIsPossible`, and that rejects every
non-comment command. The previous comment described only the narrower set, so it read
as a characterization of the predicate.

The direction is deliberate. Admitting an `ALTER` the storage rejects costs one
replicated DDL log entry and the same error; excluding one the storage applies runs it
locally without a metadata transaction and leaves the `CREATE` statement in Keeper
stale. An AST-level mirror of `AlterCommand::isCommentAlter` here would keep that drift
risk and diverge from the sibling routing site at `DDLWorker.cpp:842`, which uses the
same helper.
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 735aabdd5 with master e4c374202 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of bcaec2e05; 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, 15 s compile time in total, 7 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
if (is_keeper_map_table(query_ptr) && !alter->isCommentAlter())
/// A `KeeperMap` `ALTER` the storage applies rewrites the `CREATE` statement kept in Keeper and
/// needs a metadata transaction, so this predicate is deliberately wider than the storage's set.
if (is_keeper_map_table(query_ptr) && !alter->isSettingsOrCommentAlter())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

MODIFY/RESET SETTING now enter the replicated path even though KeeperMap can never apply them, and they still fail with the same code and message — except on a replica that can't enqueue, which now gets the enqueue error rather than NOT_IMPLEMENTED. @groeneai can you add test cases for these?

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.

Added in db40ae0, in the test this PR already adds:

ALTER TABLE 05076_keepermap MODIFY SETTING some_setting = 1; -- { serverError NOT_IMPLEMENTED }
ALTER TABLE 05076_keepermap RESET SETTING some_setting; -- { serverError BAD_ARGUMENTS }
ALTER TABLE 05076_keepermap COMMENT COLUMN k 'col-4', MODIFY SETTING some_setting = 1; -- { serverError NOT_IMPLEMENTED }

followed by the same local-vs-Keeper comment check the earlier arms use, so the mixed batch is pinned to leave both sides untouched as well (col-4 must not appear on either). The two codes differ because RESET SETTING is rejected in AlterCommands::validate ("Cannot alter settings, because table engine doesn't support settings changes") while MODIFY SETTING gets as far as IStorage::checkAlterIsPossible ("Alter of type 'MODIFY_SETTING' is not supported by storage KeeperMap"). Dropping the serverError annotations makes the test fail, so the arms are not vacuous, and 50 runs sequentially plus 50 at --jobs 8 are green.

I did not pin the cannot-enqueue half, and I would rather explain why than add an arm that flakes. The only stateless lever for it is database_replicated_initial_query_timeout_sec = 0, which does not force the error, it races the worker thread in DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry. Over 100 runs on an idle debug server I measured 99 UNFINISHED and 1 NOT_IMPLEMENTED, which puts the 50 runs of the flaky check at roughly a 40% chance of a red. Forcing it deterministically needs either the server-global SYSTEM STOP REPLICATED DDL QUERIES, which would make the test no-parallel and disturb concurrent tests, or an integration test that stops a replica. I am happy to add the integration test if you want that arm covered too.

…` database

The widened routing predicate also admits pure `MODIFY SETTING` / `RESET SETTING` and
comment-first mixed batches, none of which `KeeperMap` can apply. These arms pin what a
reader of the diff otherwise has to take on trust: on a healthy replica the user-visible
error is unchanged (`NOT_IMPLEMENTED` from `IStorage::checkAlterIsPossible`,
`BAD_ARGUMENTS` from `AlterCommands::validate` for `RESET SETTING`), and a rejected batch
leaves both the local metadata and the copy the database publishes in Keeper untouched,
even though it now reaches the replicated DDL log. Requested in review of this PR.

They are not vacuous: with the `serverError` annotations removed, the test fails.

This also corrects an over-claim in the first commit of this PR, which said such queries
"still fail with an identical error code and message before and after". That holds on a
healthy replica only. A replica that cannot enqueue now answers the enqueue error instead
of `NOT_IMPLEMENTED`, and that half is deliberately not pinned here. The only stateless
lever for it is `database_replicated_initial_query_timeout_sec = 0`, which races the DDL
worker in `DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry`: measured 99
`UNFINISHED` and 1 `NOT_IMPLEMENTED` over 100 runs, so across the 50 runs of the flaky
check it would fail about 40% of the time. Deterministic coverage needs either the
server-global `SYSTEM STOP REPLICATED DDL QUERIES`, which would force `no-parallel`, or an
integration test.

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

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - db40ae0

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
Stress test (amd_tsan) / Cannot start clickhouse-server, Check failed the same abort on 11 consecutive restarts, unreachable from this diff: the stateless test 05054_embedded_rocksdb_explicit_dir_file_grant leaves a table in a separate ..._poc_... database whose explicit rocksdb_dir under user_files is already gone, so startup metadata loading cannot attach it (Code: 555 ... Failed to open rocksdb path ... CURRENT: No such file or directory). Bucketed on that context rather than the multi-cause Cannot start clickhouse-server bucket, it also fires on 26.3 release-branch runs and on unrelated PR #94148 a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260905-000000

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Cannot start clickhouse-server row of the CI finish ledger (05054 EmbeddedRocksDB leftover directory): #118220

@PedroTadim
PedroTadim added this pull request to the merge queue Sep 6, 2026
Merged via the queue into ClickHouse:master with commit 554989a Sep 6, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 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-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

3 participants