Skip to content

Set Keeper component in ZooKeeperLock destructor - #110670

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-zerocopylock-dtor-keeper-component
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-zerocopylock-dtor-keeper-component

Conversation

@groeneai

@groeneai groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix a LOGICAL_ERROR ("Current component is empty") that could abort the server in debug/sanitizer builds when a zero-copy replicated merge or mutation task holding a zero-copy exclusive lock was torn down by the background executor.

Description

A replicated zero-copy merge/mutation task owns the zero-copy exclusive lock via its std::optional<ZeroCopyLock> member. When such a task is torn down on a MergeTreeBackgroundExecutor thread while the lock is still held, ~ZooKeeperLock issues ZooKeeper requests (exists/remove) to release the ephemeral node. That teardown runs outside any Keeper component scope, so with enforce_keeper_component_tracking enabled ZooKeeper::pushRequest throws Current component is empty, please set it for your scope using Coordination::setCurrentComponent (a server abort in debug/sanitizer builds). Reported on #110590 (amd_debug flaky check).

The Keeper component is set at the highest level that owns the section doing those ZooKeeper requests: the MutateFromLogEntryTask and MergeFromLogEntryTask destructors. Each sets the component and then releases zero_copy_lock explicitly inside that scope, because the member would otherwise be destroyed after the destructor body, outside the guard. Both task types own a std::optional<ZeroCopyLock>, so both are covered.

Observed stack (baseline, before the fix):

Coordination::ZooKeeper::pushRequest  (ZooKeeperImpl.cpp, "Current component is empty")
  zkutil::ZooKeeper::exists
  zkutil::ZooKeeperLock::unlock
  zkutil::ZooKeeperLock::~ZooKeeperLock
  DB::MutateFromLogEntryTask::~MutateFromLogEntryTask  (~optional<ZeroCopyLock>)
  DB::TaskRuntimeData::resetTask
  DB::MergeTreeBackgroundExecutor<DynamicRuntimeQueue>::routine

Added a stateless regression test (04546_zero_copy_lock_dtor_keeper_component) that pauses a mutation task on a new failpoint rmt_mutate_task_pause_after_zero_copy_lock fired right after tryCreateZeroCopyExclusiveLock() succeeds, then drops the table so the task is destroyed while it provably holds the lock. Verified locally (embedded Keeper, s3_cache zero-copy, enforce_keeper_component_tracking=1): fails with SIGABRT ("Current component is empty") without the fix, passes with it.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. s3 zero-copy ReplicatedMergeTree + enforce_keeper_component_tracking=1, pause the mutation with rmt_mutate_task_pause_in_prepare (fires after the zero-copy lock is acquired), then DROP TABLE ... SYNC so the task is destroyed while still holding the lock. Aborts every time on baseline.
b Root cause explained? ~ZooKeeperLock() -> unlock() issues Keeper exists/remove. When the still-locked lock is destroyed on a background executor thread outside executeStep's component scope, no component is set, so ZooKeeper::pushRequest throws "Current component is empty" under enforce_keeper_component_tracking.
c Fix matches root cause? Yes. Sets the component in the destructor itself (the only unscoped Keeper-issuing path), so the release is scoped regardless of the calling thread.
d Test intent preserved / new tests added? New stateless test 04546_zero_copy_lock_dtor_keeper_component reproduces the exact teardown path.
e Demonstrated both directions? Baseline (build 49ace778): SIGABRT with the reported stack. Fixed (build d71d1abc): no error, DROP completes, server alive. Same repro.
f General, not a narrow patch? Guard placed in ZooKeeperLock::~ZooKeeperLock(), covering all ZooKeeperLock users' teardown (ZeroCopyLock and DDLWorker's execute_on_single_replica_lock), not just the one reported call site.
g Generalizes across inputs? The dtor path is type-agnostic; the guard applies to every lock-release regardless of lock owner/message/path.
h Backward compatible? Yes. No format/setting/default change; only sets a thread-local component name during lock release.
i Invariants/contracts preserved? Yes. setCurrentComponent is a scoped RAII guard restoring the previous component on exit; unlock() semantics unchanged.

