Skip to content

Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2) - #103890

Merged
antaljanosbenjamin merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3555-2986-storagekafka2-uaf
May 15, 2026
Merged

antaljanosbenjamin merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3555-2986-storagekafka2-uaf

Conversation

@groeneai

@groeneai groeneai commented May 2, 2026 •

Copy link
Copy Markdown
Collaborator

What

Fix a use-after-free in DB::KeeperHandlingConsumer::setKeeper() (used by StorageKafka2) where, on a Keeper session swap, the lock holders could outlive the ZooKeeper instance they reference and crash in ~zkutil::EphemeralNodeHolder().

Why / root cause

LockedTopicPartitionInfo::lock (held in permanent_locks and tmp_locks) is a zkutil::EphemeralNodeHolder, which stores a raw ZooKeeper & reference captured at construction time (see EphemeralNodeHolder in Common/ZooKeeper/ZooKeeper.h). Its destructor calls zookeeper.expired() and possibly zookeeper.tryRemove().

KeeperHandlingConsumer::setKeeper() was assigning the new keeper shared_ptr before clearing the lock maps:

void KeeperHandlingConsumer::setKeeper(const std::shared_ptr<zkutil::ZooKeeper> & keeper_)
{
    keeper = keeper_;             // <-- (1) drops shared_ptr to old session
    {
        std::lock_guard lock(topic_partition_locks_mutex);
        permanent_locks.clear();  // <-- (2) destroys EphemeralNodeHolders that hold ZooKeeper&
        tmp_locks.clear();
    }
    ...
}

If the consumer was the last shared owner of the previous ZooKeeper (which is plausible: by the time streamToViews() calls setKeeper, StorageKafka2::keeper and Context's keeper have typically already moved on to the new session), then step (1) synchronously destroys the old ZooKeeper. Step (2) then runs the holders' destructors which call zookeeper.expired() on the freed object — SIGSEGV.

This is the same hazard already documented and fixed in StorageKafka2::partialShutdown() for replica_is_active_node. From src/Storages/Kafka/StorageKafka2.cpp lines 221-225:

/// Reset the active node holder while the old ZooKeeper session is still alive (even if expired).
/// EphemeralNodeHolder stores a raw ZooKeeper reference, so resetting it here prevents a
/// use-after-free: setZooKeeper() called afterwards may free the old session, and the holder's
/// destructor would then access a dangling reference when checking zookeeper.expired().
replica_is_active_node = nullptr;

The per-consumer lock holders need the same treatment. This PR clears permanent_locks and tmp_locks first, then replaces keeper.

Crash report

zkutil::EphemeralNodeHolder::~EphemeralNodeHolder() @ 0x15aa9699
DB::KeeperHandlingConsumer::setKeeper(...)            @ 0x15a9985c
DB::StorageKafka2::streamToViews(unsigned long)       @ 0x15b0cf1c
... StorageKafka2 ctor lambda → BackgroundSchedulePool::threadFunction

Caught on Stress test (arm_release) on PR #101113 (which is unrelated to Kafka/Keeper — the crash surfaced under stress-test ZK fault injection):

Related

Scope review

Audited every EphemeralNodeHolderPtr / EphemeralNodeHolder usage that could outlive a keeper swap:

Site Status
StorageKafka2::replica_is_active_node already correct (handled in partialShutdown())
StorageReplicatedMergeTree::replica_is_active_node already correct (handled in its partialShutdown())
StorageKafka2.cpp:574 metadata_drop_lock safe — local-scope, lives entirely within one function with its own keeper shared_ptr alive
StorageKafka2.cpp:766 drop_lock safe — local-scope, same reasoning
KeeperHandlingConsumer::permanent_locks / tmp_locks the bug, fixed by this PR

Testing notes

The bug is a race-y use-after-free: it requires the consumer to be the last shared_ptr owner of the previous ZooKeeper, with at least one acquired ephemeral lock at the moment of setKeeper. Reproducing this deterministically requires the stress-test ZK fault-injection harness that originally caught it (the bug is rare in normal operation and the master CIDB shows only one hit so far for STID 3555-2986).

The fix itself is provably correct from the shared_ptr / raw-reference lifetime argument and mirrors the documented and already-merged precedent for replica_is_active_node. It is a pure reordering of operations within setKeeper; the externally observable post-state of the function is unchanged.

The change compiles cleanly (ninja -C build src/CMakeFiles/dbms.dir/Storages/Kafka/KeeperHandlingConsumer.cpp.o).

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 use-after-free in StorageKafka2 that could crash the server when a Keeper session is replaced while the consumer is holding ephemeral topic-partition locks.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.674
  • Backported to: 26.4.3.23, 26.3.11.23, 26.2.19.30, 25.8.24.17

@groeneai

groeneai commented May 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @kssenii — could you review this? It fixes a use-after-free in KeeperHandlingConsumer::setKeeper where, on a Keeper session swap, permanent_locks.clear() / tmp_locks.clear() ran AFTER the keeper shared_ptr was already replaced — so if the consumer was the last shared owner of the previous ZooKeeper, the EphemeralNodeHolder destructors accessed a dangling ZooKeeper& reference. The fix mirrors the existing precedent in StorageKafka2::partialShutdown() (lines 221-225) for replica_is_active_node. Caught on PR #101113's arm_release stress test (STID 3555-2986); likely a sibling of issue #84616.

Session: cron:clickhouse-ci-task-worker:20260502-021500

@groeneai

groeneai commented May 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate answers (per TASK.md Phase 4 step 9):

(a) Deterministic repro? Partial. The crash is a race-y use-after-free that requires:

  1. The consumer to be the last shared_ptr owner of the previous ZooKeeper instance (plausible: by the time streamToViews calls setKeeper, both StorageKafka2::keeper and the Context have typically already moved to the new session)
  2. The consumer to hold at least one acquired ephemeral lock at the moment of setKeeper
  3. ZK session loss (in CI: stress-test ZK fault injection)

It hit once on master/PR #101113's arm_release stress run (STID 3555-2986). I did not deterministically reproduce it locally because that requires the stress-test ZK fault-injection harness (or a unit test that mocks shared_ptr ownership for ZooKeeper, which would require non-trivial scaffolding). However, the static-analysis argument for the bug is exhaustive (see (b)).

(b) Root cause explained? Yes.

  • LockedTopicPartitionInfo::lock is a zkutil::EphemeralNodeHolder, which stores a raw ZooKeeper& reference captured at construction.
  • Its destructor calls zookeeper.expired() and possibly zookeeper.tryRemove().
  • keeper = keeper_; runs first → if the consumer is the last shared_ptr owner of the previous session, the old ZooKeeper is destroyed synchronously inside that assignment.
  • permanent_locks.clear() / tmp_locks.clear() then runs the holder destructors, which dereference a freed object → SIGSEGV.

The exact same hazard is documented and fixed in StorageKafka2::partialShutdown() (StorageKafka2.cpp lines 221-225, comment: "EphemeralNodeHolder stores a raw ZooKeeper reference, so resetting it here prevents a use-after-free: setZooKeeper() called afterwards may free the old session, and the holder's destructor would then access a dangling reference when checking zookeeper.expired()").

(c) Fix matches root cause? Yes. Pure reordering: clear lock holders first (while keeper still owns the old session, keeping it alive), then replace keeper. This mirrors the documented precedent for replica_is_active_node.

(d) Test intent preserved? N/A — this is a production-code lifecycle fix, no test changes.

(e) Both directions demonstrated? Static-analysis-only. Without the stress-test fault-injection setup, I cannot easily exhibit the crash on demand. The change compiles cleanly (ninja -C build src/CMakeFiles/dbms.dir/Storages/Kafka/KeeperHandlingConsumer.cpp.o). The CI suite on this PR will exercise it.

(f) Fix is general, not a narrow patch? Yes. I audited every other EphemeralNodeHolderPtr / EphemeralNodeHolder usage that could outlive a keeper swap:

  • StorageKafka2::replica_is_active_node — already correctly handled
  • StorageReplicatedMergeTree::replica_is_active_node — already correctly handled
  • StorageKafka2.cpp:574 metadata_drop_lock — safe, local-scope, lives within one function whose own keeper shared_ptr is alive throughout
  • StorageKafka2.cpp:766 drop_lock — safe, same reasoning
  • KeeperHandlingConsumer::permanent_locks / tmp_locks — the bug, fixed here

The deeper "why does the bad value arrive" answer is: EphemeralNodeHolder deliberately uses a raw ZooKeeper& reference instead of a shared_ptr (a design choice to keep local-scope holders zero-overhead). That design forces every long-lived holder to be ordered relative to keeper swaps. This PR does that ordering at the one remaining site that missed it; making EphemeralNodeHolder itself shared_ptr-based would be a much larger change touching every call site and is out of scope.

Session: cron:clickhouse-ci-task-worker:20260502-021500

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad88999]

Summary: ❌

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

AI Review

Summary

This PR reorders operations in KeeperHandlingConsumer::setKeeper so Kafka topic-partition lock holders are destroyed before replacing the keeper pointer, avoiding a real use-after-free during Keeper session swaps. The change is small, targeted, and consistent with the existing StorageKafka2::partialShutdown precedent; I did not find correctness, safety, or rollout issues in the diff.

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 ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 2, 2026
@antaljanosbenjamin antaljanosbenjamin self-assigned this May 4, 2026
Comment on lines +134 to +145
/// Drop the lock holders BEFORE replacing the `keeper` shared_ptr.
///
/// `LockedTopicPartitionInfo::lock` is a `zkutil::EphemeralNodeHolder`, which stores
/// a raw `ZooKeeper &` reference captured at construction time (see `EphemeralNodeHolder`
/// in `Common/ZooKeeper/ZooKeeper.h`). Its destructor calls `zookeeper.expired()` and
/// possibly `zookeeper.tryRemove()`. If we assigned `keeper = keeper_` first and our
/// `keeper` was the last shared owner of the previous session, that assignment would
/// synchronously destroy the old `ZooKeeper`, and the subsequent `permanent_locks.clear()`
/// / `tmp_locks.clear()` would then access a dangling reference -> use-after-free.
///
/// `StorageKafka2::partialShutdown()` already documents and applies the same ordering for
/// `replica_is_active_node`; this mirrors that fix for the per-consumer lock holders.

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.

@groeneai this is too long explanation. Give a much simpler explanation, maybe just reference the partial shutdown and active replica node holder.

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.

Done in fdcaa94 — trimmed to two lines that just reference the precedent at StorageKafka2::partialShutdown for replica_is_active_node. Thanks for the review @antaljanosbenjamin!

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix 02270_errors_in_files_s3 and send a separate PR. If it is already fixed, link the fix here. Then update the branch here.

groeneai added 2 commits May 7, 2026 01:47
`LockedTopicPartitionInfo::lock` (held in `permanent_locks` and `tmp_locks`)
is a `zkutil::EphemeralNodeHolder`, which stores a **raw** `ZooKeeper &`
reference captured at construction. Its destructor calls
`zookeeper.expired()` and possibly `zookeeper.tryRemove()`.

`KeeperHandlingConsumer::setKeeper()` assigned the new `keeper` shared_ptr
*before* clearing the lock maps. If the consumer was the last shared owner
of the previous `ZooKeeper` session, that assignment would synchronously
destroy the old session, and the subsequent `permanent_locks.clear()` /
`tmp_locks.clear()` would then access a dangling reference -> SIGSEGV.

This is the same hazard already documented and handled in
`StorageKafka2::partialShutdown()` for `replica_is_active_node`
(see the comment at `StorageKafka2.cpp` lines 221-225). This commit
mirrors that ordering for the per-consumer lock holders.

Caught by `Stress test (arm_release)` on PR ClickHouse#101113 (which is
unrelated to Kafka/Keeper -- the crash surfaced under stress-test
ZK fault injection):

  zkutil::EphemeralNodeHolder::~EphemeralNodeHolder() @ 0x15aa9699
  DB::KeeperHandlingConsumer::setKeeper(...)            @ 0x15a9985c
  DB::StorageKafka2::streamToViews(unsigned long)       @ 0x15b0cf1c

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101113&sha=4cf4eb894643c2dac6b52dea6126f1a3f2e75cd2&name_0=PR&name_1=Stress%20test%20%28arm_release%29

Related issue: ClickHouse#84616 (sibling crash in StorageKafka2 on Keeper session loss).

STID: 3555-2986
Signed-off-by: Groene AI <[email protected]>
Reduce the explanation in `KeeperHandlingConsumer::setKeeper` to a short
two-liner that just references the precedent at
`StorageKafka2::partialShutdown` for `replica_is_active_node`, where the
same use-after-free hazard is already documented.
@groeneai
groeneai force-pushed the groeneai/fix-stid-3555-2986-storagekafka2-uaf branch from fdcaa94 to ad88999 Compare May 7, 2026 01:48
@groeneai

groeneai commented May 7, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov — 02270_errors_in_files_s3 is already fixed on master:

CIDB verification (master only, head_ref = 'master'): 0 master failures since the revert merged at 2026-05-05 12:00 UTC. The handful of post-fix failures all came from PR branches that pre-dated the revert and didn't yet include it.

Branch updated — rebased onto current master (f72e56ed5c1), so #103890 now sits on top of #104077. Diff is unchanged, just the KeeperHandlingConsumer.cpp fix:

  • 8ebf0708ff1 Fix use-after-free in KeeperHandlingConsumer::setKeeper
  • ad889997c38 Trim setKeeper comment per @antaljanosbenjamin review

Awaiting fresh CI on the rebased branch.

Session: cron:clickhouse-ci-task-worker:20260507-014500

@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 0.00% (0/7) · Uncovered code

Full report · Diff report

@antaljanosbenjamin
antaljanosbenjamin added this pull request to the merge queue May 15, 2026
Merged via the queue into ClickHouse:master with commit 3617837 May 15, 2026
163 of 165 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: KeeperHandlingConsumer::setKeeper — introduced in 25.8.

Why this might apply: Fix in KeeperHandlingConsumer::setKeeper — git log shows KeeperHandlingConsumer was introduced on 2025-06-27, which predates the 25.8 release (2025-08-29). This is a use-after-free that can cause SIGSEGV crashes on Keeper session swaps.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 15, 2026
@antaljanosbenjamin antaljanosbenjamin added pr-must-backport Pull request should be backported intentionally. Use this label with great care! v25.8-must-backport v26.2-must-backport v26.3-must-backport v26.4-must-backport labels May 15, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label May 15, 2026
robot-ch-test-poll4 added a commit that referenced this pull request May 15, 2026
Cherry pick #103890 to 25.8: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
robot-clickhouse added a commit that referenced this pull request May 15, 2026
robot-ch-test-poll4 added a commit that referenced this pull request May 15, 2026
Cherry pick #103890 to 26.2: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
robot-clickhouse added a commit that referenced this pull request May 15, 2026
robot-ch-test-poll4 added a commit that referenced this pull request May 15, 2026
Cherry pick #103890 to 26.3: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
robot-clickhouse added a commit that referenced this pull request May 15, 2026
robot-ch-test-poll4 added a commit that referenced this pull request May 15, 2026
Cherry pick #103890 to 26.4: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
robot-clickhouse added a commit that referenced this pull request May 15, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label May 15, 2026
antaljanosbenjamin added a commit that referenced this pull request May 15, 2026
Backport #103890 to 26.2: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
antaljanosbenjamin added a commit that referenced this pull request May 15, 2026
Backport #103890 to 26.3: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
antaljanosbenjamin added a commit that referenced this pull request May 15, 2026
Backport #103890 to 26.4: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
antaljanosbenjamin added a commit that referenced this pull request May 15, 2026
Backport #103890 to 25.8: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…3890

Backport ClickHouse#103890 to 26.4: Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.3-must-backport v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants