Skip to content

Do not hold mutex across ZooKeeper reads in access entities refresh - #107097

Merged
azat merged 2 commits into
ClickHouse:masterfrom
azat:fix-locking-during-update-access-from-zk
Jun 11, 2026
Merged

azat merged 2 commits into
ClickHouse:masterfrom
azat:fix-locking-during-update-access-from-zk

Conversation

@azat

@azat azat commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

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

Do not hold mutex across ZooKeeper reads in access entities refresh

ZooKeeperReplicator::refreshEntities held mutex across one synchronous ZooKeeper round trip per access entity. The same mutex is taken by findEntity, which sits on the hot path of authentication (AccessControl::authenticate -> MultipleAccessStorage::findImpl) and of Context::getAccess during query analysis. A full refresh (all=true) runs on every session expiry and on config-driven session recreation; when Keeper round trips are slow (e.g. right after a Keeper rolling restart, when every component reconnects through the freshly created shared session), the refresh holds the mutex for N * latency, during which the server accepts no new connections and query analysis stalls. Observed in production as a 693-second hold that blocked all queries for the whole window.

Version info

  • Merged into: 26.6.1.689
  • Backported to: 26.5.3.22, 26.4.5.29, 26.3.14.23, 25.8.25.22

ZooKeeperReplicator::refreshEntities held `mutex` across one synchronous
ZooKeeper round trip per access entity. The same mutex is taken by
findEntity, which sits on the hot path of authentication
(AccessControl::authenticate -> MultipleAccessStorage::findImpl) and of
Context::getAccess during query analysis. A full refresh (all=true)
runs on every session expiry and on config-driven session recreation;
when Keeper round trips are slow (e.g. right after a Keeper rolling
restart, when every component reconnects through the freshly created
shared session), the refresh holds the mutex for N * latency, during
which the server accepts no new connections and query analysis stalls.
Observed in production as a 693-second hold that blocked all queries for
the whole window.

Read the entities without the lock and take `mutex` only around the
memory_storage updates. Writers are unaffected: entity CRUD already
reads from ZooKeeper before locking (refreshEntity). The one semantic
change is that an entity mutated locally while a full reload is reading
the snapshot may be transiently overwritten by setAll with the older
snapshot; the per-entity and children watches registered by the reads
re-deliver such changes immediately afterwards, which is the same
eventual-consistency behavior remote mutations always had (previously
the local writer would instead block on the mutex for the whole
refresh).

refreshEntityNoLock is inlined into its only remaining use via
refreshEntity and removed.

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

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b8971ac]

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 moves slow ZooKeeper entity reads out from under the hot replicated-access memory_storage mutex while preserving read-to-publish ordering with a dedicated refresh_mutex. The current version addresses the stale snapshot race raised in the previous inline thread, and I did not find remaining correctness, safety, or metadata issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
Comment thread src/Access/ZooKeeperReplicator.cpp Resolved
@azat azat added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jun 11, 2026
The previous commit moved the ZooKeeper reads of `refreshEntities` out
of `mutex`, which allowed a publish based on an older ZooKeeper read to
overwrite a publish based on a newer one: a full refresh (all=true)
reads a user, a concurrent REVOKE writes ZooKeeper and publishes the
updated user via `refreshEntity`, and then `setAll` overwrites it with
the pre-REVOKE snapshot. Until the watch registered by the stale read
fires, authentication and `Context::getAccess` can observe grants that
REVOKE has already reported removed. The same read->publish inversion
existed for two concurrent `refreshEntity` calls on the same entity,
for `removeAllExcept` racing a concurrent `insertEntity` (this one
predates the previous commit: the children list was always read outside
`mutex`), and for `removeEntity` racing a full refresh (a dropped user
resurrected by a stale snapshot, with repair delayed until the children
watch fires because the per-entity watch only reacts to `CHANGED`).

Instead of gating only `setAll` on a generation counter (which would
leave the other three races open), restore the invariant the code had
while everything ran under `mutex` -- every "read from ZooKeeper, then
publish into `memory_storage`" sequence is atomic with respect to every
other one -- but on a dedicated `refresh_mutex`. It is held across
`refreshEntities` (both modes, including the children read),
`refreshEntity`, and the cache removal of `removeEntity`. Since the
sequences are totally ordered and ZooKeeper reads through a session are
monotonic, a later read always observes state at least as new as any
earlier published one, so the last publish wins with the newest state;
in particular, once a local write has published its own refresh, no
stale snapshot can be published over it. `mutex` now only guards
`memory_storage` and is held for in-memory operations only, so the hot
path (`findEntity` in authentication and query analysis) still never
waits for ZooKeeper.

Writers (RBAC DDL) and the watching thread serialize with full
refreshes exactly as they did before the previous commit (back then
they serialized on `mutex`). The one remaining stale window is
cross-session: a full refresh on a freshly created session can read a
lagging follower and miss a write committed through the old session
after the new session's sync; it also predates the previous commit and
self-heals when the follower applies the missed transaction and fires
the read's watch.

Lock order: cached_zookeeper_mutex -> refresh_mutex -> mutex.

