Skip to content

fix: limit kube loading to filter based on labels - #419

Open
hiporox wants to merge 6 commits into
ClickHouse:mainfrom
chalk-ai:main
Open

hiporox wants to merge 6 commits into
ClickHouse:mainfrom
chalk-ai:main

Conversation

@hiporox

@hiporox hiporox commented Dec 2, 2026 •

Copy link
Copy Markdown

Why

While we can use the watchNamespaces to limit the surface area that the operator looks at, if the namespace is heavily populated, it will end up loading a huge amount of data from kube. This causes unnecessary memory spikes.

What

This PR changes it so that we filter on existing kube labels to make it so that we only load relevant Keeper and Clickhouse objects. It also adds a new label to Keeper objects that would not otherwise be able to be easily filtered for, and performs that label migration on boot to keep backwards compatibility. Should reduce the memory used by the operator massively and allow it to be deployed into clusters without the watchNamespaces setting and not have it query everything in the cluster


Note

Medium Risk
Changes core caching and reconcile read paths for all managed resources; startup migration and API fallbacks must work correctly or existing Keeper clusters could be mis-reconciled.

Overview
Limits the operator’s controller-runtime informers to operator-labeled Services, ConfigMaps, Secrets, PDBs, NetworkPolicies, StatefulSets, PVCs, Jobs, and Pods so large namespaces no longer fill the cache with unrelated objects. Secrets stay uncached via DisableFor, since user or pre-created cluster secrets may not carry the cluster label.

On startup, migrateLegacyLabels (2-minute timeout) patches Keeper-owned legacy resources missing clickhouse.com/cluster before controllers run. New Keeper templates add clusterLabels on created resources; version-probe job pods get a role label so they stay visible in the filtered Pod cache.

Reconcile paths use GetAPIReader when the cache reports NotFound: ResourceManager avoids duplicate creates, can relabel unchanged specs, and refetches from the API on update conflicts; keeper loadQuorumReplicas does the same for the quorum ConfigMap so an empty quorum is not assumed.

Reviewed by Cursor Bugbot for commit 393a969. Bugbot is set up for automated code reviews on this repo. Configure here.


Workflow [PR]

hiporox and others added 4 commits December 2, 2026 11:24
The operator watched every Pod, Service, ConfigMap, Secret, Job,
StatefulSet, PDB and NetworkPolicy in the cluster, so on large clusters
the initial cache sync alone could exceed the manager's memory limit and
OOMKill it shortly after acquiring the leader lease.

- Stamp app.kubernetes.io/managed-by=clickhouse-operator on every object
  the operator creates directly (via ReconcileResource, replica
  StatefulSets, version probe Jobs and the cluster Secret).
- Restrict those kinds' informers to that label. Pods and PVCs are
  restricted by the existing clickhouse.com/role label instead, so
  existing replicas don't need a pod template change (rolling restart).
- Read Secrets directly from the API server, since user-supplied secrets
  (externalSecret or a pre-created cluster secret) are unlabeled.
- At startup, label objects created by older operator versions that are
  controlled by a ClickHouseCluster/KeeperCluster, so they stay visible
  through the filtered cache. Adds the patch RBAC verb this needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace the app.kubernetes.io/managed-by label with selectors on labels
the operator already sets:

- Service, ConfigMap, Secret, PDB, NetworkPolicy: clickhouse.com/cluster exists
- StatefulSet, PVC: clickhouse.com/role in (clickhouse-server, clickhouse-keeper)
- Job: clickhouse.com/role=version-probe
- Pod: clickhouse.com/role in (clickhouse-server, clickhouse-keeper, version-probe)

KeeperCluster's Service, PDB, NetworkPolicy and ConfigMaps were the only
operator objects without clickhouse.com/cluster; they now carry it. The
startup migration is reduced to adding it to those objects when they were
created by an older version, using update (no new RBAC verbs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix: restrict informer caches to operator-managed objects

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread internal/app/cache.go Resolved
@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

AI review gate — AI review passed

Clean review from: Cursor Bugbot.

The label-filtered cache hides operator-managed objects that lack the
selector labels, e.g. Keeper objects created by an older operator replica
still leading during a rolling upgrade, after the boot-time relabeling ran.
ReconcileResource then saw NotFound and Create failed with AlreadyExists,
and the quorum ConfigMap read as an empty quorum.

- Controllers expose an uncached APIReader (mgr.GetAPIReader()).
- ReconcileResource confirms a cache miss with the API before creating.
  If the object exists with an up-to-date spec, it only adds the missing
  labels (reported as unchanged, so no reload/restart side effects); if
  the spec is outdated, the normal update also merges the labels. Either
  way the object becomes visible to the cache again.
- loadQuorumReplicas confirms a cache miss with the API instead of
  treating it as an empty quorum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c63840a. Configure here.

Comment thread internal/controller/resourcemanager.go Resolved
ResourceManager.Update refreshed resourceVersion through the cached
client on conflict. Objects found via the ReconcileResource API fallback
lack the cache's selector labels, so that re-read returned NotFound and
the relabel or spec update failed instead of retrying. Re-read through
the API reader, which is also never stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hiporox

hiporox commented Dec 2, 2026

Copy link
Copy Markdown
Author

I can't seem to request a review, so tagging to ask for one @GrigoryPervakov

@clickhouse-operator

clickhouse-operator Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Workflow [PR], commit [393a969]

Summary: ✅


Code Review

Result: ✅ No issues found

What changed: Restricts controller-runtime caches to operator-managed Kubernetes objects using existing cluster and role labels. It migrates legacy Keeper resources at startup, adds missing Keeper and version-probe labels, and introduces direct API-reader fallbacks for cache misses and update conflicts.

No actionable correctness issues found in the current changes.

Investigation: 6/13 rounds, 42 tool calls.

@GrigoryPervakov GrigoryPervakov left a comment

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.

@hiporox, thank you for the contribution.

I'd prefer to do it differently. Let's split it into 2 parts:

  • PR 1 that labels all managed resources with the clickhouse.com/cluster label. ClickHouse resources already have it, so it's mostly Keeper ones, including pods and the version probe pod. I planned to create a new release after a few existing PRs are merged, and now I want to include it in this release. Could you extract it into a separate PR?
  • After the release, we can merge the second part with the caches (likely with an opt-out setting) without migration support, as most users will be updated by the previous release.

Comment thread internal/app/cache.go
Comment on lines +52 to +67
return map[client.Object]cache.ByObject{
&corev1.Service{}: byCluster,
&corev1.ConfigMap{}: byCluster,
&corev1.Secret{}: byCluster,
&policyv1.PodDisruptionBudget{}: byCluster,
&networkingv1.NetworkPolicy{}: byCluster,
&appsv1.StatefulSet{}: {Label: replicas},
&corev1.PersistentVolumeClaim{}: {Label: replicas},
&batchv1.Job{}: {Label: roleSelector(controllerutil.LabelVersionProbe)},
&corev1.Pod{}: {Label: roleSelector(
controllerutil.LabelClickHouseValue,
controllerutil.LabelKeeperValue,
controllerutil.LabelVersionProbe,
)},
}
}

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.

Let's use a single clickhouse.com/cluster Exists for all resources. PVCs are hard to migrate, and they may also be user-provided, so let's move them to uncachedObjects as well.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants