Skip to content

Cherry pick #107672 to 26.5: Fix quadratic access entity cache recomputation during refresh (may lead to login hungs) - #107921

Merged
robot-clickhouse merged 9 commits into
backport/26.5/107672from
cherrypick/26.5/107672
Jun 22, 2026
Merged

robot-clickhouse merged 9 commits into
backport/26.5/107672from
cherrypick/26.5/107672

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #107672

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

azat and others added 8 commits June 16, 2026 22:44
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,
#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]>
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]>
…ntion

Fix quadratic access entity cache recomputation during refresh (may lead to login hungs)
@robot-ch-test-poll robot-ch-test-poll added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Jun 18, 2026
@robot-ch-test-poll3

Copy link
Copy Markdown
Contributor

Dear @azat, @vitlibar, this cherry-pick PR has not been updated for 3d0h48m18s. Please resolve the conflicts to backport #107672, or close this PR if the backport is no longer needed. This PR will be automatically closed after 7 days of inactivity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants