Skip to content

Clean up Keeper state after a failed Replicated CREATE - #115958

Open
groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-rollback-on-failed-create-replicated
Open

groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-rollback-on-failed-create-replicated

Conversation

@groeneai

@groeneai groeneai commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #69433

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

A CREATE TABLE ... ReplicatedMergeTree that fails once its replica is registered in Keeper now removes that registration again, when it can prove it is its own. Previously it was left behind, so every later CREATE of the same replica failed with REPLICA_ALREADY_EXISTS and DROP TABLE IF EXISTS could not help. CREATE DATABASE ... ENGINE = Replicated now retries a Keeper request that failed ambiguously. Where a leftover survives, the error names the SYSTEM DROP REPLICA command that removes it.

Description

On 26.8 (reported on 26.8.1.1733), a transient Keeper failure during CREATE can leave the replica's registration in Keeper while no local object is created, permanently bricking the name: the rollback in place, dropIfEmpty(), only removes local disk state. Two seams reach that state by default, the StorageReplicatedMergeTree constructor's catch-all and database->createTable().

Ownership is proven, never inferred: creator_info, written atomically with the replica nodes, must equal this table UUID and this server UUID. Both seams require a non-nil table UUID; without one (Ordinary, Memory) behaviour is unchanged. They also refuse when is_active exists, as SYSTEM DROP REPLICA does, and when the replica ever started (non-empty host or log_pointer, or any part), since an earlier table with the same explicit UUID has the same creator_info.

The registration is kept once this statement has published anything: inside a Replicated database the entry's metadata transaction is committed before the table is attached, so the entry can be visible to the other replicas while the table is still absent locally. A transaction that was never committed published nothing; after a commit attempt, the entry's /committed node settles it, and an unanswerable read keeps it. The local directory is still removed there, since an explicit table UUID makes the retry resolve to the same path.

For the database, createReplicaNodesInZooKeeper is idempotent but tryConnectToZooKeeperAndInitDatabase had no retry ladder. It now retries on CREATE only; ATTACH and startup still defer to the DDL worker.

Cleanup goes through dropReplica, whose /replicas + /dropped-lock protocol already protects a concurrent creator, plus the zero-copy lock root when it reports the last replica, since that node lives outside the table subtree. Local cleanup stays the non-recursive dropIfEmpty(), which keeps what a table_disk root already held. A started leftover of a previous statement looks foreign, so it is left to the named command.


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

groeneai and others added 7 commits August 21, 2026 23:58
…ails

A transient Keeper failure during CREATE could leave the replica's own
registration in Keeper while no local object was created, so every later
CREATE of the same replica failed with REPLICA_ALREADY_EXISTS and
DROP TABLE IF EXISTS could not help.

The rollback used at the fault seam in InterpreterCreateQuery was
MergeTreeData::dropIfEmpty(), which only removes local disk state. At that
point the storage is already constructed, so storage.drop() is used
instead: it performs owner-scoped Keeper cleanup through the established
dropReplica path, which is what validateStorage twelve lines above
already does. On the mid-construction path nothing is deleted, and the
/replicas + /dropped-lock protocol inside dropReplica already protects a
concurrent creator.

For a Replicated database, createReplicaNodesInZooKeeper is already
idempotent (ecfe9d9) but tryConnectToZooKeeperAndInitDatabase had
no retry ladder, so nothing re-entered after a tryMulti that committed and
then returned a connection error. It now retries on CREATE only, with the
retry settings taken from the creating query's context, because the
database object keeps only the global context and would otherwise ignore
an explicit keeper_max_retries. ATTACH and server startup still defer to
DatabaseReplicatedDDLWorker, which re-invokes this from its own loop.

A leftover from a previous statement is deliberately not claimed
in-process: both reuse checks are keyed on a per-object identity (table
UUID, database UUID) that differs across statements by design
(57aa049), so such a registration is indistinguishable from a
foreign one. The REPLICA_ALREADY_EXISTS messages that remain reachable now
name SYSTEM DROP REPLICA ... FROM ZKPATH and SYSTEM DROP DATABASE REPLICA,
which is the recovery path for that case.

Adds a ONCE failpoint at the replica-node transaction boundary so the
ambiguous-commit state can be reproduced deterministically from a test.

Closes: ClickHouse#69433
… reaches

The rollback for a failed CREATE of a Replicated table was
MergeTreeData::dropIfEmpty(), which only removes local disk state. When
the failure happened after replicas/<r> was written, the registration
survived in Keeper with no local table to DROP, so every retry failed
with REPLICA_ALREADY_EXISTS and only SYSTEM DROP REPLICA could recover.

Two seams are reachable with default settings once the replica exists:
the StorageReplicatedMergeTree constructor's catch-all, and
database->createTable(), whose metadata commit can throw after the
constructor returned (DatabaseAtomic::commitCreateTable removes only the
.sql.tmp). The constructor seam now removes just its own registration
via dropReplica; the interpreter seam rolls back through storage.drop(),
which is the shape validateStorage already uses, and the existing
fault-injection branch shares that same lambda instead of its own copy.

Ownership is proven rather than inferred: creator_info, written
atomically with the replica nodes, must equal this table UUID and this
server UUID, or nothing is deleted. A leftover of another statement,
table or server therefore survives for the operator command. Cleanup
goes through dropReplica so the /replicas + /dropped lock protocol keeps
protecting a concurrent creator of the same table, and both rollbacks are
best effort so the original exception is what the user sees.

For CREATE DATABASE ... ENGINE = Replicated,
createReplicaNodesInZooKeeper is already idempotent but
tryConnectToZooKeeperAndInitDatabase had no retry ladder, so nothing
re-entered after an ambiguous tryMulti. It now retries on CREATE only,
with the settings taken from the creating query so an explicit
keeper_max_retries = 0 is honoured. Those settings hold the query's
process list element, so they are built only for CREATE and no longer
stay alive for the lifetime of an attached database.

The recovery hints render the path SYSTEM ... FROM ZKPATH resolves.
That syntax derives the Keeper from the literal, so the previous
stripped path was routed to the default Keeper: it either found nothing
or could delete a same-named inactive replica in another coordination
service. Interpolated literals are quoted so a name containing a quote
still yields a copyable command.

A cross-statement leftover is still not removed in-process, because
creator_info differs across statements by design; that case recovers
through the command the message now names.

Closes: ClickHouse#69433
…wnership

Review round 2 found two defects in the rollback added in round 1.

The ownership check compared creator_info against the table UUID and the server
UUID. Databases without their own UUID (Ordinary, Memory) reset the table UUID,
so that string is identical for every replicated table on the server. A CREATE
that collided with a live table's Keeper path therefore matched, and the rollback
removed the live replica's registration and, when it was the only replica, the
shared table metadata. Reproduced: the surviving table's INSERT then failed
permanently, where master leaves it untouched. Both rollback seams now require a
non-nil table UUID, which keeps master's behaviour for those databases: the
registration stays reusable, so a retry still completes.

The rollback around database->createTable assumed the table cannot be published
before that call throws. DatabaseOnDisk::commitCreateTable attaches the table
before a replaceFile that can throw, and createTable calls
removeDetachedPermanentlyFlag, which rethrows, after a successful commit. In
those windows drop() deleted the data and Keeper state of a table still present
in the database map. The rollback now runs only while the database has not
accepted the storage; in the published window the table is recoverable with
DETACH/ATTACH and DROP TABLE cleans up both.

The constructor seam also refuses when an active node is present, as the
interactive SYSTEM DROP REPLICA path does.

Tests: 02888 gains a Memory-database section covering the degenerate identity
(live, detached and own-statement failures) and a section covering both sides of
the publication boundary, using two new ONCE failpoints in
DatabaseOnDisk::createTable. Each guard was removed individually and the arms
redden at three distinct lines.
…lock root

Three defects in the failed-CREATE rollback, all found by review of the previous round.

Inside a Replicated database, DatabaseAtomic::commitCreateTable commits the entry's
metadata transaction before it moves the metadata file and attaches the table, so a
failure in that window leaves the table absent locally while the entry is already
visible to the other replicas. The rollback's isTableExist check passes there and the
replica is removed, deleting a table subtree the other replicas are about to use. The
registration is now only removed when this statement did not already publish the entry,
mirroring the prohibition the atomic POPULATE path already states for the same reason.

Declining to remove the registration must not also decline to remove the local data
directory: with an explicit table UUID the retry resolves to the same data path, and a
leftover directory fails it with TABLE_ALREADY_EXISTS. The rollback therefore falls back
to dropIfEmpty(), which is what the fault-injection seam did before this work.

createNewZooKeeperNodes creates the zero-copy lock root under
remote_fs_zero_copy_zookeeper_path, which is outside the table subtree that dropReplica
removes, so the constructor rollback orphaned one node per failed CREATE under a path
shared by all tables. It now collects and removes those paths exactly as drop() does.

The identity test moves into tryRemoveOwnReplicaFromZooKeeper, next to the comparison it
is about, so a future caller cannot lose it.

Tests: a new failpoint inside the commit-to-attach window drives the first case from a
Replicated database, and asserts the entry, the registration, the table metadata and an
advanced digest all survive. A second arm covers the retry after the registration is
kept. A third arm asserts the zero-copy root is removed on a disk that supports it, with
a plain DROP TABLE as the comparison. Each arm was shown to fail with only its own guard
removed, on a Build-ID-verified binary.
Collecting the zero-copy lock roots is part of the rollback, and naming them
reads the table's shared ID. The shared ID is created after the replica is
registered, so on a failure in between there is none to read and the attempt to
create one can throw. That throw happened before dropReplica, so the whole
rollback was skipped and the replica registration was left behind, which is the
state this change set exists to remove. A lock root left behind is recoverable
with SYSTEM DROP REPLICA; a registration left behind is what makes the retry
fail with REPLICA_ALREADY_EXISTS.

Reproduced without fault injection: an unresolvable macro in
remote_fs_zero_copy_zookeeper_path fails the CREATE after registration, and the
registration survived it. Covered by section 13 of
02888_replicated_merge_tree_creation.

Also make section 9 create the auxiliary Keeper chroot before using it, as
02311_system_zookeeper_insert does. The section reads zookeeper2, whose
configured root only some test flavors create, so it depended on an unrelated
test having run first in the same server.

Co-Authored-By: Claude Opus <[email protected]>
…EATE rollback

The rollback of a failed CREATE removed the replica registration only when the query
carried no ZooKeeper metadata transaction. Inside a Replicated database the initial query
also carries one, installed by DatabaseReplicatedTask::makeQueryContext for initial and
secondary queries alike, so every pre-commit failure there was treated as if the table had
already been published to the other replicas and the registration was kept.

Nothing is published in that window: the log entry becomes executable on the other
replicas only once the transaction's commit creates its /committed node, without which the
DDL worker refuses the entry. Keeping the registration there is what breaks the retry: the
implicit table UUID is regenerated, creator_info no longer matches, the reuse branch cannot
adopt the leftover and the CREATE fails with REPLICA_ALREADY_EXISTS. That is the failure
reported in issue ClickHouse#69433.

Test publication directly instead. A transaction blocks the removal once it has been
executed, which covers the initial query that already committed, or when it is not the
initial query, since a secondary query replays an entry the initiator already published and
must never remove the registration whatever its own state is.

Add a 04946 section that pins the removal: an implicit UUID and an explicit Keeper path, so
the retry cannot reuse a leftover, a failure injected in the pre-commit window, and
assertions that nothing was published, that the registration is gone and that the plain
retry then succeeds. The existing arms could not catch this: section 6 injects after the
commit, and section 7 runs with a fixed UUID whose reuse branch adopts any leftover.

Also provision the auxiliary Keeper chroot 04946 uses before its first zookeeper2 database,
as 02888 already does, since a client whose configured chroot is absent throws at
construction and only some test flavors create it; and wait for the Query gauge to return to
its baseline in section 4 rather than comparing it once, because that gauge counts every
process-list query, internal ones included, while a retained increment never goes away.
Two states were conflated. A metadata transaction is marked as no longer pending before its multi
runs, so a transaction that Keeper rejected atomically was read as one that had published its DDL
entry, and the replica registration of a rejected CREATE was kept. With an implicit table UUID no
retry can adopt that registration, which is the permanent failure this change set removes; it
survived here in a narrower trigger. The visibility of an entry is now taken from Keeper itself,
from the existence of its `/committed` node, and any answer that cannot be obtained keeps the
registration.

The constructor's own rollback is narrowed to an initiating CREATE. A secondary creation replays an
entry another host published, or restores a backup, so its registration is shared and removing it
would diverge this replica from the ones executing the same entry successfully.

The new arm of 04946 reaches the rejected-transaction state without fault injection, by pre-creating
the metadata node the entry transaction of the table would create. It asserts the arming condition
and the absence of `/committed` separately from the oracle, and pins the removal by re-creating a
table at the same Keeper path.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Two known limits of this PR, stated up front rather than left for review to find:

  • Ownership cannot be proven when the table UUID is given explicitly. The check is creator_info == <table UUID>|<server UUID>, and both halves survive across statements, so two CREATEs naming the same explicit UUID on the same server are indistinguishable. If an older, inactive, non-empty registration sits at that replica path, a failing CREATE can remove it. An implicit UUID (the reported case, and the default) is unaffected, and a matching local data directory makes the constructor refuse earlier — but the gap is real. A per-CREATE token written atomically with the replica nodes would close it.
  • /committed absent is treated as proof that nothing was published. DDLWorker::cleanupQueue deletes the whole log entry once entry_number + logs_to_keep < max_log_ptr, so absence is ambiguous between never-committed and committed-then-pruned. Defaults (logs_to_keep = 1000, 60 s cleanup period) make it rare, but the safe form is for ZooKeeperMetadataTransaction to record its own committed / rejected / ambiguous outcome and fail closed on the first and last.

Both are narrow and both fail toward keeping Keeper state in the common case, so I would rather ship the fix for the reported bug with these named than hold it. Happy to follow either remedy if you prefer it in this PR.