Co-Authored-By: Claude Fable 5 <[email protected]>
@azat
azat enabled auto-merge June 11, 2026 16:46
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.60% -0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 32/32 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@azat
azat added this pull request to the merge queue Jun 11, 2026
Merged via the queue into ClickHouse:master with commit 48658ff Jun 11, 2026
325 of 328 checks passed
@azat
azat deleted the fix-locking-during-update-access-from-zk branch June 11, 2026 20:20
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 11, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 11, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 11, 2026
Cherry pick #107097 to 25.8: Do not hold mutex across ZooKeeper reads in access entities refresh
robot-clickhouse added a commit that referenced this pull request Jun 11, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 11, 2026
Cherry pick #107097 to 26.3: Do not hold mutex across ZooKeeper reads in access entities refresh
robot-clickhouse added a commit that referenced this pull request Jun 11, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 11, 2026
Cherry pick #107097 to 26.4: Do not hold mutex across ZooKeeper reads in access entities refresh
robot-clickhouse added a commit that referenced this pull request Jun 11, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 11, 2026
Cherry pick #107097 to 26.5: Do not hold mutex across ZooKeeper reads in access entities refresh
robot-clickhouse added a commit that referenced this pull request Jun 11, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 11, 2026
azat added a commit that referenced this pull request Jun 12, 2026
Backport #107097 to 26.4: Do not hold mutex across ZooKeeper reads in access entities refresh
azat added a commit that referenced this pull request Jun 12, 2026
Backport #107097 to 26.5: Do not hold mutex across ZooKeeper reads in access entities refresh
azat added a commit that referenced this pull request Jun 12, 2026
Backport #107097 to 26.3: Do not hold mutex across ZooKeeper reads in access entities refresh
azat added a commit that referenced this pull request Jun 12, 2026
Backport #107097 to 25.8: Do not hold mutex across ZooKeeper reads in access entities refresh
@azat azat added v25.12-must-backport v26.2-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels Jun 12, 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 Jun 12, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jun 18, 2026
Each per-entity cache recomputes every live "enabled" set on every
entity change, under the `mutex` the `ContextAccess` build path takes.
Notifications arrive one per changed entity, so a batch changing N
entities does N full O(enabled sets * entities) rebuilds, degenerating
to O(enabled sets * entities^2) when a refresh changes everything
(e.g. after a Keeper session is recreated,
ClickHouse#107097). In one
installation with ~50K row policies and a few hundred enabled sets a
single rebuild is tens of millions of ops; repeated per changed policy
it held the lock for minutes, blocking session creation and query
analysis.

`sendNotifications` already drains the whole queue (an entire refresh)
in one call, so add a batch-finished hook (`subscribeForBatchFinished`)
invoked once after the queue is drained. Each per-entity handler now
only updates its `all_*` map and sets a dirty flag; the rebuild runs
once per batch if dirty. This drops a batch to O(enabled sets *
entities). The rebuild still completes within the same
`sendNotifications` call, so state is current once it returns, and
single-DDL notifications still recompute exactly once.

`RoleCache` subscribes on first `getEnabledRoles`, not in its ctor,
because `changes_notifier` is constructed after the caches.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Slach added a commit to Slach/ClickHouse that referenced this pull request Jul 14, 2026
…esolution

The fix for the UNKNOWN_ROLE race was already merged into master via
ClickHouse#107097 (refresh_mutex +
scoped mutex locks at publish points). The merge of master into this
branch (db83926) incorrectly kept the older approach's outer
std::lock_guard lock{mutex} before getChildrenWatch on top of it,
producing a double lock of mutex in refreshEntities and failing the
build with -Wshadow and -Wthread-safety-analysis:

https://github.com/ClickHouse/ClickHouse/actions/runs/29334767283/job/87091850817

Remove the leftover hunk so ZooKeeperReplicator.cpp matches master;
this PR now only adds the integration test.

Co-Authored-By: Claude Fable 5 <[email protected]>
Slach added a commit to Slach/ClickHouse that referenced this pull request Jul 15, 2026
The fix itself was merged via ClickHouse#107097,
so this PR is test-only now and Bugfix validation no longer applies.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai groeneai mentioned this pull request Jul 21, 2026
1 task done
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
…7097

Backport ClickHouse#107097 to 26.4: Do not hold mutex across ZooKeeper reads in access entities refresh
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…esolution

The fix for the UNKNOWN_ROLE race was already merged into master via
ClickHouse#107097 (refresh_mutex +
scoped mutex locks at publish points). The merge of master into this
branch (db83926) incorrectly kept the older approach's outer
std::lock_guard lock{mutex} before getChildrenWatch on top of it,
producing a double lock of mutex in refreshEntities and failing the
build with -Wshadow and -Wthread-safety-analysis:

https://github.com/ClickHouse/ClickHouse/actions/runs/29334767283/job/87091850817

Remove the leftover hunk so ZooKeeperReplicator.cpp matches master;
this PR now only adds the integration test.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The fix itself was merged via ClickHouse#107097,
so this PR is test-only now and Bugfix validation no longer applies.

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

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 v25.12-must-backport v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants