Skip to content

feat: Add support for Topology Spread Constraints in Karmada components#7558

Open
Ebraam-Ashraf wants to merge 3 commits into
karmada-io:masterfrom
Ebraam-Ashraf:feature/operator-topology-spread-constraints
Open

feat: Add support for Topology Spread Constraints in Karmada components#7558
Ebraam-Ashraf wants to merge 3 commits into
karmada-io:masterfrom
Ebraam-Ashraf:feature/operator-topology-spread-constraints

Conversation

@Ebraam-Ashraf
Copy link
Copy Markdown

What type of PR is this?

/kind feature
/kind api-change

What this PR does / why we need it:

Adds a topologySpreadConstraints field to the CommonSettings struct so
that users can control how control plane component pod replicas are distributed
across topology domains (zones, nodes, racks, etc.) using the standard
Kubernetes Topology Spread Constraints mechanism.

This complements the existing affinity field. Unlike podAntiAffinity, which
blocks scheduling entirely when replicas exceed node count, topology spread
constraints keep distribution as even as possible — making them the safer choice
for node pools that may grow or shrink over time.

Key use cases:

  • Spreading karmada-search replicas across nodes in a targeted large-VM node pool
  • Ensuring karmada-apiserver replicas are distributed one-per-zone in multi-zone clusters
  • Protecting etcd quorum by guaranteeing replicas span multiple zones

Which issue(s) this PR fixes:

Part of #7436

Special notes for your reviewer:

  • The topologySpreadConstraints and affinity (podAntiAffinity) fields are
    fully complementary and can be used together. When both are specified,
    Kubernetes evaluates them jointly.
  • All 11 generated applyconfigurations files were updated to use the correct
    *corev1.TopologySpreadConstraintApplyConfiguration pointer type, matching
    the existing pattern for Tolerations and Affinity.
  • CRDs were regenerated via hack/update-crdgen.sh.
  • Tests were added for all control plane components, exceeding the proposal's
    requirement of at least one Deployment and one StatefulSet.

Does this PR introduce a user-facing change?:

API Change: Added `spec.components.*.topologySpreadConstraints` field to the
Karmada API. This allows users to configure Topology Spread Constraints on any
Karmada control plane component pod to control replica distribution across
topology domains (zones, nodes, etc.) for high availability.

Copilot AI review requested due to automatic review settings May 26, 2026 19:52
@karmada-bot karmada-bot added the kind/feature Categorizes issue or PR as related to a new feature. label May 26, 2026
@karmada-bot karmada-bot added the kind/api-change Categorizes issue or PR as related to adding, removing, or otherwise changing an API label May 26, 2026
@karmada-bot karmada-bot requested a review from Poor12 May 26, 2026 19:52
@karmada-bot
Copy link
Copy Markdown
Contributor

Welcome @Ebraam-Ashraf! It looks like this is your first PR to karmada-io/karmada 🎉

@karmada-bot karmada-bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label May 26, 2026
@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces support for Kubernetes Topology Spread Constraints within the Karmada operator. By exposing this configuration in the CommonSettings API, users can now exert finer control over how control plane component pods are distributed across topology domains such as zones or nodes. This enhancement provides a more flexible and resilient alternative to traditional pod anti-affinity, significantly improving high availability for Karmada deployments.

Highlights

  • API Enhancement: Added the topologySpreadConstraints field to the CommonSettings struct, allowing users to define pod distribution constraints across topology domains.
  • Patcher Utility Update: Updated the Patcher utility to support applying topology spread constraints to both Deployments and StatefulSets.
  • Component Integration: Integrated the new configuration across all Karmada control plane components, including the APIServer, Controller Manager, Scheduler, and Etcd.
  • Test Coverage: Added comprehensive unit tests for all affected control plane components to verify the correct application of topology spread constraints.
  • Code Generation: Regenerated deepcopy and applyconfigurations files to include the new field support.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

This PR adds support for configuring Kubernetes topologySpreadConstraints across operator-managed components by extending the shared patcher, API types, and CRD schemas, plus adding/update unit tests to validate propagation into generated Deployments/StatefulSets.

Changes:

  • Extend the Patcher to accept and apply TopologySpreadConstraints to Deployments and StatefulSets.
  • Add topologySpreadConstraints to CommonSettings (API type + CRD schemas, including Helm chart CRD template).
  • Add tests across patcher and controlplane components to verify constraints are applied.