Internal second-model review — 14 findings adjudicated (5 agreed, 9 withdrawn)

Independent cold review plus a second model, adjudicated against the code. AGREE = confirmed; DISAGREE = refuted with a citation.

# Finding Verdict
❌ hasProvableCreationIdentity tests only uuid != Nil, so an explicit UUID does not identify a statement AGREE — creator_info (SRMT.cpp:1301) combines a preserved explicit UUID (CreateQueryUUIDs.cpp:59-74) with a persistent ServerUUID. Not fixed; disclosed above.
❌ Absence of /committed is not durable proof of non-publication AGREE — single write site DDLTask.cpp:726; entry removed wholesale by DDLWorker.cpp:1027-1092 under DatabaseReplicatedWorker.cpp:793-797. Not fixed; disclosed above.
⚠️ No arm seeds an inactive prior registration with matching identity AGREE — section 1's second attempt sees a clean path (the first now cleans up); section 10 covers only nil UUIDs.
⚠️ The post-commit arm cannot detect misclassification after pruning AGREE — the failpoint throws on the line after txn->commit() (DatabaseAtomic.cpp:427-433), so /committed is necessarily still present.
⚠️ Section 7 does not exercise the local-only cleanup it claims AGREE — its seam (InterpreterCreateQuery.cpp:2514) precedes the commit, so with an explicit UUID the branch taken is the full drop(), not dropIfEmpty(). Its comments overstate this.
💡 Missing no-fasttest on the extended 02888 DISAGREE — zookeeper in Tags already yields NO_ZOOKEEPER (clickhouse-test:2926); Fast test runs --fast-tests-only; storage_conf_local.xml is symlinked unconditionally (install.sh:510).
💡 CurrentMetrics::Query is a server-global oracle DISAGREE — the failure mode is a permanently retained QueryStatusPtr, which never converges; the 30 s loop absorbs in-flight queries.
💡 Comment budget exceeded DISAGREE — 55 comment vs 194 code lines added in src/; both 4-line blocks state non-obvious invariants, not fix history.
💡 Six further nits (carrier enumeration, revert-sensitivity, crash sweep, in-diff claims, exception safety, plan drift) DISAGREE — each withdrawn against a citation; details in the ledger.

Notable verifications: dropReplica's /replicas + /dropped-lock protocol is reused unchanged, and the zero-copy roots are collected before and removed after it, mirroring drop() (SRMT.cpp:1601,1625); restoreDatabaseInKeeper calls initDatabaseReplica directly (DatabaseReplicated.cpp:2389), so RESTORE is structurally outside the new retry ladder; FROM ZKPATH resolves its Keeper from the literal (ParserSystemQuery.cpp:231, InterpreterSystemQuery.cpp:1801), which is why the hint names the auxiliary Keeper.

Session id: cron:clickhouse-review-slot-10:20260822-225900

@clickhouse-gh clickhouse-gh Bot closed this Aug 23, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed97915]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

At ed9791576c821270b36798bc981b9396f9161dad, this PR cleans up owned Keeper registrations after failed CREATE TABLE operations, retries replicated database initialization, and supplies recovery commands. The latest change addresses the previously reported fault-injection data-loss path, whose thread is now resolved. A separate validation rollback still deletes pre-existing detached data, and the previously discussed publication-state ambiguity remains.

Findings

❌ Blockers

  • src/Interpreters/InterpreterCreateQuery.cpp:3080: Validation failures bypass the safe rollback. With case 14's writable table_disk containing detached data, creating the replicated table with an additional _part_offset UInt64 column and allow_reserved_column_names=0 completes construction but fails in validateStorage. Its catch calls storage.drop at line 2771, before this helper is constructed. MergeTreeData::dropAllData consequently deletes the pre-existing detached part. This path predates the PR but violates the same preservation invariant. Apply the Keeper-only removal plus dropIfEmpty separation there too, or explicitly link an issue tracking this remaining data-loss path.

  • src/Interpreters/InterpreterCreateQuery.cpp:3104 [dismissed by author -- https://github.com/Clean up Keeper state after a failed Replicated CREATE #115958#discussion_r3838653704]: A pruned commit is still classified as unpublished. The isExecuted guard handles unattempted commits, but after an attempted commit, DDLWorker::cleanupQueue can remove /committed together with its log entry. A delayed local failure then permits removing a registration, potentially including the shared table subtree, despite published database metadata. The retention window limits frequency; it does not establish non-publication. Preserve registrations after successful or ambiguous commits using durable transaction outcomes, while allowing cleanup after definitive rejection. No duplicate inline comment was posted.

Missing context / blind spots
  • ⚠️ Review was based on the current source and PR diff; no local ClickHouse binary or build was available for a runtime reproduction. The current head's full test suite was held by review threads, and its targeted test report contains no executions.
Tests
  • ⚠️ Add a case 14 variant that fails column validation without a failpoint and proves all three detached rows remain recoverable.
  • ⚠️ Cover an attempted, committed transaction whose log entry is pruned before local rollback; the current post-commit failpoint does not establish safety after pruning.
Final Verdict

Status: ❌ Block. Address or explicitly track the pre-existing validation data-loss path, and make attempted-commit classification preserve published state after log pruning.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 23, 2026
Two mechanical style violations on 04946, both in the test only.

1. check_style.py's functional-test rule is a plain substring test,
   `if "fail" in test_case`, so the name ..._keeper_failure trips it on
   "failure". Renamed the .sh and the .reference to ..._keeper_rollback.

2. various_checks.sh requires the zookeeper-path prefix to appear on the
   same physical line as Replicated*MergeTree(. The test did interpolate
   $CLICKHOUSE_TEST_ZOOKEEPER_PREFIX, but hoisted into shell variables
   defined above the engine clause, so the same-line grep could not see
   it. Inlined the prefix on the five engine lines, which is also how the
   sibling 02888 and the repo majority spell it. The braced form
   ${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX} does NOT satisfy the rule; the
   pattern matches a literal $CLICKHOUSE_..., so the unbraced spelling is
   required. The three shell variables stay in place and the oracles keep
   reading them, and the inlined literal expands byte-identically.

Verified against the real CI code rather than by inspection: over all
14312 traversed files check_functional_test_cases, check_file_names and
check_gaps_in_tests_numbers are clean, and various_checks.sh reports no
violation. Both matchers were positive-controlled so a silent pass could
not be mistaken for a clean one: re-bracing an engine line makes the
zookeeper-path rule name this file, and a synthetic ..._failure.sh name
makes the substring rule fire. 04946 and 02888 both pass on the shipping
binary, and a deliberately wrong table path reddens 04946, so the green
result is not vacuous.
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ad59008d7 with master dd7889a11 (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.

Object file sizes

15 object files changed (+87.32 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseReplicated.cpp.o 1.21 MiB 1.28 MiB +63.30 KiB (+5.09%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

Both tests exceeded, or came close to, the 180s per-run limit the flaky check
applies (tests/clickhouse-test:3566-3569): a single run of
02888_replicated_merge_tree_creation measured 297s on amd_asan_ubsan and 172s on
amd_msan, and 04946_replicated_database_creation_keeper_rollback measured 160s on
amd_asan_ubsan, which is 89% of the limit.

The cost is the number of client processes, not the work the server does. For
02888, summing query_duration_ms over one run's own log_comment gives 6.8s of
server time out of 27.2s of wall time; the other 20.4s is 134 client startups at
about 150ms each. The runner passes the randomized settings as command-line
options (shell_config.sh:44), so every additional client also parses ~137 of
them: 20 invocations of SELECT 1 cost 60ms each without those options and 82ms
each with them, while one invocation running 20 statements costs 83ms in total.

So group the statements that print nothing on stderr, and keep a separate client
only where the failure itself is the assertion and stderr is piped to grep. The
statements, their order within each arm and both .reference files are unchanged,
and the summed server time stays the same (6.9s), so this removes process
startups and nothing else.

02888 goes from 133 client invocations to 45 and 04946 from 75 to 35. Measured
locally on a debug build, interleaving the old and new versions against one
server: 02888 29.5s -> 15.2s over 10 rounds each, 04946 15.7s -> 9.2s over 6
rounds each, no failures in 32 runs. Applying those ratios to the CI figures
above puts the worst flavor at about 153s for 02888 and 94s for 04946.

Note a batch stops at its first failing statement, so statements that must all
run are only grouped when none of them can fail.
The arm plants a node under the database's `/metadata` that is deliberately not
parseable as table metadata, in order to make the next entry transaction fail
atomically. Grouping that INSERT into the same client call as the CREATE DATABASE
let it run while the replica's DDL worker had not yet taken its startup snapshot
of `/metadata`. The worker then read the node, failed to parse it
(SYNTAX_ERROR in parseQueryFromMetadataInZooKeeper), and restarted initialization
from scratch, which it repeats indefinitely because the node never goes away.
A worker stuck in that loop never publishes `current_task`, so the arm's own
CREATE TABLE waited out database_replicated_initial_query_timeout_sec (300s) and
reported UNFINISHED, and the following statement did the same, taking the test
past the 600s per-test limit.

Observed on Stateless tests (amd_tsan, flaky check) at 600030ms, 1 FAIL in 116
runs: 379 initialization attempts, all with the same SYNTAX_ERROR, against 1
attempt in every healthy run of the same job.

SYSTEM SYNC DATABASE REPLICA waits for the replica's log_ptr to reach
max_log_ptr, which happens after the snapshot read, so the node cannot appear
before it. Measured with the recovery phase widened by the
database_replicated_delay_recovery failpoint: without the sync the statement
returns with log_ptr=0 against max_log_ptr=1 in 10 of 10 runs; with it, log_ptr
equals max_log_ptr in 10 of 10. Racing the node into the window reproduces the
loop in 8 of 8 runs. Test output is byte-identical to the reference.
/// A transaction carrying no task path is not an entry of the DDL log.
const String task_path = txn->getTaskZooKeeperPath();
if (txn->isInitialQuery() && !task_path.empty())
published = txn->getZooKeeper()->exists(fs::path(task_path) / "committed");

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.

exists(task_path + "/committed") is not durable proof that the DDL was never published. DDLWorker::cleanupQueue eventually deletes the whole log entry once it falls behind max_log_ptr, so a committed entry that has already been pruned also makes this check return false. In that case registration_is_ours flips to true and the new rollback can drop() a replica/table subtree that was already published to other replicas. This needs a fail-closed committed/rejected/ambiguous state from ZooKeeperMetadataTransaction, not a negative lookup on a prunable node.

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.

Agreed on the mechanism, and this is the second limit I listed in the adjudication comment above. Two things I measured since:

The window is bounded, not merely rare. The commit multi sets max_log_ptr to the entry's own number (DDLTask.cpp:727) atomically with creating /committed, and the pruning predicate is entry_number + logs_to_keep < max_log_ptr with logs_to_keep = 1000 (DatabaseReplicatedWorker.cpp:793, DatabaseReplicatedSettings.cpp:25). So immediately after that commit the predicate is false, and pruning the entry needs more than 1000 further committed entries on that database inside the window between the commit and the local metadata move failing, with cleanup_delay_period = 60s as a second brake. Pruning also cannot overlap execution: the removal of active/<host> is pushed into task.ops (DDLWorker.cpp:736) before those ops are moved into the transaction (:764 then :575), so it lands in the same multi as /committed, and cleanupQueue skips an entry whose active is ZNOTEMPTY (:1053-1063).

The fail-closed state you are asking for already exists and is public. ZooKeeperMetadataTransaction::isExecuted() is state != CREATED, and commit() sets FAILED before the multi and COMMITTED after (DDLTask.cpp:790-803), so an ambiguous or throwing multi reads as executed. It is in-memory, so pruning cannot affect it, and DDLWorker.cpp:597 already uses it for this exact question. That makes the remedy a one-line swap rather than new machinery.

One caveat if it is taken: published starts as txn != nullptr and is only narrowed inside isInitialQuery() && !task_path.empty(). Both guards have to stay, or a secondary replica would classify a published registration as its own and drop() a subtree the other replicas already have, which is the reported bug inverted.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@antonio2368 this is the Keeper-rollback fix for #69433 that @ PedroTadim asked me to route to you. It covers both halves of the report: CREATE DATABASE ... ENGINE = Replicated and CREATE TABLE ... ReplicatedMergeTree.

One open decision for you. I shipped with two limits named up front in the comment above, and the automated review has since re-raised both. For the second one, absence of /committed being ambiguous once the log entry is pruned, the fail-closed state already exists and is public: ZooKeeperMetadataTransaction::isExecuted() is state != CREATED, with commit() setting FAILED before the multi and COMMITTED after (DDLTask.cpp:790-803), and DDLWorker.cpp:597 already uses it for this question. Swapping the Keeper read for it is a one line change, keeping the existing isInitialQuery() && !task_path.empty() guards so a secondary replica is never misclassified.

The first limit, an explicit table UUID not identifying a single statement, needs a per-CREATE token written atomically with the replica nodes, so it is a real if small addition and it only bites on non-default database_replicated_allow_explicit_uuid modes 1 and 3.

Want either or both in this PR, or as a follow-up? I would rather do them in one push than iterate.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 931a142

CI is fully finished at this commit and no check failed, so no ledger row is owed.

Evidence: no check queued or in progress; Config Workflow, Style check and Finish Workflow all
green; 155 praktika nodes with every node in {OK, SKIPPED} and none dropped. A CIDB query at this
commit, filtered against the measured healthy-token set, returns zero non-green rows against a
control of 293,390 rows at the same commit, so that zero is a real filtered subset rather than an
empty query. The four unstable rows present are Performance Comparison per-query verdicts,
which are a review class rather than a failure.

Session id: cron:our-pr-ci-monitor:20260823-183000

@antonio2368

Copy link
Copy Markdown
Member

@PedroTadim not all issues that use Keeper are Keeper related. Eg this is RMT related.
@groeneai do you know who would be better suitable to review this PR?

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim not all issues that use Keeper are Keeper related. Eg this is RMT related. @groeneai do you know who would be better suitable to review this PR?

Yes, sorry, maybe someone from @tavplubix team can review? @tiandiwonder or @tuanpach ?

@groeneai

Copy link
Copy Markdown
Collaborator Author

The source half of the diff splits into two components in component-tree.yaml:

  • src/Databases/DatabaseReplicated.{cpp,h}, DatabaseAtomic.cpp, DatabaseOnDisk.cpp (~118 added lines): comp-database-engines, experts tavplubix, alesapin, tuanpach.
  • src/Storages/StorageReplicatedMergeTree.{cpp,h} (~70 added lines): comp-replication, experts CheSema, tavplubix, alesapin.

So @ tuanpach from PedroTadim's suggestion is tree-backed, and @ tavplubix is the one name covering both halves. If the RMT constructor rollback is worth a separate pair of eyes, @ CheSema is the third name on comp-replication. @ tiandiwonder is listed under comp-mergetree, but not under either of those two leaves.

The src/Interpreters/InterpreterCreateQuery.cpp change (~56 lines) is only the call site that invokes both rollbacks, so I do not think it pulls in the query-execution owners.

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e4ddd8a8-1cdd-4094-93e4-5dcdbd98a446
  • MIRAI run: 74e88819-ea97-40e8-ad2b-43411f50f6ed
  • PR check IDs:
    • clickbench_564692_1788152647
    • clickbench_564705_1788152646
    • clickbench_564711_1788152646
    • tpch_adapted_1_official_564998_1788152656
    • tpch_adapted_1_official_565100_1788152664
    • tpch_adapted_1_official_565114_1788152665

`tests/config/install.sh` links `zookeeper_auth.xml` only on a coin flip and
`database_replicated.xml` only for that flavour, so `zookeeper2` does not exist in every run.
Where it does not, `CREATE DATABASE ... Replicated('zookeeper2:...')` fails with
`Unknown auxiliary ZooKeeper name` before reaching the recovery hint this arm checks, and the
setup error lands in the test's stderr - which is what made the private sync run report the test
as failed in every sequential configuration.

Guard the arm on its own setup statement and print the line it would have produced, so the
reference is unchanged and the coverage is unchanged wherever the auxiliary Keeper exists.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ad59008d7633fa044396c5193598f896e0723d81

Every failure below has an owner: a fixing PR (ours 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_asan_ubsan, db disk, old analyzer, 4/6) / Container memory budget exceeded (/docker) the job's containers breach the /docker cgroup budget and the kernel kills processes inside it, so the shard errors at job level with no test-level failure #117202 (external, merged 2026-08-31 11:05:36Z)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) same signature #117202 (external, merged 2026-08-31 11:05:36Z)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) same signature #117202 (external, merged 2026-08-31 11:05:36Z)
CH Inc sync - CH Inc sync (private, not actionable by me)

None of the three can be caused by this PR. Its diff is the Keeper-rollback path on failed
CREATE (DatabaseAtomic.cpp, DatabaseOnDisk.cpp, DatabaseReplicated.cpp,
InterpreterCreateQuery.cpp, StorageReplicatedMergeTree.cpp, one failpoint and two stateless
tests), which cannot change how much memory an unrelated integration module's containers use.
Mergeable Check reported Failed: 3, matching the integration set exactly, and all three failing
shards report at job level with an empty test set.

This head predates the fix: 7fc3004ed25a2dc8aa66428f4f010244dea3046a is not an ancestor of
ad59008d7633, measured by content rather than by commit distance (the symbol GDB_ATTACH_LOCK
that #117202 introduces in tests/integration/integration-tests-entrypoint.sh is absent from this
head and present at the fix), so a master merge would clear all three. I have deliberately not
pushed one: this head is a commit of @ alexey-milovidov's, so the branch is being edited by someone
else right now and it is not mine to advance. Merging master in will pick the fix up whenever its
next push happens.

Reports:

Session id: cron:our-pr-ci-monitor:20260831-173000

@clickhouse-gh clickhouse-gh Bot added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Sep 4, 2026
groeneai and others added 8 commits November 18, 2026 15:27
…-on-failed-create-replicated

# Conflicts:
#	src/Databases/DatabaseOnDisk.cpp
#	src/Databases/DatabaseReplicated.cpp
#	src/Databases/DatabaseReplicated.h
#	src/Interpreters/InterpreterCreateQuery.cpp
#	src/Storages/StorageReplicatedMergeTree.cpp
`creator_info` pins a registration to the table UUID and the server, but an
earlier table created with the same explicit UUID on the same server has the
same value. When such a table is gone locally and inactive, a CREATE that fails
with REPLICA_ALREADY_EXISTS on its registration would remove a replica that has
data. Take only a registration that never started, with the criteria the reuse
check in createReplicaAttempt uses: `host` and `log_pointer` exist and are
empty, and `parts` is empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A metadata transaction that was never committed published nothing, so the DDL
entry is unpublished without a Keeper round trip, and the absence of
`/committed` after the log entry is pruned no longer matters for any failure
before the commit. After an attempt, the Keeper read still tells a rejected
commit from a lost reply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The command the REPLICA_ALREADY_EXISTS message prints removes the registration
the failed attempt left under `${ZK}/zero`, and the retry then succeeds. This
cleans the leftover up and runs the database hint end to end, which was only
grepped before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ured

Case 9 of 02888 has the same setup as case 5 of 04946 and failed the same way
where `zookeeper2` is absent. Both now skip only on `Unknown auxiliary
ZooKeeper name` and print any other error, so a regression in the
auxiliary-Keeper path fails the test instead of turning the case off.
02888 gets `no-shared-merge-tree`: it asserts the ReplicatedMergeTree layout
under `replicas`, and SharedMergeTree does not support auxiliary Keepers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Disable every fail point a test enables, tag 02888 `no-fasttest` because it
enables them, and bound the `system.text_log` read in 04946 by `event_time`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Case 7 fails before the entry transaction is executed, so its registration is
removed together with the local directory; the comments said it was kept.
Function names in the rollback comments follow the repository style.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The master merge brought master's own include of the header and its
`FailPoints` block, so the include added by this PR became a duplicate
(`readability-duplicate-include` in `Build (arm_tidy)`). Keep master's
include and declare the new fail point in master's block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test asserts the ReplicatedMergeTree layout under `replicas` and injects
a ReplicatedMergeTree constructor fault, neither of which exists once
`--replace-replicated-with-shared` rewrites the engine. Same tag as 02888.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rollback around `database->createTable()` (and the fault injection
branch sharing it) called `StorageReplicatedMergeTree::drop()` for a
registration it owns. `drop()` runs `MergeTreeData::dropAllData()`, which
recursively removes `detached/` and the data path. With `table_disk = 1`
the data path is the root of the disk, which is not created by the
statement and can hold detached parts of an earlier table (a `MergeTree`
over the same disk, detached permanently). A failed CREATE then deleted
those parts, while master's `dropIfEmpty()` kept them.

Measured on a local plain_rewritable disk holding one detached part
(3 rows) and a fault-injected CREATE of a ReplicatedMergeTree over it:
- master: part kept, registration left (`replicas = ['r1']`, issue ClickHouse#69433)
- previous head: registration removed, part deleted (0 rows after
  re-attaching the partition)
- this commit: registration removed, part kept (3 rows)

The interpreter seam now does what the constructor seam does: remove only
the Keeper registration with `tryRemoveOwnReplicaFromZooKeeper()` (now
public; it also checks the table UUID, so `hasProvableCreationIdentity()`
goes private), then the non-recursive `dropIfEmpty()`. Inside the
interpreter the table has not started up yet, so that function's
`is_active` and never-started checks hold for the registration this
statement created.

02888 case 14 covers it; it fails on the previous head (0 rows instead
of 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// A constructed replicated storage has its replica registered in Keeper, and a registration left
/// there makes every retry of the CREATE fail with REPLICA_ALREADY_EXISTS. Best effort, because the
/// original exception is the one the user must see.
auto rollback_failed_creation = [&]

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.

[Blocker] Apply the non-recursive rollback to validation failures too.

The same table-disk preservation invariant is still violated before this helper is reached. Reuse case 14's setup (a writable table_disk containing a detached part), remove the fault-injection setting, and create the replicated table with (k Int32, _part_offset UInt64) and allow_reserved_column_names=0. The constructor succeeds and registers the replica, then validateStorage at line 3063 rejects _part_offset. Its catch at line 2771 calls storage.drop, which reaches StorageReplicatedMergeTree::drop and MergeTreeData::dropAllData and deletes the pre-existing detached part. This lambda has not even been constructed yet, so the new safe cleanup does not protect that failure.

This is a pre-existing path in the same creation flow, rather than a regression introduced by the latest commit. Please apply the same Keeper-only removal plus dropIfEmpty separation to the validation rollback, or explicitly link a tracking issue for this remaining data-loss path. A variant of case 14 that fails validation without a failpoint would cover it.

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.

This path is master's validateStorage, which this PR does not change: master loses the detached part the same way for a plain MergeTree table (the rejected CREATE leaves 0 of the root's 15 files), and there the replica registration is already removed, so it is a separate bug from the Keeper rollback here. I will fix it in its own PR and link it in this thread.

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 fix for this path is #132874: the MergeTree factory now refuses such a definition before constructing the table, so a rejected CREATE leaves the table_disk root unchanged.

This branch has not been deployed

No deployments
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-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

exception in zookeeper while creating database with Replicated engine leave state hanging in zookeeper

5 participants