Skip to content

Fix LOGICAL_ERROR race between creation and removal of replicated table - #99557

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
tiandiwonder:fix_race_creation_removal_replicated_table
Mar 24, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
tiandiwonder:fix_race_creation_removal_replicated_table

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor
    When `removeTableNodesFromZooKeeper` is called and the ZooKeeper session
    expires mid-cleanup, the ephemeral `/dropped/lock` node is deleted
    automatically by ZooKeeper. Another process can then take ownership and
    complete (or restart) the cleanup. When the original session reconnects
    and resumes, two sites previously threw `LOGICAL_ERROR`:

    1. `tryGetChildren(zookeeper_path)` returns `ZNONODE` → path already gone.
    2. The final `tryMulti` returns `ZNONODE` → nodes already deleted.

    Both sites assumed that holding the ephemeral lock guarantees the path
    cannot disappear, which is only true while the session is alive. Session
    expiry is a normal distributed-systems event, not a code bug.

    Fix: replace both `throw LOGICAL_ERROR` with graceful returns:
    - Site 1: log a warning and return `completely_removed = false`.
    - Site 2: add an `else if (ZNONODE)` branch that logs a warning; callers
      already handle `false` correctly (retry loop in `createTableIfNotExists`,
      ignored return value in `dropReplica`).

    Two `PAUSEABLE_ONCE` failpoints are added to make the race deterministic
    in tests:
    - `replicated_table_remove_zk_before_get_children`
    - `replicated_table_remove_zk_before_final_multi`

    Test 04036 exercises both scenarios via DROP TABLE SYNC: the path is
    deleted while the failpoint is paused, then the DROP is resumed and must
    complete without any exception.

fix #99385

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.210

@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a8a212d]

Summary: ✅


AI Review

Summary

This PR fixes a real race in ReplicatedMergeTree table cleanup when ZooKeeper session expiry allows concurrent removal, replacing two LOGICAL_ERROR throws with graceful handling and adding deterministic failpoint-based regression coverage. The core change is targeted, consistent with existing retry/caller semantics, and the new test exercises both affected branches.

ClickHouse Rules

Item Status Notes
Deletion logging ✅
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅

Final Verdict

  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Mar 16, 2026
# shellcheck source=../shell_config.sh
. "$CURDIR"/../shell_config.sh

ZK_PATH="/clickhouse/tables/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/race_test"

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.

Style check is currently failing on this line because the Replicated*MergeTree ZooKeeper path must contain the literal $CLICKHOUSE_TEST_ZOOKEEPER_PREFIX (or {database}) pattern in the test source.

Please switch to the literal macro form, e.g. ZK_PATH="/clickhouse/tables/\$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/race_test", so the style rule can validate path isolation and CI passes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Style check passed actually.

throw Exception(ErrorCodes::LOGICAL_ERROR, "There is a race condition between creation and removal of replicated table. It's a bug");
{
/// It is possible if ZooKeeper session expired and ephemeral drop lock was deleted,
/// allowing another process to complete the removal. Return false so the caller retries.

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.

removeTableNodesFromZooKeeper(zookeeper, zookeeper_info, metadata_drop_lock, logger);

At this point, the caller doesn't handle the returned value, and it doesn't retry.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed the comment.

  1. the caller createTableIfNotExistsAttempt() does retry to remove the entries before craate.
  2. the caller dropReplia() doesn't retry.

@tuanpach tuanpach self-assigned this Mar 19, 2026
@tiandiwonder
tiandiwonder requested a review from tuanpach March 23, 2026 00:40
# Simulate another process completing the ZK cleanup: delete the entire path.
${CLICKHOUSE_KEEPER_CLIENT} -q "rmr '${ZK_PATH}'" 2>/dev/null ||:

# Resume. tryGetChildren returns ZNONODE; with the fix we return false instead of throwing.

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.

The comment is inconsistent with the actual behavior here.

At this failpoint (ZNONODE on tryGetChildren), removeTableNodesFromZooKeeper now returns true (table path already fully removed), not false.

Please update the comment to avoid confusion for future maintenance.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed.

@tuanpach

Copy link
Copy Markdown
Member

The fix LGTM.

There are still 2 remaining comments left by the bot.

@tiandiwonder

Copy link
Copy Markdown
Contributor Author

There are still 2 remaining comments left by the bot.
Fixed.

@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.90% 83.90% +0.00%
Functions 24.70% 24.70% +0.00%
Branches 76.50% 76.50% +0.00%

PR changed lines: PR changed-lines coverage: 91.18% (31/34, 0 noise lines excluded)
Diff coverage report
Uncovered code

@alexey-milovidov
alexey-milovidov merged commit 321911d into ClickHouse:master Mar 24, 2026
148 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 24, 2026
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Jul 27, 2026
…on finishes the Keeper cleanup

StorageKafka2::removeTableNodesFromZooKeeper is a copy of the
StorageReplicatedMergeTree create/drop coordination protocol, and it kept both
throw sites that PR ClickHouse#99557 removed from the original:

  - tryGetChildren(keeper_path) returning ZNONODE
  - the final tryMulti removing {drop_lock, dropped, keeper_path} returning ZNONODE

Both encode the invariant "while I hold the ephemeral dropped/lock node, the
table's Keeper path cannot disappear". That invariant only holds while the
Keeper session is alive. When the session expires, Keeper itself deletes the
ephemeral lock, another replica legitimately finishes the removal, and the
resumed thread observes ZNONODE. Session expiry mid-cleanup is a normal
distributed-systems outcome, which is why every occurrence in the CI database
is on a Stress test check (thread fuzzer + fault injection).

The second message is byte-identical to the one reported by CI, so the
signature ClickHouse#99557 fixed is still reachable on master through this sibling.

Both branches now log a warning instead, matching the resolution the
maintainers already reviewed and merged for StorageReplicatedMergeTree:
ZNONODE on the root path means the table IS completely removed, so return
true; ZNONODE on the final multi means only part of the removal happened, so
completely_removed stays false. Neither caller relied on the throw.

Two PAUSEABLE_ONCE failpoints make both races deterministic in a regression
test modelled on 04036_replicated_table_race_creation_removal.sh.

Related: ClickHouse#99557
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Jul 27, 2026
…ROP injection

Two test-only hardenings; the source fix is unchanged.

Pin ignore_drop_queries_probability = 0 on every DROP TABLE. The whole test
mechanism is "DROP TABLE k2_race SYNC reaches
StorageKafka2::removeTableNodesFromZooKeeper and pauses on the failpoint", but
the stress runner appends --client-option ignore_drop_queries_probability=0.2
to every worker and clickhouse-client --fake-drop (upgrade check) sets it to 1.
Because StorageKafka2 does not override storesDataOnDisk,
InterpreterDropQuery::executeToTableImpl takes the branch that rewrites the
query into TRUNCATE, and StorageKafka2 does not implement truncate either, so
IStorage::truncate throws NOT_IMPLEMENTED and the failpoint is never reached.
Two DROPs are load-bearing, so about one stress run in three would have failed
by dice alone. No tag escapes this: no-stress is rejected outright and
--stress-tests disables the no-<build> filter.

Assert each tolerate branch's own warning from system.text_log. Previously the
only committed assertion was "the DROP did not throw", which does not pin the
branches individually: replacing the tryGetChildren branch with a bare
fall-through lets execution reach the final tryMulti, whose ZNONODE the other
new branch tolerates, so the DROP still succeeds and the scenario still passes.
The predicate is scoped to this run's own kafka_keeper_path (which embeds the
per-run random database) so rows from an earlier --test-runs iteration cannot
satisfy it, and to level = 'Warning' because the server also records the text
of this very SELECT - needle included - at Debug level.

Related: ClickHouse#99557
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
…on finishes the Keeper cleanup

StorageKafka2::removeTableNodesFromZooKeeper is a copy of the
StorageReplicatedMergeTree create/drop coordination protocol, and it kept both
throw sites that PR ClickHouse#99557 removed from the original:

  - tryGetChildren(keeper_path) returning ZNONODE
  - the final tryMulti removing {drop_lock, dropped, keeper_path} returning ZNONODE

Both encode the invariant "while I hold the ephemeral dropped/lock node, the
table's Keeper path cannot disappear". That invariant only holds while the
Keeper session is alive. When the session expires, Keeper itself deletes the
ephemeral lock, another replica legitimately finishes the removal, and the
resumed thread observes ZNONODE. Session expiry mid-cleanup is a normal
distributed-systems outcome, which is why every occurrence in the CI database
is on a Stress test check (thread fuzzer + fault injection).

The second message is byte-identical to the one reported by CI, so the
signature ClickHouse#99557 fixed is still reachable on master through this sibling.

Both branches now log a warning instead, matching the resolution the
maintainers already reviewed and merged for StorageReplicatedMergeTree:
ZNONODE on the root path means the table IS completely removed, so return
true; ZNONODE on the final multi means only part of the removal happened, so
completely_removed stays false. Neither caller relied on the throw.

Two PAUSEABLE_ONCE failpoints make both races deterministic in a regression
test modelled on 04036_replicated_table_race_creation_removal.sh.

Related: ClickHouse#99557
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
…ROP injection

Two test-only hardenings; the source fix is unchanged.

Pin ignore_drop_queries_probability = 0 on every DROP TABLE. The whole test
mechanism is "DROP TABLE k2_race SYNC reaches
StorageKafka2::removeTableNodesFromZooKeeper and pauses on the failpoint", but
the stress runner appends --client-option ignore_drop_queries_probability=0.2
to every worker and clickhouse-client --fake-drop (upgrade check) sets it to 1.
Because StorageKafka2 does not override storesDataOnDisk,
InterpreterDropQuery::executeToTableImpl takes the branch that rewrites the
query into TRUNCATE, and StorageKafka2 does not implement truncate either, so
IStorage::truncate throws NOT_IMPLEMENTED and the failpoint is never reached.
Two DROPs are load-bearing, so about one stress run in three would have failed
by dice alone. No tag escapes this: no-stress is rejected outright and
--stress-tests disables the no-<build> filter.

Assert each tolerate branch's own warning from system.text_log. Previously the
only committed assertion was "the DROP did not throw", which does not pin the
branches individually: replacing the tryGetChildren branch with a bare
fall-through lets execution reach the final tryMulti, whose ZNONODE the other
new branch tolerates, so the DROP still succeeds and the scenario still passes.
The predicate is scoped to this run's own kafka_keeper_path (which embeds the
per-run random database) so rows from an earlier --test-runs iteration cannot
satisfy it, and to level = 'Warning' because the server also records the text
of this very SELECT - needle included - at Debug level.

Related: ClickHouse#99557
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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.

Logical error: There is a race condition between creation and removal of replicated table. It's a bug (STID: 2508-1e6e)

4 participants