Reviewed changes

Copilot reviewed 15 out of 29 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
operator/pkg/util/patcher/pather.go Add topologySpreadConstraints field + setter and apply to pod specs.
operator/pkg/util/patcher/pather_test.go Add patcher-level tests for constraints patching / not patching.
operator/pkg/controlplane/webhook/webhook.go Pass TopologySpreadConstraints into patcher for webhook deployment.
operator/pkg/controlplane/webhook/webhook_test.go Add webhook install test covering topology spread constraints.
operator/pkg/controlplane/search/search.go Pass TopologySpreadConstraints into patcher for search deployment.
operator/pkg/controlplane/search/search_test.go Add search install test covering topology spread constraints.
operator/pkg/controlplane/metricsadapter/metricsadapter.go Pass TopologySpreadConstraints into patcher for metrics-adapter deployment.
operator/pkg/controlplane/metricsadapter/metricsadapter_test.go Add metrics-adapter install test covering topology spread constraints.
operator/pkg/controlplane/etcd/etcd.go Pass TopologySpreadConstraints into patcher for etcd statefulset.
operator/pkg/controlplane/etcd/etcd_test.go Add etcd install test covering topology spread constraints.
operator/pkg/controlplane/controlplane.go Pass TopologySpreadConstraints into patcher for controlplane deployments.
operator/pkg/controlplane/controlplane_test.go Add manifest tests covering topology spread constraints across controlplane components.
operator/pkg/controlplane/apiserver/apiserver.go Pass TopologySpreadConstraints into patcher for API server deployments.
operator/pkg/controlplane/apiserver/apiserver_test.go Add API server install tests covering topology spread constraints.
operator/pkg/apis/operator/v1alpha1/type.go Add TopologySpreadConstraints to CommonSettings API type.
operator/config/crds/operator.karmada.io_karmadas.yaml Extend CRD OpenAPI schema with topologySpreadConstraints.
charts/karmada-operator/templates/crd-operator.karmada.io_karmadas.yaml Mirror CRD schema changes in Helm chart template.
Files not reviewed (1)
  • operator/pkg/apis/operator/v1alpha1/zz_generated.deepcopy.go: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +131 to +135
// WithTopologySpreadConstraints sets topology spread constraints to the patcher.
func (p *Patcher) WithTopologySpreadConstraints(constraints []corev1.TopologySpreadConstraint) *Patcher {
p.topologySpreadConstraints = constraints
return p
}
Comment on lines +152 to +154
if len(p.topologySpreadConstraints) > 0 {
deployment.Spec.Template.Spec.TopologySpreadConstraints = p.topologySpreadConstraints
}
Comment on lines +202 to +207
if len(deployment.Spec.Template.Spec.TopologySpreadConstraints) != 1 {
t.Fatalf("expected 1 topology spread constraint, but got %d", len(deployment.Spec.Template.Spec.TopologySpreadConstraints))
}
if deployment.Spec.Template.Spec.TopologySpreadConstraints[0].TopologyKey != "topology.kubernetes.io/zone" {
t.Errorf("expected topology key 'topology.kubernetes.io/zone', but got '%s'", deployment.Spec.Template.Spec.TopologySpreadConstraints[0].TopologyKey)
}
}
}

func TestGetKubeControllerManagerManifestWithTopologySpreadConstraints(t *testing.T) {
}
}

func TestGetKarmadaControllerManagerManifestWithTopologySpreadConstraints(t *testing.T) {
}
}

func TestGetKarmadaSchedulerManifestWithTopologySpreadConstraints(t *testing.T) {
}
}

func TestGetKarmadaDeschedulerManifestWithTopologySpreadConstraints(t *testing.T) {
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for TopologySpreadConstraints across various Karmada control plane components (including APIServer, Controller Manager, Scheduler, Descheduler, Etcd, Metrics Adapter, Search, and Webhook). This is achieved by adding the field to the CommonSettings API definition, updating the Patcher utility to apply these constraints to Deployments and StatefulSets, and adding corresponding unit tests. One review comment was kept, which suggests improving code clarity in etcd.go by explicitly accessing embedded fields via cfg.CommonSettings rather than directly through cfg.

Comment thread operator/pkg/controlplane/etcd/etcd.go Outdated
Comment on lines +101 to +102
WithTolerations(cfg.Tolerations).WithAffinity(cfg.Affinity).
WithTopologySpreadConstraints(cfg.TopologySpreadConstraints).WithVolumeData(cfg.VolumeData).ForStatefulSet(etcdStatefulSet)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

When accessing fields from an embedded struct, prefer explicit access through the struct name for clarity, even if direct access is possible. Please access Tolerations, Affinity, and TopologySpreadConstraints through cfg.CommonSettings.

Suggested change
WithTolerations(cfg.Tolerations).WithAffinity(cfg.Affinity).
WithTopologySpreadConstraints(cfg.TopologySpreadConstraints).WithVolumeData(cfg.VolumeData).ForStatefulSet(etcdStatefulSet)
WithTolerations(cfg.CommonSettings.Tolerations).WithAffinity(cfg.CommonSettings.Affinity).
WithTopologySpreadConstraints(cfg.CommonSettings.TopologySpreadConstraints).WithVolumeData(cfg.VolumeData).ForStatefulSet(etcdStatefulSet)
References
  1. When accessing fields from an embedded struct, prefer explicit access through the struct name for clarity, even if direct access is possible.

@Ebraam-Ashraf
Copy link
Copy Markdown
Author

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented May 26, 2026

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 25.80645% with 69 lines in your changes missing coverage. Please review.
✅ Project coverage is 42.10%. Comparing base (8eb0d30) to head (670aafb).
⚠️ Report is 4 commits behind head on master.

Files with missing lines Patch % Lines
...configurations/operator/v1alpha1/commonsettings.go 0.00% 6 Missing ⚠️
...ns/operator/v1alpha1/karmadaaggregatedapiserver.go 0.00% 6 Missing ⚠️
...nfigurations/operator/v1alpha1/karmadaapiserver.go 0.00% 6 Missing ⚠️
...ions/operator/v1alpha1/karmadacontrollermanager.go 0.00% 6 Missing ⚠️
...igurations/operator/v1alpha1/karmadadescheduler.go 0.00% 6 Missing ⚠️
...rations/operator/v1alpha1/karmadametricsadapter.go 0.00% 6 Missing ⚠️
...nfigurations/operator/v1alpha1/karmadascheduler.go 0.00% 6 Missing ⚠️
...yconfigurations/operator/v1alpha1/karmadasearch.go 0.00% 6 Missing ⚠️
...configurations/operator/v1alpha1/karmadawebhook.go 0.00% 6 Missing ⚠️
...rations/operator/v1alpha1/kubecontrollermanager.go 0.00% 6 Missing ⚠️
... and 2 more
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7558      +/-   ##
==========================================
- Coverage   42.12%   42.10%   -0.03%     
==========================================
  Files         879      879              
  Lines       54649    54767     +118     
==========================================
+ Hits        23022    23060      +38     
- Misses      29898    29973      +75     
- Partials     1729     1734       +5     
Flag Coverage Δ
unittests 42.10% <25.80%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jabellard
Copy link
Copy Markdown
Member

Welcome @Ebraam-Ashraf! It looks like this is your first PR to karmada-io/karmada 🎉

Wow! @Ebraam-Ashraf , I'm very happy to celebrate this milestone with you. Working on such an essential feature for you first PR is quite impressive.

@jabellard
Copy link
Copy Markdown
Member

@jabellard @zhzhuang-zju @RainbowMango

Thanks! Will take a look.

@jabellard
Copy link
Copy Markdown
Member

@Ebraam-Ashraf, please get the DCO done. I see that step failling.

@jabellard
Copy link
Copy Markdown
Member

/assign

@karmada-bot
Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign rainbowmango for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

Signed-off-by: Ebraam <ebraam.ashraf@gmail.com>
Signed-off-by: Ebraam <ebraam.ashraf@gmail.com>
Signed-off-by: Ebraam <ebraam.ashraf@gmail.com>
@Ebraam-Ashraf Ebraam-Ashraf force-pushed the feature/operator-topology-spread-constraints branch from 952b9fc to 670aafb Compare May 27, 2026 07:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/api-change Categorizes issue or PR as related to adding, removing, or otherwise changing an API kind/feature Categorizes issue or PR as related to a new feature. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants