Repository navigation
Fix quadratic access entity cache recomputation during refresh (may lead to login hungs) - #107672
Conversation
The per-entity caches (`RowPolicyCache`, `RoleCache`, `SettingsProfilesCache`, `QuotaCache`) recompute every live "enabled" set on each entity change, under the same `mutex` the `ContextAccess` build path (`getEnabled*`) takes, so a slow recompute stalls session creation and query analysis for every user. None of them logged anything, so neither the entity count nor the duration was observable. Log at the end of each recompute (`mixFilters`, `collectEnabledRoles`, `mergeSettingsAndConstraints`, `chooseQuotaToConsume`) the number of enabled sets, the entity count, and the elapsed time -- at `DEBUG`, escalating to `WARNING` at >= 1000 ms so a pathological recompute surfaces without enabling debug logging. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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]>
|
Workflow [PR], commit [a4cfad8] Summary: ❌
AI ReviewSummaryThis PR coalesces access-entity cache recomputation to one batch-finished pass per Final VerdictStatus: ✅ Approve |
|
A test would be nice here. Probably it can work like this: create several users with a bunch row policies each, and then drop ZK connection, and reconnect it to make |
Follow-up to the previous two commits, applying review feedback: - `RowPolicyCache`: guard `need_mix_filters` with `TSA_GUARDED_BY(mutex)` and reorder the declarations to call order (`mixFiltersIfNeeded`, `mixFilters`, `mixFiltersFor`). - `RoleCache`: set up the batch-finished subscription in `getRole` together with the per-role change subscriptions instead of in `getEnabledRoles`, so all subscriptions live in one place. - Rename the per-cache "needs rebuild" flags after the function they gate: `need_recalculate` -> `need_collect_enabled_roles` (`RoleCache`), `need_recalculate` -> `need_merge_settings_and_constraints` (`SettingsProfilesCache`), `need_rechoose_quotas` -> `need_choose_quota` (`QuotaCache`). - Drop the redundant counters in the recompute logs: after the loop erases expired weak refs, the live-set count equals the container size. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The per-entity access caches rely on `subscribeForBatchFinished` firing exactly once after a notification batch is drained, so the expensive O(enabled sets * entities) rebuild runs once per batch instead of once per changed entity. Cover that contract directly: a batch of N entity events dispatches N per-entity notifications but invokes the batch hook only once, the hook runs after all per-entity notifications within the same `sendNotifications` call (so derived state is current on return), a single event still recomputes once, and an empty queue invokes nothing. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a counter and a microseconds timer per access cache recompute: `RowPolicyCacheRecalculations`/`RowPolicyCacheRecalculationMicroseconds` and the analogous `RoleCache*`, `SettingsProfileCache*`, `QuotaCache*` events, incremented in the coalesced per-batch recompute functions next to the existing log lines. The timers make a pathological recompute visible in `system.events` / `system.metric_log` without enabling debug logging; the plain counters give tests a deterministic signal that the recompute is coalesced to once per notification batch rather than once per changed entity. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Reproduces the multi-entity refresh that motivated the coalescing: with a user and many row policies, node2's ZooKeeper session is dropped, every policy is altered on node1, and node2 reconnects and rereads all entities in a single notification batch. The test asserts via the `RowPolicyCacheRecalculations` ProfileEvent that the row policy cache re-mixed filters about once for the whole batch rather than once per changed policy (which is what the quadratic behavior would produce). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
📊 Cloud Performance Report 🟢 AI verdict: This sync PR changes only access-control cache recompute coalescing (row-policy, role, settings-profile and quota caches); the server's query-execution hot path is untouched, so plain ClickBench/TPC-H SELECTs cannot be sped up by it. The smaller flagged improvements (clickbench Q4/Q15/Q22, tpch Q4) are downgraded as run-to-run variance since they're off this PR's path. Three large deltas — clickbench Q23 (-34%), tpch Q7 (-36%) and Q20 (-48%) — clear the high-trust threshold and are reported as-is, but they aren't attributable to this change and two have noisy histories, so a re-run is recommended to rule out baseline drift (only 6 source runs). clickbench🟢 1 improved · Flagged queries (5 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 2 improved · Flagged queries (3 of 22)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 177/180 (98.33%) | Lost baseline coverage: none · Uncovered code |
11bf272
|
I've checked this manually and previously a query can hang for up to 40+ seconds (with 50k row policies, 100 users), and now it works, but slightly slower - https://pastila.nl/?0031b026/ada03f962b6f0bba6ace0cac333a6b6b#v3mnHTF1ipbgVcOX2uwUWA==GCM (note the first output is trimmed due query just hunged) |
With many row policies, recomputing the cached filters takes seconds, and it ran while holding the lock every login needs to resolve access. So a burst of row policy changes (e.g. provisioning) stalled all logins until the rebuild finished. Now the rebuild runs on a snapshot taken under a brief lock and publishes its result atomically, so logins are no longer blocked while it runs. My test (similar to [1]), shows good results [2], so in other words 0 degradation under DROP/CREATE ROW POLICY queries. [1]: ClickHouse#107672 (comment) [2]: https://pastila.nl/?000a9f0d/098eb7d78de026b75c13a2b4e16daf0c#qHx0nBBrcjF0T5OXSsDnjQ==GCM v2: Add concurrent row policy CREATE/DROP rebuild test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
With many row policies, recomputing the cached filters takes seconds, and it ran while holding the lock every login needs to resolve access. So a burst of row policy changes (e.g. provisioning) stalled all logins until the rebuild finished. Now the rebuild runs on a snapshot taken under a brief lock and publishes its result atomically, so logins are no longer blocked while it runs. My test (similar to [1]), shows good results [2], so in other words 0 degradation under DROP/CREATE ROW POLICY queries. [1]: ClickHouse#107672 (comment) [2]: https://pastila.nl/?000a9f0d/098eb7d78de026b75c13a2b4e16daf0c#qHx0nBBrcjF0T5OXSsDnjQ==GCM v2: Add concurrent row policy CREATE/DROP rebuild test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
With many row policies, recomputing the cached filters takes seconds, and it ran while holding the lock every login needs to resolve access. So a burst of row policy changes (e.g. provisioning) stalled all logins until the rebuild finished. Now the rebuild runs on a snapshot taken under a brief lock and publishes its result atomically, so logins are no longer blocked while it runs. My test (similar to [1]), shows good results [2], so in other words 0 degradation under DROP/CREATE ROW POLICY queries. [1]: ClickHouse#107672 (comment) [2]: https://pastila.nl/?000a9f0d/098eb7d78de026b75c13a2b4e16daf0c#qHx0nBBrcjF0T5OXSsDnjQ==GCM v2: Add concurrent row policy CREATE/DROP rebuild test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cherry pick #107672 to 26.3: Fix quadratic access entity cache recomputation during refresh (may lead to login hungs)
…tion during refresh (may lead to login hungs)
Cherry pick #107672 to 26.4: Fix quadratic access entity cache recomputation during refresh (may lead to login hungs)
…tion during refresh (may lead to login hungs)
Cherry pick #107672 to 26.5: Fix quadratic access entity cache recomputation during refresh (may lead to login hungs)
…tion during refresh (may lead to login hungs)
Backport #107672 to 26.3: Fix quadratic access entity cache recomputation during refresh (may lead to login hungs)
Backport #107672 to 26.4: Fix quadratic access entity cache recomputation during refresh (may lead to login hungs)
Backport #107672 to 26.5: Fix quadratic access entity cache recomputation during refresh (may lead to login hungs)
After PR ClickHouse#107672 a coalesced rebuild that threw left its need_* flag set, but the retry was gated on `sent_any`, so sendNotifications re-ran batch handlers only on batches that delivered an event. Stale quota/role/row-policy/ settings state then persisted until an unrelated change queued a notification (an up-to-date `SYSTEM RELOAD USERS` diffs to zero and never retried). Run the handlers unconditionally; they early-return when idle. Refs: ClickHouse#107672 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
With many row policies, recomputing the cached filters takes seconds, and it ran while holding the lock every login needs to resolve access. So a burst of row policy changes (e.g. provisioning) stalled all logins until the rebuild finished. Now the rebuild runs on a snapshot taken under a brief lock and publishes its result atomically, so logins are no longer blocked while it runs. My test (similar to [1]), shows good results [2], so in other words 0 degradation under DROP/CREATE ROW POLICY queries. [1]: ClickHouse#107672 (comment) [2]: https://pastila.nl/?000a9f0d/098eb7d78de026b75c13a2b4e16daf0c#qHx0nBBrcjF0T5OXSsDnjQ==GCM v2: Add concurrent row policy CREATE/DROP rebuild test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…og queue Per maintainer review, drop the ScopedSuppressClientLogs queue-detach guard in AccessChangesNotifier::sendNotifications and instead lower the ClickHouse#107672 access cache recompute log levels: WARNING -> DEBUG (slow, >= 1000 ms) and DEBUG -> TRACE (fast) in QuotaCache, RoleCache, RowPolicyCache, SettingsProfilesCache. Both levels are now below the default client send_logs_level=warning, so the server-internal recompute diagnostics are no longer forwarded to the client that issued an access DDL. Reworked 04416 to assert the recompute line is forwarded at send_logs_level=trace (the path runs) but not at debug (the regression guard), keeping the private-table parallel-safety and the non-zero-DDL-status guard. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The test fails under the amd_tsan parallel check with "having stderror". The leaked line is a benign server log forwarded to the native client via send_logs_level: "<Warning> QuotaCache: Re-chose quotas for N enabled set(s) over M quotas in ... ms" (src/Access/QuotaCache.cpp, logged at WARNING when the recompute takes at least 1000 ms, introduced in ClickHouse#107672). CREATE/DROP QUOTA runs the access-entity notification batch synchronously on the query thread, which recomputes the quota cache. Under the thread fuzzer on sanitizer builds that coalesced recompute can cross the 1000 ms threshold (pure scheduler slowdown, not a pathological recompute), so the warning fires and is forwarded into the test's captured stderr, failing the "having stderror" check. Silence server-log forwarding on the test's DDL client calls with --send_logs_level=fatal (--allow_repeated_settings lets it override the runner-injected --send_logs_level). The quota-masking assertions are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The per-entity access caches (QuotaCache, RoleCache, RowPolicyCache, SettingsProfilesCache) recompute every enabled set on each access change. Since ClickHouse#107672 each recompute logs its size and duration, and because the recompute runs in the batch-finished callback on whichever client thread issued the access DDL, those server-internal logs were forwarded to the issuing client. clickhouse-test runs the client at send_logs_level=warning and treats any client stderr as a failure, so a slow (>= 1000 ms) recompute crossing the WARNING threshold surfaced as flaky access DDL tests on sanitizer builds (for example 02884_authentication_quota). Lower the recompute log levels in all four caches: WARNING to DEBUG for the slow path and DEBUG to TRACE for the fast path. Both are now below warning, so a client at send_logs_level=warning no longer receives them. A slow recompute remains available at an explicit send_logs_level=debug by design. Add 04416_access_cache_recompute_no_client_log_leak, a bugfix-validation regression test that probes all four caches at three client log levels: trace forwards (path is exercised), warning does not forward (the contract), and debug forwards only the fast (< 1000 ms) lines, which is the deterministic discriminator (DEBUG on master, TRACE on the fix) that fails on master and passes on the fix without reintroducing threshold flakiness. Co-authored-by: Alexey Milovidov <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tings profiles Follow up for ClickHouse#107672. The access-cache recompute log lines (QuotaCache, RoleCache, RowPolicyCache, SettingsProfilesCache) were forwarded to the client that issued an access DDL. Lower them so they are not sent at the default client log level: slow (>= 1000 ms) recompute LOG_WARNING -> LOG_DEBUG, fast (< 1000 ms) recompute LOG_DEBUG -> LOG_TRACE. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The test fails under the amd_tsan parallel check with "having stderror". The leaked line is a benign server log forwarded to the native client via send_logs_level: "<Warning> QuotaCache: Re-chose quotas for N enabled set(s) over M quotas in ... ms" (src/Access/QuotaCache.cpp, logged at WARNING when the recompute takes at least 1000 ms, introduced in ClickHouse#107672). CREATE/DROP QUOTA runs the access-entity notification batch synchronously on the query thread, which recomputes the quota cache. Under the thread fuzzer on sanitizer builds that coalesced recompute can cross the 1000 ms threshold (pure scheduler slowdown, not a pathological recompute), so the warning fires and is forwarded into the test's captured stderr, failing the "having stderror" check. Silence server-log forwarding on the test's DDL client calls with --send_logs_level=fatal (--allow_repeated_settings lets it override the runner-injected --send_logs_level). The quota-masking assertions are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tings profiles Follow up for ClickHouse#107672. The access-cache recompute log lines (QuotaCache, RoleCache, RowPolicyCache, SettingsProfilesCache) were forwarded to the client that issued an access DDL. Lower them so they are not sent at the default client log level: slow (>= 1000 ms) recompute LOG_WARNING -> LOG_DEBUG, fast (< 1000 ms) recompute LOG_DEBUG -> LOG_TRACE. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed long login and query-startup stalls with replicated access storage when many access entities (row policies, roles, quotas, settings profiles) change at once. Each per-entity cache now recomputes once per notification batch instead of once per changed entity, removing quadratic work that could hold the access lock for minutes.
With replicated (Keeper-backed) access storage, applying many access changes at once — row policies, roles, quotas, or settings profiles — could stall logins and query startup for a long time (minutes in production), even on replicas that only observe the change.
The notifier already delivers a whole change in one pass, so each cache now does only the cheap per-object bookkeeping on each notification and runs the single expensive rebuild once per batch instead of once per object. A batch changing N objects does ~1 rebuild instead of N; a single statement still rebuilds exactly once; and the rebuild completes before the call returns, so access stays current.
Also logs each rebuild's size and duration (DEBUG, raised to WARNING at ≥1s) so a slow rebuild is visible without enabling debug logging.
Refs: #107097
Version info
26.6.1.100626.5.3.51,26.4.5.58,26.3.14.48