Session id: cron:clickhouse-worker-slot-7:20260716-101500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @antonio2368 could you review? One-line guard setting the Keeper component in ZooKeeperLock's destructor so lock release from an unscoped background/teardown thread no longer aborts under enforce_keeper_component_tracking. Reproduced and validated in both directions; regression test included.

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

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9f30d43]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL

AI Review

Summary

This PR’s code fix has already landed on master; the remaining net effect here is adding 04546, which is an older and weaker copy of the existing 04603 regression. I found two test-contract gaps in that duplicate: the first half no longer has an observable that fails on the broken destructor path, and the second half does not exercise the async move path that MergeTreeData::moveParts was fixed for.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04546_zero_copy_lock_dtor_keeper_component.sh:71-75] The first scope no longer proves the ~MutateFromLogEntryTask fix. zkutil::ZooKeeperLock::~ZooKeeperLock catches and logs unlock exceptions, and the script ignores the background DROP exit status with wait "$drop_pid" || true, so the broken code can still leave the server alive and make this test pass. The stronger observable already exists in 04603: keep the DROP result meaningful and assert that no Current component is empty message appears in system.text_log.

  • [tests/queries/0_stateless/04546_zero_copy_lock_dtor_keeper_component.sh:77-95] The second scope claims to cover the MergeTreeData::moveParts component guard, but ALTER TABLE ... MOVE PART is synchronous unless alter_move_to_space_execute_async = 1 is enabled. In the synchronous case the call is already wrapped by StorageReplicatedMergeTree::alter, so this copy never reaches the background ExecutableLambdaAdapter path that the fix was for. Either switch this to the async move flow and assert the part actually lands on s3_disk, or drop the duplicate test in favor of the stronger existing 04603.

Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Remove the weaker duplicate regression or align 04546 with the existing 04603 assertions.
    • Restore a failing observable for the destructor path and exercise the async moveParts path instead of the already-scoped synchronous ALTER.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
@antonio2368

Copy link
Copy Markdown
Member

@groeneai ZooKeeperLock is too low level for component name. ~MutateFromLogEntryTask looks much better. Remember that the point is to add keeper component at the highest level which defines a specific section doing ZooKeeper requests.

A replicated zero-copy merge/mutate task owns the zero-copy exclusive lock
via its std::optional<ZeroCopyLock> member. When the task is torn down on a
MergeTreeBackgroundExecutor thread while the lock is still held, ~ZooKeeperLock
issues Keeper requests (exists/remove) to release the ephemeral node. That
teardown runs outside any component scope, so with enforce_keeper_component_tracking
enabled the server aborts with "Current component is empty, please set it for
your scope using Coordination::setCurrentComponent".

The Keeper component is set at the highest level that owns the section doing
those ZooKeeper requests: the MutateFromLogEntryTask / MergeFromLogEntryTask
destructors. Each explicitly releases zero_copy_lock inside the guarded scope,
because the member would otherwise be destroyed after the destructor body,
outside the guard.

Regression test 04546 pauses a mutation task on a new failpoint fired right
after tryCreateZeroCopyExclusiveLock() succeeds, so the task provably holds the
lock, then drops the table so the task is destroyed with the lock still held.

Related: ClickHouse#110590
@groeneai
groeneai force-pushed the fix-zerocopylock-dtor-keeper-component branch from a831f7a to 9aa5044 Compare July 16, 2026 12:54
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reworked per review.

Component placement (@antonio2368): moved the Keeper component out of the low-level ~ZooKeeperLock and up to the destructors of MutateFromLogEntryTask and MergeFromLogEntryTask, which are the highest level that owns the section issuing the ZooKeeper release. Each destructor sets the component and then releases zero_copy_lock explicitly inside that scope, because the member would otherwise be destroyed after the destructor body, outside the guard. Both merge and mutate tasks own a std::optional<ZeroCopyLock>, so both are covered.

Test sync: the test now enables a new failpoint rmt_mutate_task_pause_after_zero_copy_lock fired immediately after tryCreateZeroCopyExclusiveLock() succeeds, and synchronizes on SYSTEM WAIT FAILPOINT ... PAUSE. So DROP TABLE only proceeds once the task provably holds the lock, not merely once the mutation entry is queued.

Verified in both directions locally (embedded Keeper, s3_cache zero-copy, enforce_keeper_component_tracking=1):

  • Without the destructor guard: server aborts with Logical error: 'Current component is empty, please set it for your scope using Coordination::setCurrentComponent' (test fails).
  • With the fix: test passes, server stays alive.

The test synced on the DROP TABLE query appearing in system.processes to
assert the mutation task is torn down while holding the zero-copy lock. That
does not establish the condition: the task is flagged is_currently_deleting
only later, in MergeTreeBackgroundExecutor::removeTasksCorrespondingToStorage
(driven by partialShutdown -> background_operations_assignee.finish). If the
after-zero-copy-lock failpoint is released before that, the task is requeued
and finalized normally, releasing the lock under executeStep's component scope
instead of through ~MutateFromLogEntryTask, so the test could pass without
exercising the fixed teardown path.

Add a pauseable failpoint merge_tree_background_task_marked_for_deletion that
fires right after the task is flagged is_currently_deleting (outside the
executor mutex, only when a task is actually being deleted). The test now waits
on it before resuming, guaranteeing the paused task takes the destruction path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 16, 2026
…t a Keeper component

The AI review kept this PR at request-changes because nothing in-tree
proved the guarded destructor path is exercised: the existing failpoints
(`rmt_mutate_task_pause_in_prepare`, `rmt_merge_task_sleep_in_prepare`)
fire before `tryCreateZeroCopyExclusiveLock`, so a future refactor could
drop the guards and CI would stay green.

Add two pauseable failpoints and a stateless test:
- `rmt_mutate_task_pause_after_zero_copy_lock` pauses `MutateFromLogEntryTask::prepare`
  right after the zero-copy exclusive lock is acquired, so the task provably
  holds the lock;
- `merge_tree_background_task_marked_for_deletion` pauses
  `MergeTreeBackgroundExecutor::removeTasksCorrespondingToStorage` right after
  active tasks are flagged `is_currently_deleting`, guaranteeing the resumed
  task takes the destruction path (cancel + destroy via the task destructor)
  instead of being requeued and finalized normally.

The test `04603_zero_copy_lock_dtor_keeper_component` synchronizes on both
failpoints, drops the table while the mutation task still holds the lock, and
checks the server survives `~ZooKeeperLock` releasing the ephemeral node from
the destructor (stateless runs enable `enforce_keeper_component_tracking`, so
before this PR's guards that release threw the `LOGICAL_ERROR` "Current
component is empty ..."). A second scope covers the sibling
`MergeTreeData::moveParts` path via a synchronous `ALTER TABLE ... MOVE PART`
to a zero-copy disk.

The failpoints and test are adapted from #110670 by @groeneai (renumbered to
04603 because 04546 is already taken on master).

Related: #110670

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

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 23/25 (92.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e727021

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Logical error 'Block structure mismatch in UnionStep stream' (STID 0993-27f0) chronic trunk (100+ PRs / master, 30d; UnionStep const-vs-full column) fixing PR #107719 (ours, open)
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (45 master + 15+ unrelated PRs, 30d) fixing PR #110030 (ours, open) / #110145 (external, open)
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260717-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e727021

CI fully finished on this head (Finish Workflow SUCCESS; only the exempt CH Inc sync remains). All failures owned; none PR-caused (both unrelated to the ZeroCopyLock destructor component-scope fix).

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (known, #110036) #110030 (ours, open)
AST fuzzer (amd_debug) / Block structure mismatch in UnionStep stream (STID 0993-27f0) crash (liftUpUnion / divergent aggregate-state UNION family, unrelated to ZeroCopyLock) #110745 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260718-033000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #110664 (merged), which lands the same fix: the ~MutateFromLogEntryTask / ~MergeFromLogEntryTask component guards, the MergeTreeData::moveParts guard, the three failpoints, and a regression test adapted from this PR as 04603_zero_copy_lock_dtor_keeper_component.

The functional diff of this branch against current master is empty (only comment wording and include ordering differ), so rebasing off the current merge conflict would add no code. Leaving the close decision to the maintainers; happy to close on request.

Conflicts were comment-only: master already contains the same
component-scope fix in ~MergeFromLogEntryTask/~MutateFromLogEntryTask and in
removeTasksCorrespondingToStorage, so master's wording is kept. Also dropped
this branch's duplicate ZooKeeperCommon.h includes, its duplicate
~MutateFromLogEntryTask declaration, and its moveParts component guard, which
shadowed master's narrower guard and broke the -Werror,-Wshadow build.
# Let removeTasksCorrespondingToStorage proceed to wait for the (now destroyed) task, so DROP finishes.
$CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT merge_tree_background_task_marked_for_deletion;"

# Do not let the (irrelevant) exit status of the background DROP abort the script under `set -e`.

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.

SELECT 1 is not a discriminating observable for the destructor-scope bug anymore. zkutil::ZooKeeperLock::~ZooKeeperLock catches and only logs unlock failures (src/Common/ZooKeeper/ZooKeeperLock.cpp:36-44), so on the broken code path the server can stay up and this script still reaches the final query. Swallowing wait "$drop_pid" with || true removes the other signal from the first half as well. That means this regression can pass even when ~MutateFromLogEntryTask releases the zero-copy lock without a Keeper component. Can we keep the stronger check from 04603 here: require the background DROP to finish cleanly and assert via system.text_log that no Current component is empty message was produced after the test started?

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.

Agree, and I verified both halves of this.

zkutil::ZooKeeperLock::~ZooKeeperLock wraps unlock() in a try whose catch (...) only calls DB::tryLogCurrentException, so on the broken path the server stays up, and with wait "$drop_pid" || true plus a bare SELECT 1 this script has no observable that discriminates the fix from the bug. It can pass with the destructor guard removed.

The stronger form you describe is already on master, in tests/queries/0_stateless/04603_zero_copy_lock_dtor_keeper_component.sh, which merged #110664 adapted from this PR: it requires the background DROP to finish cleanly (wait "$drop_pid", no || true) and then asserts SELECT count() FROM system.text_log WHERE event_time_microseconds >= ... AND message LIKE '%Current component is empty%' is 0, with reference 1\n0 against this copy's 1\n1.

So I am not strengthening 04546. After the master merge into this branch, the entire remaining diff of this PR is 04546 plus its reference file: the two destructor guards, the MergeTreeData::moveParts guard and all three failpoints are already on master. This copy is a strictly weaker duplicate of 04603 and should be dropped rather than fixed. I noted the same conclusion on the PR on 2026-07-18 and I am leaving the close decision to the maintainers.


# Second scope: the zero-copy part-move path. MergeTreeData::moveParts acquires/uses/releases a
# local ZeroCopyLock (tryCreateZeroCopyExclusiveLock does Keeper I/O), so it must run under a
# Keeper component too. A synchronous ALTER ... MOVE PART runs moveParts directly on the query

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.

This ALTER TABLE ... MOVE PART is synchronous by default, so it runs under StorageReplicatedMergeTree::alter's existing component scope (src/Storages/StorageReplicatedMergeTree.cpp:6796-6800) and does not exercise the background ExecutableLambdaAdapter path that the MergeTreeData::moveParts guard was added for (src/Storages/MergeTree/MergeTreeData.cpp:11062-11070, 11185-11190). As written, the second half can pass even if the new moveParts component guard is removed. The existing 04603 variant gets this right by setting alter_move_to_space_execute_async = 1 and waiting until the part actually lands on s3_disk; this copy should do the same or be dropped instead of adding a weaker duplicate.

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.

Agree, and I verified the mechanism.

alter_move_to_space_execute_async defaults to false, and StorageReplicatedMergeTree::alter opens its own Coordination::setCurrentComponent("StorageReplicatedMergeTree::alter") guard at the top, so a synchronous ALTER TABLE ... MOVE PART runs moveParts on the query thread already inside a component scope. It never reaches the background ExecutableLambdaAdapter route that scheduleDataMovingJob submits to background_moves_assignee, which is the unscoped path the MergeTreeData::moveParts guard exists for. So this second half passes with that guard removed.

As with the first half, the correct version is already on master in 04603: it sets alter_move_to_space_execute_async = 1 and then polls system.parts until the part actually lands on s3_disk, so the background moves thread is genuinely exercised.

I am not going to strengthen this copy, because 04546 and its reference file are the whole remaining diff of this PR after the master merge into this branch. Every source hunk it was written for is already on master, so there is nothing here to keep and nothing to add over 04603. Dropping it means closing this PR, which I am leaving to the maintainers.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Finish Workflow / Post Hooks red on 9f30d43c is real, and it is not fixable inside this PR. Recording why, since it changes the disposition from "redundant" to "permanently unmergeable".

new_tests_check.py gates a pr-bugfix PR that adds functional tests on at least one per-arch Bugfix Validation job reaching strict success. Those jobs run the new test against a merge-base "before" build. The merge-base of this branch is 0aae1c26, which already contains eda0515a (merged #110664), so the ~MutateFromLogEntryTask / ~MergeFromLogEntryTask guards, the MergeTreeData::moveParts guard and all three failpoints are present in the "before" tree. Both functional validators therefore correctly report Bug does not reproduce on this arch, both land on SKIPPED, and the gate fails. Nothing upstream errored, so the "or every arch errored out" clause does not apply: of 174 nodes in result_pr.json there are 0 ERROR nodes, every Build (*) is OK or legitimately skipped, and the only FAIL is the gate itself.

Strengthening 04546 cannot clear this. For a validator to reach strict success the test would have to fail on a merge-base that already carries the fix. There is also nothing left to fix: the only two zkutil::ZooKeeperLock owners on master are ZeroCopyLock and DDLWorker's execute_on_single_replica_lock, and both teardowns now run inside a component scope. CIDB shows 0 Current component is empty failures in the last 12 days, while 04603_zero_copy_lock_dtor_keeper_component has 1782 OK rows across 205 master commits over 7 days, so the silence is a working fix rather than an untested path.

I am also not relabelling the changelog category to make the gate green. The remaining diff is 04546 plus its reference, and it is a strict subset of master's 04603: it lacks alter_move_to_space_execute_async = 1 and the system.text_log assertion, and its only unique lines are wait "$drop_pid" || true and two SELECT 1 liveness checks, none of which discriminate the fix from the bug. Merging it would add a weaker duplicate of a test that already exists.

So the only useful outcome is closing this PR. I am not closing it myself since you reviewed it. @antonio2368 could you close it, or tell me to?

@azat

azat commented Aug 16, 2026

Copy link
Copy Markdown
Member

Closed in favor #110664

@azat azat closed this Aug 16, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…t a Keeper component

The AI review kept this PR at request-changes because nothing in-tree
proved the guarded destructor path is exercised: the existing failpoints
(`rmt_mutate_task_pause_in_prepare`, `rmt_merge_task_sleep_in_prepare`)
fire before `tryCreateZeroCopyExclusiveLock`, so a future refactor could
drop the guards and CI would stay green.

Add two pauseable failpoints and a stateless test:
- `rmt_mutate_task_pause_after_zero_copy_lock` pauses `MutateFromLogEntryTask::prepare`
  right after the zero-copy exclusive lock is acquired, so the task provably
  holds the lock;
- `merge_tree_background_task_marked_for_deletion` pauses
  `MergeTreeBackgroundExecutor::removeTasksCorrespondingToStorage` right after
  active tasks are flagged `is_currently_deleting`, guaranteeing the resumed
  task takes the destruction path (cancel + destroy via the task destructor)
  instead of being requeued and finalized normally.

The test `04603_zero_copy_lock_dtor_keeper_component` synchronizes on both
failpoints, drops the table while the mutation task still holds the lock, and
checks the server survives `~ZooKeeperLock` releasing the ephemeral node from
the destructor (stateless runs enable `enforce_keeper_component_tracking`, so
before this PR's guards that release threw the `LOGICAL_ERROR` "Current
component is empty ..."). A second scope covers the sibling
`MergeTreeData::moveParts` path via a synchronous `ALTER TABLE ... MOVE PART`
to a zero-copy disk.

The failpoints and test are adapted from ClickHouse#110670 by @groeneai (renumbered to
04603 because 04546 is already taken on master).

Related: ClickHouse#110670

Co-Authored-By: Claude Fable 5 <[email protected]>
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants