This is an automated email from the ASF dual-hosted git repository.

villebro pushed a commit to branch main
in repository 
https://gitbox.apache.org/repos/asf/superset-kubernetes-operator.git


The following commit(s) were added to refs/heads/main by this push:
     new fc4128d  feat(api): add scalingMode External for externally managed 
replicas (#506)
fc4128d is described below

commit fc4128d8dea8c64840106a23eb8152250c381ed1
Author: Luis Carbonell <[email protected]>
AuthorDate: Mon Nov 16 21:49:44 2026 +0100

    feat(api): add scalingMode External for externally managed replicas (#506)
    
    * feat(api): add scalingMode External for externally managed replicas
    
    Scalable components had no way to hand Deployment replicas to an external
    controller such as KEDA. Without autoscaling, the resolver defaults
    replicas to 1 and the operator rewrites them on every reconcile, so it
    fights any external HPA (the external-controller counterpart of #151).
    With autoscaling set, the operator owns a same-named HPA instead.
    
    scalingMode: External on a scalable component leaves replicas unset on
    the Deployment, so the existing preserveDeploymentReplicasWhenUnmanaged
    path keeps the live count, drops inherited spec.autoscaling so no
    operator HPA is created (an existing one is removed), and reports
    status without the operator HPA. CEL rejects replicas or autoscaling on
    the same component.
    
    * feat(api): add top-level scalingMode with per-component override
    
    Per the top-level defaults guideline (#508), scalingMode is now declared
    at both levels and resolved like autoscaling: a component's value
    overrides spec.scalingMode, so Operator opts one component out of a
    top-level External. Celery beat and lifecycle Jobs ignore it.
    
    The one-owner-of-the-replica-count rules move to SupersetSpec and check
    the effective mode: top-level External rejects top-level replicas and
    autoscaling, and each scalable component rejects its own replicas or
    autoscaling when its effective mode is External, pointing at
    scalingMode: Operator. They replace the five per-component copies.
    
    ScalingMode.IsExternal() replaces the duplicated checks in the resolver
    and status. The test fixture HPA now carries a controller reference,
    since #507 only deletes HPAs this Superset controls. Docs show both
    forms and what follows a lifecycle drain.
    
    * docs(releases): note external scaling; resolve status scalingMode in one 
place
    
    Add the Unreleased entry for scalingMode, and resolve the component and
    top-level scalingMode in status with resolution.ResolveOverridableValue
    so it stays in step with the resolver.
    
    * docs: cover switching modes and a production-ready KEDA example
    
    The KEDA example now authenticates through a TriggerAuthentication that
    reads the same Secret key as valkey.passwordFrom, and notes enableTLS
    and databaseIndex for valkey.ssl and valkey.celeryBroker.database. The
    guide warns that KEDA's minReplicaCount defaults to 0, which suits
    Celery workers but not components that serve HTTP, and how to keep
    scale-in from stopping a worker mid-task. A new "Switching modes"
    section orders the hand-over between the operator and KEDA in both
    directions so only one of them sets the replica count.
    
    The architecture docs list External in the replicas resolution order.
    The reconcile test now also covers a newly created externally scaled
    Deployment, which must have no replicas set.
---
 api/v1alpha1/shared_types.go                       | 24 ++++++++
 api/v1alpha1/superset_types.go                     | 10 ++++
 api/v1alpha1/zz_generated.deepcopy.go              | 10 ++++
 .../crds/superset.apache.org_supersets.yaml        | 67 ++++++++++++++++++++++
 .../crd/bases/superset.apache.org_supersets.yaml   | 67 ++++++++++++++++++++++
 docs/architecture/internals.md                     |  7 ++-
 docs/architecture/overview.md                      |  4 +-
 docs/reference/api-reference.md                    | 31 ++++++++++
 docs/reference/releases.md                         |  1 +
 docs/user-guide/configuration.md                   | 67 ++++++++++++++++++++++
 internal/controller/cel_validation_test.go         | 58 +++++++++++++++++++
 internal/controller/component_descriptors.go       |  3 +
 internal/controller/config_builder.go              | 10 +++-
 .../controller/reconcile_parent_resources_test.go  | 52 +++++++++++++++++
 internal/controller/status.go                      | 17 ++++++
 internal/controller/status_test.go                 | 27 +++++++++
 internal/resolution/resolver.go                    | 14 +++++
 internal/resolution/resolver_test.go               | 35 +++++++++++
 18 files changed, 498 insertions(+), 6 deletions(-)

diff --git a/api/v1alpha1/shared_types.go b/api/v1alpha1/shared_types.go
index ce15b2d..8c71b42 100644
--- a/api/v1alpha1/shared_types.go
+++ b/api/v1alpha1/shared_types.go
@@ -676,6 +676,24 @@ type ContainerTemplate struct {
 
 // --- Scaling and component types ---
 
+// ScalingMode selects who manages a component Deployment's replica count.
+// +kubebuilder:validation:Enum=Operator;External
+type ScalingMode string
+
+const (
+       // ScalingModeOperator sets the replica count from replicas or 
autoscaling.
+       ScalingModeOperator ScalingMode = "Operator"
+       // ScalingModeExternal leaves the replica count to an external 
controller,
+       // such as a KEDA ScaledObject or a user-managed 
HorizontalPodAutoscaler.
+       ScalingModeExternal ScalingMode = "External"
+)
+
+// IsExternal reports whether an external controller owns the replica count.
+// A nil mode is the default, Operator.
+func (m *ScalingMode) IsExternal() bool {
+       return m != nil && *m == ScalingModeExternal
+}
+
 // ScalableComponentSpec provides deployment template and scaling fields.
 // Embedded by scalable components (WebServer, CeleryWorker, CeleryFlower,
 // WebsocketServer, McpServer). Non-scalable components (CeleryBeat, Init)
@@ -693,6 +711,12 @@ type ScalableComponentSpec struct {
        // HorizontalPodAutoscaler configuration. When set, the HPA manages 
replica count. Overrides spec.autoscaling.
        // +optional
        Autoscaling *AutoscalingSpec `json:"autoscaling,omitempty"`
+       // Who manages the Deployment replica count. Operator (default) applies 
replicas or autoscaling.
+       // External hands it to an external controller such as a KEDA 
ScaledObject: the operator keeps the
+       // live replica count, creates no HorizontalPodAutoscaler, and ignores 
spec.replicas and spec.autoscaling.
+       // Overrides spec.scalingMode; set Operator to opt one component out of 
a top-level External.
+       // +optional
+       ScalingMode *ScalingMode `json:"scalingMode,omitempty"`
        // PodDisruptionBudget for protecting availability during voluntary 
disruptions. Overrides spec.podDisruptionBudget.
        // +optional
        PodDisruptionBudget *PDBSpec `json:"podDisruptionBudget,omitempty"`
diff --git a/api/v1alpha1/superset_types.go b/api/v1alpha1/superset_types.go
index da20979..b00db57 100644
--- a/api/v1alpha1/superset_types.go
+++ b/api/v1alpha1/superset_types.go
@@ -57,6 +57,12 @@ const (
 // +kubebuilder:validation:XValidation:rule="(has(self.environment) && 
self.environment == 'Development') || 
!has(self.previousSecretKey)",message="previousSecretKey is only allowed when 
environment is Development; use previousSecretKeyFrom in Staging or Production"
 // +kubebuilder:validation:XValidation:rule="!has(self.previousSecretKey) || 
!has(self.previousSecretKeyFrom)",message="previousSecretKey and 
previousSecretKeyFrom are mutually exclusive"
 // +kubebuilder:validation:XValidation:rule="!has(self.lifecycle) || 
!has(self.lifecycle.rotate) || (has(self.lifecycle.rotate.disabled) && 
self.lifecycle.rotate.disabled) || has(self.previousSecretKey) || 
has(self.previousSecretKeyFrom)",message="lifecycle.rotate requires 
previousSecretKey (dev) or previousSecretKeyFrom to be set"
+// +kubebuilder:validation:XValidation:rule="!has(self.scalingMode) || 
self.scalingMode != 'External' || (!has(self.replicas) && 
!has(self.autoscaling))",message="replicas and autoscaling cannot be set when 
scalingMode is External"
+// +kubebuilder:validation:XValidation:rule="!has(self.webServer) || 
(has(self.webServer.scalingMode) ? self.webServer.scalingMode : 
(has(self.scalingMode) ? self.scalingMode : 'Operator')) != 'External' || 
(!has(self.webServer.replicas) && 
!has(self.webServer.autoscaling))",message="webServer.replicas and 
webServer.autoscaling cannot be set when its effective scalingMode is External; 
set webServer.scalingMode: Operator to opt out of a top-level External"
+// +kubebuilder:validation:XValidation:rule="!has(self.celeryWorker) || 
(has(self.celeryWorker.scalingMode) ? self.celeryWorker.scalingMode : 
(has(self.scalingMode) ? self.scalingMode : 'Operator')) != 'External' || 
(!has(self.celeryWorker.replicas) && 
!has(self.celeryWorker.autoscaling))",message="celeryWorker.replicas and 
celeryWorker.autoscaling cannot be set when its effective scalingMode is 
External; set celeryWorker.scalingMode: Operator to opt out of a top-level 
External"
+// +kubebuilder:validation:XValidation:rule="!has(self.celeryFlower) || 
(has(self.celeryFlower.scalingMode) ? self.celeryFlower.scalingMode : 
(has(self.scalingMode) ? self.scalingMode : 'Operator')) != 'External' || 
(!has(self.celeryFlower.replicas) && 
!has(self.celeryFlower.autoscaling))",message="celeryFlower.replicas and 
celeryFlower.autoscaling cannot be set when its effective scalingMode is 
External; set celeryFlower.scalingMode: Operator to opt out of a top-level 
External"
+// +kubebuilder:validation:XValidation:rule="!has(self.websocketServer) || 
(has(self.websocketServer.scalingMode) ? self.websocketServer.scalingMode : 
(has(self.scalingMode) ? self.scalingMode : 'Operator')) != 'External' || 
(!has(self.websocketServer.replicas) && 
!has(self.websocketServer.autoscaling))",message="websocketServer.replicas and 
websocketServer.autoscaling cannot be set when its effective scalingMode is 
External; set websocketServer.scalingMode: Operator to opt out of a top- [...]
+// +kubebuilder:validation:XValidation:rule="!has(self.mcpServer) || 
(has(self.mcpServer.scalingMode) ? self.mcpServer.scalingMode : 
(has(self.scalingMode) ? self.scalingMode : 'Operator')) != 'External' || 
(!has(self.mcpServer.replicas) && 
!has(self.mcpServer.autoscaling))",message="mcpServer.replicas and 
mcpServer.autoscaling cannot be set when its effective scalingMode is External; 
set mcpServer.scalingMode: Operator to opt out of a top-level External"
 type SupersetSpec struct {
        // Image configuration inherited by all components.
        Image ImageSpec `json:"image"`
@@ -73,6 +79,10 @@ type SupersetSpec struct {
        // Default autoscaling for all scalable components (component-level 
overrides this).
        // +optional
        Autoscaling *AutoscalingSpec `json:"autoscaling,omitempty"`
+       // Default scaling mode for all scalable components (component-level 
overrides this).
+       // External leaves replica counts to an external controller such as 
KEDA; see the component field.
+       // +optional
+       ScalingMode *ScalingMode `json:"scalingMode,omitempty"`
        // Default pod disruption budget for all scalable components 
(component-level overrides this).
        // +optional
        PodDisruptionBudget *PDBSpec `json:"podDisruptionBudget,omitempty"`
diff --git a/api/v1alpha1/zz_generated.deepcopy.go 
b/api/v1alpha1/zz_generated.deepcopy.go
index 5171bc0..0f26989 100644
--- a/api/v1alpha1/zz_generated.deepcopy.go
+++ b/api/v1alpha1/zz_generated.deepcopy.go
@@ -1574,6 +1574,11 @@ func (in *ScalableComponentSpec) DeepCopyInto(out 
*ScalableComponentSpec) {
                *out = new(AutoscalingSpec)
                (*in).DeepCopyInto(*out)
        }
+       if in.ScalingMode != nil {
+               in, out := &in.ScalingMode, &out.ScalingMode
+               *out = new(ScalingMode)
+               **out = **in
+       }
        if in.PodDisruptionBudget != nil {
                in, out := &in.PodDisruptionBudget, &out.PodDisruptionBudget
                *out = new(PDBSpec)
@@ -1856,6 +1861,11 @@ func (in *SupersetSpec) DeepCopyInto(out *SupersetSpec) {
                *out = new(AutoscalingSpec)
                (*in).DeepCopyInto(*out)
        }
+       if in.ScalingMode != nil {
+               in, out := &in.ScalingMode, &out.ScalingMode
+               *out = new(ScalingMode)
+               **out = **in
+       }
        if in.PodDisruptionBudget != nil {
                in, out := &in.PodDisruptionBudget, &out.PodDisruptionBudget
                *out = new(PDBSpec)
diff --git a/charts/superset-operator/crds/superset.apache.org_supersets.yaml 
b/charts/superset-operator/crds/superset.apache.org_supersets.yaml
index eeb3f04..4068350 100644
--- a/charts/superset-operator/crds/superset.apache.org_supersets.yaml
+++ b/charts/superset-operator/crds/superset.apache.org_supersets.yaml
@@ -8087,6 +8087,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -12181,6 +12186,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   sqlaEngineOptions:
                     properties:
                       maxOverflow:
@@ -27655,6 +27665,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -31855,6 +31870,11 @@ spec:
               replicas:
                 format: int32
                 type: integer
+              scalingMode:
+                enum:
+                - Operator
+                - External
+                type: string
               secretKey:
                 type: string
               secretKeyFrom:
@@ -36186,6 +36206,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -40274,6 +40299,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -40390,6 +40420,43 @@ spec:
               rule: '!has(self.lifecycle) || !has(self.lifecycle.rotate) || 
(has(self.lifecycle.rotate.disabled)
                 && self.lifecycle.rotate.disabled) || 
has(self.previousSecretKey)
                 || has(self.previousSecretKeyFrom)'
+            - message: replicas and autoscaling cannot be set when scalingMode 
is
+                External
+              rule: '!has(self.scalingMode) || self.scalingMode != 
''External'' ||
+                (!has(self.replicas) && !has(self.autoscaling))'
+            - message: 'webServer.replicas and webServer.autoscaling cannot be 
set
+                when its effective scalingMode is External; set 
webServer.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.webServer) || (has(self.webServer.scalingMode) 
? self.webServer.scalingMode
+                : (has(self.scalingMode) ? self.scalingMode : ''Operator'')) 
!= ''External''
+                || (!has(self.webServer.replicas) && 
!has(self.webServer.autoscaling))'
+            - message: 'celeryWorker.replicas and celeryWorker.autoscaling 
cannot
+                be set when its effective scalingMode is External; set 
celeryWorker.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.celeryWorker) || 
(has(self.celeryWorker.scalingMode)
+                ? self.celeryWorker.scalingMode : (has(self.scalingMode) ? 
self.scalingMode
+                : ''Operator'')) != ''External'' || 
(!has(self.celeryWorker.replicas)
+                && !has(self.celeryWorker.autoscaling))'
+            - message: 'celeryFlower.replicas and celeryFlower.autoscaling 
cannot
+                be set when its effective scalingMode is External; set 
celeryFlower.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.celeryFlower) || 
(has(self.celeryFlower.scalingMode)
+                ? self.celeryFlower.scalingMode : (has(self.scalingMode) ? 
self.scalingMode
+                : ''Operator'')) != ''External'' || 
(!has(self.celeryFlower.replicas)
+                && !has(self.celeryFlower.autoscaling))'
+            - message: 'websocketServer.replicas and 
websocketServer.autoscaling cannot
+                be set when its effective scalingMode is External; set 
websocketServer.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.websocketServer) || 
(has(self.websocketServer.scalingMode)
+                ? self.websocketServer.scalingMode : (has(self.scalingMode) ? 
self.scalingMode
+                : ''Operator'')) != ''External'' || 
(!has(self.websocketServer.replicas)
+                && !has(self.websocketServer.autoscaling))'
+            - message: 'mcpServer.replicas and mcpServer.autoscaling cannot be 
set
+                when its effective scalingMode is External; set 
mcpServer.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.mcpServer) || (has(self.mcpServer.scalingMode) 
? self.mcpServer.scalingMode
+                : (has(self.scalingMode) ? self.scalingMode : ''Operator'')) 
!= ''External''
+                || (!has(self.mcpServer.replicas) && 
!has(self.mcpServer.autoscaling))'
           status:
             properties:
               components:
diff --git a/config/crd/bases/superset.apache.org_supersets.yaml 
b/config/crd/bases/superset.apache.org_supersets.yaml
index eeb3f04..4068350 100644
--- a/config/crd/bases/superset.apache.org_supersets.yaml
+++ b/config/crd/bases/superset.apache.org_supersets.yaml
@@ -8087,6 +8087,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -12181,6 +12186,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   sqlaEngineOptions:
                     properties:
                       maxOverflow:
@@ -27655,6 +27665,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -31855,6 +31870,11 @@ spec:
               replicas:
                 format: int32
                 type: integer
+              scalingMode:
+                enum:
+                - Operator
+                - External
+                type: string
               secretKey:
                 type: string
               secretKeyFrom:
@@ -36186,6 +36206,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -40274,6 +40299,11 @@ spec:
                   replicas:
                     format: int32
                     type: integer
+                  scalingMode:
+                    enum:
+                    - Operator
+                    - External
+                    type: string
                   service:
                     properties:
                       annotations:
@@ -40390,6 +40420,43 @@ spec:
               rule: '!has(self.lifecycle) || !has(self.lifecycle.rotate) || 
(has(self.lifecycle.rotate.disabled)
                 && self.lifecycle.rotate.disabled) || 
has(self.previousSecretKey)
                 || has(self.previousSecretKeyFrom)'
+            - message: replicas and autoscaling cannot be set when scalingMode 
is
+                External
+              rule: '!has(self.scalingMode) || self.scalingMode != 
''External'' ||
+                (!has(self.replicas) && !has(self.autoscaling))'
+            - message: 'webServer.replicas and webServer.autoscaling cannot be 
set
+                when its effective scalingMode is External; set 
webServer.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.webServer) || (has(self.webServer.scalingMode) 
? self.webServer.scalingMode
+                : (has(self.scalingMode) ? self.scalingMode : ''Operator'')) 
!= ''External''
+                || (!has(self.webServer.replicas) && 
!has(self.webServer.autoscaling))'
+            - message: 'celeryWorker.replicas and celeryWorker.autoscaling 
cannot
+                be set when its effective scalingMode is External; set 
celeryWorker.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.celeryWorker) || 
(has(self.celeryWorker.scalingMode)
+                ? self.celeryWorker.scalingMode : (has(self.scalingMode) ? 
self.scalingMode
+                : ''Operator'')) != ''External'' || 
(!has(self.celeryWorker.replicas)
+                && !has(self.celeryWorker.autoscaling))'
+            - message: 'celeryFlower.replicas and celeryFlower.autoscaling 
cannot
+                be set when its effective scalingMode is External; set 
celeryFlower.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.celeryFlower) || 
(has(self.celeryFlower.scalingMode)
+                ? self.celeryFlower.scalingMode : (has(self.scalingMode) ? 
self.scalingMode
+                : ''Operator'')) != ''External'' || 
(!has(self.celeryFlower.replicas)
+                && !has(self.celeryFlower.autoscaling))'
+            - message: 'websocketServer.replicas and 
websocketServer.autoscaling cannot
+                be set when its effective scalingMode is External; set 
websocketServer.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.websocketServer) || 
(has(self.websocketServer.scalingMode)
+                ? self.websocketServer.scalingMode : (has(self.scalingMode) ? 
self.scalingMode
+                : ''Operator'')) != ''External'' || 
(!has(self.websocketServer.replicas)
+                && !has(self.websocketServer.autoscaling))'
+            - message: 'mcpServer.replicas and mcpServer.autoscaling cannot be 
set
+                when its effective scalingMode is External; set 
mcpServer.scalingMode:
+                Operator to opt out of a top-level External'
+              rule: '!has(self.mcpServer) || (has(self.mcpServer.scalingMode) 
? self.mcpServer.scalingMode
+                : (has(self.scalingMode) ? self.scalingMode : ''Operator'')) 
!= ''External''
+                || (!has(self.mcpServer.replicas) && 
!has(self.mcpServer.autoscaling))'
           status:
             properties:
               components:
diff --git a/docs/architecture/internals.md b/docs/architecture/internals.md
index 2e0d131..c03b09c 100644
--- a/docs/architecture/internals.md
+++ b/docs/architecture/internals.md
@@ -89,7 +89,7 @@ During lifecycle and maintenance return, status still 
reflects observed componen
 
 The parent controller reconciles each component through table-driven component 
descriptors and shared resource helpers. This keeps per-component variation 
explicit while avoiding intermediate CRDs in the public API.
 
-**Scalable components** (WebServer, CeleryWorker, CeleryFlower, 
WebsocketServer, McpServer) manage a Deployment and support replicas, HPA, and 
PDB. Their specs embed `ScalableComponentSpec`, which has `DeploymentTemplate`, 
`PodTemplate`, and scaling fields.
+**Scalable components** (WebServer, CeleryWorker, CeleryFlower, 
WebsocketServer, McpServer) manage a Deployment and support replicas, HPA, 
external scaling (`scalingMode`), and PDB. Their specs embed 
`ScalableComponentSpec`, which has `DeploymentTemplate`, `PodTemplate`, and 
scaling fields.
 
 **Singleton components** (lifecycle tasks and CeleryBeat) run exactly one 
instance. Lifecycle tasks are Jobs with operator-managed retry logic (uses 
`PodTemplate` only). CeleryBeat uses a Deployment but forces `replicas: 1` (has 
both `DeploymentTemplate` and `PodTemplate` but no scaling fields).
 
@@ -150,7 +150,10 @@ type DeploymentConfig struct {
 
 1. `ForceReplicas` (beat singleton) — always wins
 2. `nil` if HPA is configured — HPA manages scaling
-3. `spec.Replicas` otherwise
+3. `nil` if the effective `scalingMode` is `External` — an external controller 
such as KEDA manages scaling
+4. `spec.Replicas` otherwise
+
+When replicas resolve to `nil`, the operator keeps the Deployment's live 
replica count on update instead of resetting it.
 
 ### Idempotent Reconciliation
 
diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md
index 308aeab..9cc144f 100644
--- a/docs/architecture/overview.md
+++ b/docs/architecture/overview.md
@@ -69,7 +69,7 @@ spec:
 
 Components fall into two runtime categories:
 
-**Scalable components** support replicas, HPA, and PodDisruptionBudgets:
+**Scalable components** support replicas, HPA, external scaling 
(`scalingMode`), and PodDisruptionBudgets:
 
 | Parent field | Suffix | Creates |
 |---|---|---|
@@ -100,7 +100,7 @@ podTemplate                            → PodSpec-level 
(affinity, tolerations,
 └── container                          → Container-level (resources, env, 
probes, ...)
 ```
 
-**Top-level `deploymentTemplate` and `podTemplate`** provide defaults 
inherited by all components. **Per-component** values are field-level merged 
with the top-level — only specify what's different. Scaling fields (`replicas`, 
`autoscaling`, `podDisruptionBudget`) are outside the templates since they 
interact with operator logic (HPA, Beat singleton).
+**Top-level `deploymentTemplate` and `podTemplate`** provide defaults 
inherited by all components. **Per-component** values are field-level merged 
with the top-level — only specify what's different. Scaling fields (`replicas`, 
`autoscaling`, `scalingMode`, `podDisruptionBudget`) are outside the templates 
since they interact with operator logic (HPA, Beat singleton).
 
 Merge semantics per field type:
 
diff --git a/docs/reference/api-reference.md b/docs/reference/api-reference.md
index 8ca1d44..ee6dcf1 100644
--- a/docs/reference/api-reference.md
+++ b/docs/reference/api-reference.md
@@ -123,6 +123,7 @@ _Appears in:_
 | `podTemplate` _[PodTemplate](#podtemplate)_ | Pod template (Pod and 
container configuration). |  | Optional: \{\} <br /> |
 | `replicas` _integer_ | Desired replica count; overridden by autoscaling when 
active. Defaults to spec.replicas if unset. |  | Optional: \{\} <br /> |
 | `autoscaling` _[AutoscalingSpec](#autoscalingspec)_ | 
HorizontalPodAutoscaler configuration. When set, the HPA manages replica count. 
Overrides spec.autoscaling. |  | Optional: \{\} <br /> |
+| `scalingMode` _[ScalingMode](#scalingmode)_ | Who manages the Deployment 
replica count. Operator (default) applies replicas or autoscaling. External 
hands it to an external controller such as a KEDA ScaledObject: the operator 
keeps the live replica count, creates no HorizontalPodAutoscaler, and ignores 
spec.replicas and spec.autoscaling. Overrides spec.scalingMode; set Operator to 
opt one component out of a top-level External. |  | Enum: [Operator External] 
<br />Optional: \{\} <br /> |
 | `podDisruptionBudget` _[PDBSpec](#pdbspec)_ | PodDisruptionBudget for 
protecting availability during voluntary disruptions. Overrides 
spec.podDisruptionBudget. |  | Optional: \{\} <br /> |
 | `image` _[ImageOverrideSpec](#imageoverridespec)_ | Image tag and/or 
repository overrides; inherits from spec.image if unset. |  | Optional: \{\} 
<br /> |
 | `config` _string_ | Per-component raw Python appended after top-level 
config. |  | Optional: \{\} <br /> |
@@ -147,6 +148,7 @@ _Appears in:_
 | `podTemplate` _[PodTemplate](#podtemplate)_ | Pod template (Pod and 
container configuration). |  | Optional: \{\} <br /> |
 | `replicas` _integer_ | Desired replica count; overridden by autoscaling when 
active. Defaults to spec.replicas if unset. |  | Optional: \{\} <br /> |
 | `autoscaling` _[AutoscalingSpec](#autoscalingspec)_ | 
HorizontalPodAutoscaler configuration. When set, the HPA manages replica count. 
Overrides spec.autoscaling. |  | Optional: \{\} <br /> |
+| `scalingMode` _[ScalingMode](#scalingmode)_ | Who manages the Deployment 
replica count. Operator (default) applies replicas or autoscaling. External 
hands it to an external controller such as a KEDA ScaledObject: the operator 
keeps the live replica count, creates no HorizontalPodAutoscaler, and ignores 
spec.replicas and spec.autoscaling. Overrides spec.scalingMode; set Operator to 
opt one component out of a top-level External. |  | Enum: [Operator External] 
<br />Optional: \{\} <br /> |
 | `podDisruptionBudget` _[PDBSpec](#pdbspec)_ | PodDisruptionBudget for 
protecting availability during voluntary disruptions. Overrides 
spec.podDisruptionBudget. |  | Optional: \{\} <br /> |
 | `image` _[ImageOverrideSpec](#imageoverridespec)_ | Image tag and/or 
repository overrides; inherits from spec.image if unset. |  | Optional: \{\} 
<br /> |
 | `config` _string_ | Per-component raw Python appended after top-level 
config. |  | Optional: \{\} <br /> |
@@ -742,6 +744,7 @@ _Appears in:_
 | `podTemplate` _[PodTemplate](#podtemplate)_ | Pod template (Pod and 
container configuration). |  | Optional: \{\} <br /> |
 | `replicas` _integer_ | Desired replica count; overridden by autoscaling when 
active. Defaults to spec.replicas if unset. |  | Optional: \{\} <br /> |
 | `autoscaling` _[AutoscalingSpec](#autoscalingspec)_ | 
HorizontalPodAutoscaler configuration. When set, the HPA manages replica count. 
Overrides spec.autoscaling. |  | Optional: \{\} <br /> |
+| `scalingMode` _[ScalingMode](#scalingmode)_ | Who manages the Deployment 
replica count. Operator (default) applies replicas or autoscaling. External 
hands it to an external controller such as a KEDA ScaledObject: the operator 
keeps the live replica count, creates no HorizontalPodAutoscaler, and ignores 
spec.replicas and spec.autoscaling. Overrides spec.scalingMode; set Operator to 
opt one component out of a top-level External. |  | Enum: [Operator External] 
<br />Optional: \{\} <br /> |
 | `podDisruptionBudget` _[PDBSpec](#pdbspec)_ | PodDisruptionBudget for 
protecting availability during voluntary disruptions. Overrides 
spec.podDisruptionBudget. |  | Optional: \{\} <br /> |
 | `image` _[ImageOverrideSpec](#imageoverridespec)_ | Image tag and/or 
repository overrides; inherits from spec.image if unset. |  | Optional: \{\} 
<br /> |
 | `config` _string_ | Per-component raw Python appended after top-level 
config. |  | Optional: \{\} <br /> |
@@ -1057,9 +1060,34 @@ _Appears in:_
 | `podTemplate` _[PodTemplate](#podtemplate)_ | Pod template (Pod and 
container configuration). |  | Optional: \{\} <br /> |
 | `replicas` _integer_ | Desired replica count; overridden by autoscaling when 
active. Defaults to spec.replicas if unset. |  | Optional: \{\} <br /> |
 | `autoscaling` _[AutoscalingSpec](#autoscalingspec)_ | 
HorizontalPodAutoscaler configuration. When set, the HPA manages replica count. 
Overrides spec.autoscaling. |  | Optional: \{\} <br /> |
+| `scalingMode` _[ScalingMode](#scalingmode)_ | Who manages the Deployment 
replica count. Operator (default) applies replicas or autoscaling. External 
hands it to an external controller such as a KEDA ScaledObject: the operator 
keeps the live replica count, creates no HorizontalPodAutoscaler, and ignores 
spec.replicas and spec.autoscaling. Overrides spec.scalingMode; set Operator to 
opt one component out of a top-level External. |  | Enum: [Operator External] 
<br />Optional: \{\} <br /> |
 | `podDisruptionBudget` _[PDBSpec](#pdbspec)_ | PodDisruptionBudget for 
protecting availability during voluntary disruptions. Overrides 
spec.podDisruptionBudget. |  | Optional: \{\} <br /> |
 
 
+#### ScalingMode
+
+_Underlying type:_ _string_
+
+ScalingMode selects who manages a component Deployment's replica count.
+
+_Validation:_
+- Enum: [Operator External]
+
+_Appears in:_
+- [CeleryFlowerComponentSpec](#celeryflowercomponentspec)
+- [CeleryWorkerComponentSpec](#celeryworkercomponentspec)
+- [McpServerComponentSpec](#mcpservercomponentspec)
+- [ScalableComponentSpec](#scalablecomponentspec)
+- [SupersetSpec](#supersetspec)
+- [WebServerComponentSpec](#webservercomponentspec)
+- [WebsocketServerComponentSpec](#websocketservercomponentspec)
+
+| Field | Description |
+| --- | --- |
+| `Operator` | ScalingModeOperator sets the replica count from replicas or 
autoscaling. |
+| `External` | ScalingModeExternal leaves the replica count to an external 
controller, such as a KEDA ScaledObject or a user-managed 
HorizontalPodAutoscaler. |
+
+
 #### SchedulableBaseTaskSpec
 
 
@@ -1239,6 +1267,7 @@ _Appears in:_
 | `podTemplate` _[PodTemplate](#podtemplate)_ | Pod template defaults 
inherited by all components (field-level merge). |  | Optional: \{\} <br /> |
 | `replicas` _integer_ | Default replica count for all scalable components; 
per-component replicas override this. |  | Optional: \{\} <br /> |
 | `autoscaling` _[AutoscalingSpec](#autoscalingspec)_ | Default autoscaling 
for all scalable components (component-level overrides this). |  | Optional: 
\{\} <br /> |
+| `scalingMode` _[ScalingMode](#scalingmode)_ | Default scaling mode for all 
scalable components (component-level overrides this). External leaves replica 
counts to an external controller such as KEDA; see the component field. |  | 
Enum: [Operator External] <br />Optional: \{\} <br /> |
 | `podDisruptionBudget` _[PDBSpec](#pdbspec)_ | Default pod disruption budget 
for all scalable components (component-level overrides this). |  | Optional: 
\{\} <br /> |
 | `environment` _[Environment](#environment)_ | Environment mode: 
"Development", "Staging", or "Production". Controls validation strictness. In 
Production mode, CRD validation rejects plain text secrets and disallows 
seeding. In Staging mode, secrets are enforced (like Production) but seeding is 
allowed. In Development mode, plain text secrets, seeding, admin user, and load 
examples are all permitted. | Production | Enum: [Development Staging 
Production] <br />Optional: \{\} <br /> |
 | `secretKey` _string_ | Plain text secret key for session signing. Only 
allowed in Development mode. In Staging or Production, use secretKeyFrom to 
reference a Kubernetes Secret. |  | Optional: \{\} <br /> |
@@ -1500,6 +1529,7 @@ _Appears in:_
 | `podTemplate` _[PodTemplate](#podtemplate)_ | Pod template (Pod and 
container configuration). |  | Optional: \{\} <br /> |
 | `replicas` _integer_ | Desired replica count; overridden by autoscaling when 
active. Defaults to spec.replicas if unset. |  | Optional: \{\} <br /> |
 | `autoscaling` _[AutoscalingSpec](#autoscalingspec)_ | 
HorizontalPodAutoscaler configuration. When set, the HPA manages replica count. 
Overrides spec.autoscaling. |  | Optional: \{\} <br /> |
+| `scalingMode` _[ScalingMode](#scalingmode)_ | Who manages the Deployment 
replica count. Operator (default) applies replicas or autoscaling. External 
hands it to an external controller such as a KEDA ScaledObject: the operator 
keeps the live replica count, creates no HorizontalPodAutoscaler, and ignores 
spec.replicas and spec.autoscaling. Overrides spec.scalingMode; set Operator to 
opt one component out of a top-level External. |  | Enum: [Operator External] 
<br />Optional: \{\} <br /> |
 | `podDisruptionBudget` _[PDBSpec](#pdbspec)_ | PodDisruptionBudget for 
protecting availability during voluntary disruptions. Overrides 
spec.podDisruptionBudget. |  | Optional: \{\} <br /> |
 | `image` _[ImageOverrideSpec](#imageoverridespec)_ | Image tag and/or 
repository overrides; inherits from spec.image if unset. |  | Optional: \{\} 
<br /> |
 | `config` _string_ | Per-component raw Python appended after top-level 
config. |  | Optional: \{\} <br /> |
@@ -1532,6 +1562,7 @@ _Appears in:_
 | `podTemplate` _[PodTemplate](#podtemplate)_ | Pod template (Pod and 
container configuration). |  | Optional: \{\} <br /> |
 | `replicas` _integer_ | Desired replica count; overridden by autoscaling when 
active. Defaults to spec.replicas if unset. |  | Optional: \{\} <br /> |
 | `autoscaling` _[AutoscalingSpec](#autoscalingspec)_ | 
HorizontalPodAutoscaler configuration. When set, the HPA manages replica count. 
Overrides spec.autoscaling. |  | Optional: \{\} <br /> |
+| `scalingMode` _[ScalingMode](#scalingmode)_ | Who manages the Deployment 
replica count. Operator (default) applies replicas or autoscaling. External 
hands it to an external controller such as a KEDA ScaledObject: the operator 
keeps the live replica count, creates no HorizontalPodAutoscaler, and ignores 
spec.replicas and spec.autoscaling. Overrides spec.scalingMode; set Operator to 
opt one component out of a top-level External. |  | Enum: [Operator External] 
<br />Optional: \{\} <br /> |
 | `podDisruptionBudget` _[PDBSpec](#pdbspec)_ | PodDisruptionBudget for 
protecting availability during voluntary disruptions. Overrides 
spec.podDisruptionBudget. |  | Optional: \{\} <br /> |
 | `image` _[ImageOverrideSpec](#imageoverridespec)_ | Image tag and/or 
repository overrides; inherits from spec.image if unset. |  | Optional: \{\} 
<br /> |
 | `config` 
_[JSON](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.31/#json-v1-apiextensions-k8s-io)_
 | Inline config.json content for the websocket server. Only allowed in 
Development mode because this config commonly contains jwtSecret or Redis 
credentials. In Production, use configFrom to mount an existing Secret key. |  
| Type: object <br />Optional: \{\} <br /> |
diff --git a/docs/reference/releases.md b/docs/reference/releases.md
index 874cb78..a004b7d 100644
--- a/docs/reference/releases.md
+++ b/docs/reference/releases.md
@@ -30,6 +30,7 @@ This page tracks notable changes in Apache Superset 
Kubernetes Operator releases
 - **Removing default probes.** Setting `livenessProbe`, `readinessProbe`, or 
`startupProbe` to `{}` now removes the operator's default probe. It works on 
every component and follows the usual top-level and per-component override 
rules ([#427](https://github.com/apache/superset-kubernetes-operator/pull/427), 
[@younsl](https://github.com/younsl)).
 - **Helm `extraEnv`.** The Helm chart now exposes an `extraEnv` value that 
appends environment variables to the operator manager container, for example a 
`GOMEMLIMIT` derived from the memory limit. `WATCH_NAMESPACE` is rejected 
because the `watch` block owns it 
([#426](https://github.com/apache/superset-kubernetes-operator/pull/426), 
[@younsl](https://github.com/younsl)).
 - **`sup` short name.** The `Superset` resource now has the short name `sup`, 
so `kubectl get sup` works the same as `kubectl get superset` 
([#480](https://github.com/apache/superset-kubernetes-operator/pull/480), 
[@younsl](https://github.com/younsl)).
+- **External scaling.** A new `scalingMode` field hands a component's replica 
count to an external controller, such as a [KEDA](https://keda.sh) 
`ScaledObject` that scales Celery workers on broker queue depth. With 
`scalingMode: External`, the operator keeps the Deployment's live replica count 
and creates no HPA for the component. Set it at the top level for every 
scalable component or per component; a component's `scalingMode: Operator` opts 
it out of a top-level `External`. `replicas`  [...]
 
 ### Changed
 
diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md
index 5cda2a6..1336d96 100644
--- a/docs/user-guide/configuration.md
+++ b/docs/user-guide/configuration.md
@@ -877,6 +877,73 @@ spec:
 
 When HPA is configured, the `replicas` field is ignored (HPA manages scaling).
 
+### External scaling
+
+Set `scalingMode: External` to let another controller own the replica count, 
for example a [KEDA](https://keda.sh) `ScaledObject` that scales Celery workers 
on broker queue depth. The operator then keeps the Deployment's live replica 
count, creates no HPA for the component (removing one it created earlier), and 
ignores the inherited `spec.replicas` and `spec.autoscaling`. A newly created 
Deployment starts at one replica, and the external controller scales it from 
there.
+
+Like `replicas` and `autoscaling`, `scalingMode` can be set on a component or 
once at the top level for every scalable component. A component's own value 
overrides the top-level one, so `scalingMode: Operator` opts one component out 
of a top-level `External`. `replicas` and `autoscaling` cannot be set where the 
effective mode is `External`:
+
+```yaml
+spec:
+  # Only the Celery workers are scaled externally.
+  celeryWorker:
+    scalingMode: External
+```
+
+```yaml
+spec:
+  # Every scalable component is scaled externally, except the web server.
+  scalingMode: External
+  webServer:
+    scalingMode: Operator
+    replicas: 2
+```
+
+A matching KEDA `ScaledObject` targets the component's Deployment by name. Its 
`TriggerAuthentication` reads the Valkey password from the same Secret key as 
`valkey.passwordFrom`:
+
+```yaml
+apiVersion: keda.sh/v1alpha1
+kind: TriggerAuthentication
+metadata:
+  name: superset-valkey
+spec:
+  secretTargetRef:
+    - parameter: password
+      name: superset-valkey  # same Secret and key as valkey.passwordFrom
+      key: password
+---
+apiVersion: keda.sh/v1alpha1
+kind: ScaledObject
+metadata:
+  name: superset-celery-worker
+spec:
+  scaleTargetRef:
+    name: superset-celery-worker  # <superset name>-celery-worker
+  minReplicaCount: 1
+  maxReplicaCount: 10
+  triggers:
+    - type: redis
+      metadata:
+        address: valkey.example.com:6379  # valkey.host and valkey.port
+        databaseIndex: "0"                # valkey.celeryBroker.database
+        enableTLS: "true"                 # only when valkey.ssl is set
+        listName: celery                  # default Celery queue
+        listLength: "4"
+      authenticationRef:
+        name: superset-valkey
+```
+
+KEDA's `minReplicaCount` defaults to 0. Celery workers can scale to zero 
because new tasks reactivate the queue trigger, but keep it at 1 or more for 
the web server, websocket server, Flower, and MCP server: incoming requests 
don't activate a queue trigger, so a component scaled to zero stays 
unavailable. A queue-length trigger counts only waiting tasks, so scaling in 
can stop a worker in the middle of a task. Size 
`celeryWorker.podTemplate.terminationGracePeriodSeconds` for your longest [...]
+
+#### Switching modes
+
+Let only one controller own the replica count at a time:
+
+- **To `External`:** set `scalingMode: External` first, and create the 
`ScaledObject` once the operator has removed its HPA. KEDA's admission webhook 
rejects a `ScaledObject` for a Deployment that another HPA already manages.
+- **Back to `Operator`:** delete the `ScaledObject` first, then remove 
`scalingMode: External` and set `replicas` or `autoscaling` in the same change. 
While the `ScaledObject` exists, KEDA and the operator would both set the 
replica count, and without `replicas` or `autoscaling` the Deployment drops to 
one replica. Deleting the `ScaledObject` leaves the replica count where KEDA 
last set it, unless `advanced.restoreToOriginalReplicaCount` is set.
+
+A lifecycle drain deletes component Deployments. When they are recreated they 
start at one replica, and for an externally scaled web server the maintenance 
page ends as soon as that pod is ready, so traffic briefly reaches a single 
web-server pod until the external controller scales it up.
+
 ## Pod Disruption Budget
 
 ```yaml
diff --git a/internal/controller/cel_validation_test.go 
b/internal/controller/cel_validation_test.go
index c33a21a..5be544c 100644
--- a/internal/controller/cel_validation_test.go
+++ b/internal/controller/cel_validation_test.go
@@ -405,6 +405,64 @@ var _ = Describe("CEL Validation", Ordered, func() {
                        Expect(err).To(HaveOccurred())
                        Expect(err.Error()).To(ContainSubstring("mutually 
exclusive"))
                })
+
+               DescribeTable("rejects replicas or autoscaling when the 
effective scalingMode is External",
+                       func(name, message string, mutate 
func(*supersetv1alpha1.SupersetSpec)) {
+                               cr := validDevSuperset(name)
+                               mutate(&cr.Spec)
+                               err := k8sClient.Create(ctx, cr)
+                               Expect(err).To(HaveOccurred())
+                               
Expect(err.Error()).To(ContainSubstring(message))
+                       },
+                       Entry("top-level replicas", "external-tl-replicas", 
"replicas and autoscaling cannot be set when scalingMode is External",
+                               func(s *supersetv1alpha1.SupersetSpec) {
+                                       s.ScalingMode = 
new(supersetv1alpha1.ScalingModeExternal)
+                                       s.Replicas = new(int32(2))
+                               }),
+                       Entry("top-level autoscaling", 
"external-tl-autoscaling", "replicas and autoscaling cannot be set when 
scalingMode is External",
+                               func(s *supersetv1alpha1.SupersetSpec) {
+                                       s.ScalingMode = 
new(supersetv1alpha1.ScalingModeExternal)
+                                       s.Autoscaling = 
&supersetv1alpha1.AutoscalingSpec{MaxReplicas: 4}
+                               }),
+                       Entry("component replicas", "external-replicas", 
"celeryWorker.replicas and celeryWorker.autoscaling cannot be set",
+                               func(s *supersetv1alpha1.SupersetSpec) {
+                                       s.CeleryWorker = 
&supersetv1alpha1.CeleryWorkerComponentSpec{
+                                               ScalingMode: 
new(supersetv1alpha1.ScalingModeExternal),
+                                               Replicas:    new(int32(2)),
+                                       }
+                               }),
+                       Entry("component autoscaling", "external-autoscaling", 
"celeryWorker.replicas and celeryWorker.autoscaling cannot be set",
+                               func(s *supersetv1alpha1.SupersetSpec) {
+                                       s.CeleryWorker = 
&supersetv1alpha1.CeleryWorkerComponentSpec{
+                                               ScalingMode: 
new(supersetv1alpha1.ScalingModeExternal),
+                                               Autoscaling: 
&supersetv1alpha1.AutoscalingSpec{MaxReplicas: 4},
+                                       }
+                               }),
+                       Entry("component replicas under an inherited External", 
"external-inherited-replicas", "set webServer.scalingMode: Operator",
+                               func(s *supersetv1alpha1.SupersetSpec) {
+                                       s.ScalingMode = 
new(supersetv1alpha1.ScalingModeExternal)
+                                       s.WebServer = 
&supersetv1alpha1.WebServerComponentSpec{Replicas: new(int32(3))}
+                               }),
+               )
+
+               It("accepts a component opting out of a top-level External", 
func() {
+                       cr := validDevSuperset("external-opt-out")
+                       cr.Spec.ScalingMode = 
new(supersetv1alpha1.ScalingModeExternal)
+                       cr.Spec.WebServer = 
&supersetv1alpha1.WebServerComponentSpec{
+                               ScalingMode: 
new(supersetv1alpha1.ScalingModeOperator),
+                               Replicas:    new(int32(3)),
+                       }
+                       Expect(k8sClient.Create(ctx, cr)).To(Succeed())
+               })
+
+               It("accepts scalingMode External alongside top-level 
autoscaling", func() {
+                       cr := validDevSuperset("external-top-level-hpa")
+                       cr.Spec.Autoscaling = 
&supersetv1alpha1.AutoscalingSpec{MaxReplicas: 5}
+                       cr.Spec.CeleryWorker = 
&supersetv1alpha1.CeleryWorkerComponentSpec{
+                               ScalingMode: 
new(supersetv1alpha1.ScalingModeExternal),
+                       }
+                       Expect(k8sClient.Create(ctx, cr)).To(Succeed())
+               })
        })
 
        // --- Networking / Monitoring component requirements ---
diff --git a/internal/controller/component_descriptors.go 
b/internal/controller/component_descriptors.go
index 31e3579..8e81a06 100644
--- a/internal/controller/component_descriptors.go
+++ b/internal/controller/component_descriptors.go
@@ -39,6 +39,7 @@ type componentAccessor struct {
        podTemplate         *supersetv1alpha1.PodTemplate
        replicas            *int32
        autoscaling         *supersetv1alpha1.AutoscalingSpec
+       scalingMode         *supersetv1alpha1.ScalingMode
        pdb                 *supersetv1alpha1.PDBSpec
        config              *string
        bootstrapScript     *string
@@ -96,6 +97,7 @@ func convertComponent(a *componentAccessor) 
*resolution.ComponentInput {
                PodTemplate:         a.podTemplate,
                Autoscaling:         a.autoscaling,
                PodDisruptionBudget: a.pdb,
+               ScalingMode:         a.scalingMode,
        }
 }
 
@@ -366,6 +368,7 @@ func extractScalable(s 
*supersetv1alpha1.ScalableComponentSpec, config, bootstra
                podTemplate:        s.PodTemplate,
                replicas:           s.Replicas,
                autoscaling:        s.Autoscaling,
+               scalingMode:        s.ScalingMode,
                pdb:                s.PodDisruptionBudget,
                config:             config,
                bootstrapScript:    bootstrapScript,
diff --git a/internal/controller/config_builder.go 
b/internal/controller/config_builder.go
index f11f239..ff6eb56 100644
--- a/internal/controller/config_builder.go
+++ b/internal/controller/config_builder.go
@@ -36,6 +36,7 @@ func convertTopLevelSpec(spec *supersetv1alpha1.SupersetSpec) 
*resolution.Shared
                PodTemplate:         spec.PodTemplate,
                Autoscaling:         spec.Autoscaling,
                PodDisruptionBudget: spec.PodDisruptionBudget,
+               ScalingMode:         spec.ScalingMode,
        }
 }
 
@@ -409,7 +410,12 @@ func buildOperatorInjected(renderedConfig, 
bootstrapScript, resourceBaseName, fo
 // When imageOverride is non-nil, its Tag and/or Repository override the 
parent image.
 // saName is set on the FlatComponentSpec so it propagates to Deployment pods.
 func flatSpecFromResolution(flat *resolution.FlatSpec, parentImage 
*supersetv1alpha1.ImageSpec, imageOverride *supersetv1alpha1.ImageOverrideSpec, 
saName string) supersetv1alpha1.FlatComponentSpec {
-       replicas := flat.Replicas
+       // Nil replicas leave Deployment.spec.replicas to the external 
controller.
+       var replicas *int32
+       if !flat.ExternalScaling {
+               r := flat.Replicas
+               replicas = &r
+       }
        image := *parentImage
        if imageOverride != nil {
                if imageOverride.Tag != nil {
@@ -424,7 +430,7 @@ func flatSpecFromResolution(flat *resolution.FlatSpec, 
parentImage *supersetv1al
        }
        return supersetv1alpha1.FlatComponentSpec{
                Image:               image,
-               Replicas:            &replicas,
+               Replicas:            replicas,
                DeploymentTemplate:  flat.DeploymentTemplate,
                PodTemplate:         flat.PodTemplate,
                ServiceAccountName:  saName,
diff --git a/internal/controller/reconcile_parent_resources_test.go 
b/internal/controller/reconcile_parent_resources_test.go
index d0bec1b..d589e07 100644
--- a/internal/controller/reconcile_parent_resources_test.go
+++ b/internal/controller/reconcile_parent_resources_test.go
@@ -24,6 +24,7 @@ import (
        "testing"
 
        appsv1 "k8s.io/api/apps/v1"
+       autoscalingv2 "k8s.io/api/autoscaling/v2"
        batchv1 "k8s.io/api/batch/v1"
        corev1 "k8s.io/api/core/v1"
        apiextensionsv1 
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
@@ -132,6 +133,57 @@ func TestReconcile_CreatesParentOwnedComponentResources(t 
*testing.T) {
        }
 }
 
+func TestReconcile_ExternalScalingLeavesReplicasToExternalController(t 
*testing.T) {
+       scheme := testScheme(t)
+
+       spec := minimalSupersetSpec()
+       // Inherited by every component; the externally scaled worker must 
ignore it.
+       spec.Autoscaling = &supersetv1alpha1.AutoscalingSpec{MaxReplicas: 10}
+       spec.CeleryWorker = &supersetv1alpha1.CeleryWorkerComponentSpec{
+               ScalingMode: new(supersetv1alpha1.ScalingModeExternal),
+       }
+       // Created fresh by this reconcile, so it covers the create path.
+       spec.CeleryFlower = &supersetv1alpha1.CeleryFlowerComponentSpec{
+               ScalingMode: new(supersetv1alpha1.ScalingModeExternal),
+       }
+       superset := &supersetv1alpha1.Superset{Name: "test", Namespace: 
"default", UID: "uid-1", Spec: spec}
+
+       // An external controller (e.g. KEDA) has scaled the worker to 7, and 
the
+       // operator's HPA from before the switch to External is still present.
+       workerDeploy := &appsv1.Deployment{
+               Name: "test-celery-worker", Namespace: "default",
+               Spec: appsv1.DeploymentSpec{Replicas: new(int32(7))},
+       }
+       workerHPA := &autoscalingv2.HorizontalPodAutoscaler{Name: 
"test-celery-worker", Namespace: "default", OwnerReferences: 
controllerRefTo(superset)}
+
+       c := reconcileOnce(t, scheme, superset).WithObjects(workerDeploy, 
workerHPA).Build()
+       r := &SupersetReconciler{Client: c, Scheme: scheme, Recorder: 
events.NewFakeRecorder(10)}
+       doReconcile(t, r)
+
+       deploy := &appsv1.Deployment{}
+       if err := c.Get(context.Background(), types.NamespacedName{Name: 
"test-celery-worker", Namespace: "default"}, deploy); err != nil {
+               t.Fatalf("expected worker Deployment: %v", err)
+       }
+       if deploy.Spec.Replicas == nil {
+               t.Error("worker replicas = nil, want the externally set 7")
+       } else if *deploy.Spec.Replicas != 7 {
+               t.Errorf("worker replicas = %d, want the externally set 7", 
*deploy.Spec.Replicas)
+       }
+       if err := c.Get(context.Background(), types.NamespacedName{Name: 
"test-celery-worker", Namespace: "default"}, 
&autoscalingv2.HorizontalPodAutoscaler{}); err == nil {
+               t.Error("expected the operator HPA for the externally scaled 
worker to be deleted")
+       }
+       flower := &appsv1.Deployment{}
+       if err := c.Get(context.Background(), types.NamespacedName{Name: 
"test-celery-flower", Namespace: "default"}, flower); err != nil {
+               t.Fatalf("expected flower Deployment: %v", err)
+       }
+       if flower.Spec.Replicas != nil {
+               t.Errorf("new flower replicas = %d, want unset so the external 
controller owns them", *flower.Spec.Replicas)
+       }
+       if err := c.Get(context.Background(), types.NamespacedName{Name: 
"test-web-server", Namespace: "default"}, 
&autoscalingv2.HorizontalPodAutoscaler{}); err != nil {
+               t.Errorf("expected inherited autoscaling to still create the 
web-server HPA: %v", err)
+       }
+}
+
 func TestReconcile_DisabledComponentDeletesParentOwnedResources(t *testing.T) {
        scheme := testScheme(t)
 
diff --git a/internal/controller/status.go b/internal/controller/status.go
index bc1bbea..138115c 100644
--- a/internal/controller/status.go
+++ b/internal/controller/status.go
@@ -34,6 +34,7 @@ import (
 
        supersetv1alpha1 
"github.com/apache/superset-kubernetes-operator/api/v1alpha1"
        naming "github.com/apache/superset-kubernetes-operator/internal/common"
+       "github.com/apache/superset-kubernetes-operator/internal/resolution"
 )
 
 const (
@@ -365,7 +366,18 @@ func componentHasService(desc *componentDescriptor, cfg 
componentReconcilerConfi
        return cfg.defaultPort > 0 || desc.componentType == 
naming.ComponentWebServer
 }
 
+func effectiveScalingModeForStatus(superset *supersetv1alpha1.Superset, 
accessor *componentAccessor) *supersetv1alpha1.ScalingMode {
+       var component *supersetv1alpha1.ScalingMode
+       if accessor != nil {
+               component = accessor.scalingMode
+       }
+       return resolution.ResolveOverridableValue(component, 
superset.Spec.ScalingMode)
+}
+
 func effectiveAutoscalingForStatus(superset *supersetv1alpha1.Superset, 
accessor *componentAccessor) *supersetv1alpha1.AutoscalingSpec {
+       if effectiveScalingModeForStatus(superset, accessor).IsExternal() {
+               return nil
+       }
        if accessor != nil && accessor.autoscaling != nil {
                return accessor.autoscaling
        }
@@ -383,6 +395,11 @@ func desiredReplicasForStatus(superset 
*supersetv1alpha1.Superset, desc *compone
        if desc.componentType == naming.ComponentCeleryBeat {
                return celeryBeatSingletonReplica
        }
+       // A new Deployment without replicas starts at one; the external
+       // controller scales it from there.
+       if effectiveScalingModeForStatus(superset, accessor).IsExternal() {
+               return 1
+       }
        if autoscaling := effectiveAutoscalingForStatus(superset, accessor); 
autoscaling != nil {
                if autoscaling.MinReplicas != nil {
                        return *autoscaling.MinReplicas
diff --git a/internal/controller/status_test.go 
b/internal/controller/status_test.go
index f8393d5..3fafbd5 100644
--- a/internal/controller/status_test.go
+++ b/internal/controller/status_test.go
@@ -430,6 +430,19 @@ func TestEffectiveAutoscalingForStatus(t *testing.T) {
        t.Run("nil when neither set", func(t *testing.T) {
                assert.Nil(t, 
effectiveAutoscalingForStatus(&supersetv1alpha1.Superset{}, nil))
        })
+
+       t.Run("nil when externally scaled, ignoring top-level", func(t 
*testing.T) {
+               superset := &supersetv1alpha1.Superset{Spec: 
supersetv1alpha1.SupersetSpec{Autoscaling: topAS}}
+               accessor := &componentAccessor{scalingMode: 
new(supersetv1alpha1.ScalingModeExternal)}
+               assert.Nil(t, effectiveAutoscalingForStatus(superset, accessor))
+       })
+
+       t.Run("top-level External is inherited unless the component opts out", 
func(t *testing.T) {
+               superset := &supersetv1alpha1.Superset{Spec: 
supersetv1alpha1.SupersetSpec{ScalingMode: 
new(supersetv1alpha1.ScalingModeExternal)}}
+               assert.Nil(t, effectiveAutoscalingForStatus(superset, 
&componentAccessor{}))
+               optOut := &componentAccessor{scalingMode: 
new(supersetv1alpha1.ScalingModeOperator), autoscaling: componentAS}
+               assert.Same(t, componentAS, 
effectiveAutoscalingForStatus(superset, optOut))
+       })
 }
 
 func TestEffectivePDBForStatus(t *testing.T) {
@@ -485,6 +498,20 @@ func TestDesiredReplicasForStatus(t *testing.T) {
        t.Run("defaults to 1 when nothing is set", func(t *testing.T) {
                assert.Equal(t, int32(1), 
desiredReplicasForStatus(&supersetv1alpha1.Superset{}, webDesc, 
&componentAccessor{}))
        })
+
+       t.Run("externally scaled starts at 1, ignoring top-level replicas and 
autoscaling", func(t *testing.T) {
+               superset := &supersetv1alpha1.Superset{Spec: 
supersetv1alpha1.SupersetSpec{
+                       Replicas:    new(int32(5)),
+                       Autoscaling: 
&supersetv1alpha1.AutoscalingSpec{MinReplicas: new(int32(3))},
+               }}
+               accessor := &componentAccessor{scalingMode: 
new(supersetv1alpha1.ScalingModeExternal)}
+               assert.Equal(t, int32(1), desiredReplicasForStatus(superset, 
webDesc, accessor))
+       })
+
+       t.Run("inherited top-level External starts at 1", func(t *testing.T) {
+               superset := &supersetv1alpha1.Superset{Spec: 
supersetv1alpha1.SupersetSpec{ScalingMode: 
new(supersetv1alpha1.ScalingModeExternal)}}
+               assert.Equal(t, int32(1), desiredReplicasForStatus(superset, 
webDesc, &componentAccessor{}))
+       })
 }
 
 func TestComponentPhaseAndMessage(t *testing.T) {
diff --git a/internal/resolution/resolver.go b/internal/resolution/resolver.go
index 424e96b..d70e93f 100644
--- a/internal/resolution/resolver.go
+++ b/internal/resolution/resolver.go
@@ -46,6 +46,7 @@ type SharedInput struct {
        PodTemplate         *supersetv1alpha1.PodTemplate
        Autoscaling         *supersetv1alpha1.AutoscalingSpec
        PodDisruptionBudget *supersetv1alpha1.PDBSpec
+       ScalingMode         *supersetv1alpha1.ScalingMode
 }
 
 // ComponentInput captures per-component fields. Embeds SharedInput.
@@ -69,6 +70,9 @@ type FlatSpec struct {
        PodTemplate         *supersetv1alpha1.PodTemplate
        Autoscaling         *supersetv1alpha1.AutoscalingSpec
        PodDisruptionBudget *supersetv1alpha1.PDBSpec
+       // ExternalScaling is true when an external controller owns the replica
+       // count: Replicas is not applied and Autoscaling is nil.
+       ExternalScaling bool
 }
 
 // defaultReplicas is the fallback when neither component nor defaults specify 
replicas.
@@ -103,5 +107,15 @@ func ResolveComponentSpec(
        result.Autoscaling = ResolveOverridableValue(comp.Autoscaling, 
tl.Autoscaling)
        result.PodDisruptionBudget = 
ResolveOverridableValue(comp.PodDisruptionBudget, tl.PodDisruptionBudget)
 
+       // An external controller owns the replica count, so inherited
+       // spec.autoscaling must not create a competing HPA. Beat and lifecycle
+       // Jobs are not scalable and ignore the mode (they also have no scaling
+       // resources; see hasScaling in 
internal/controller/component_resources.go).
+       scalable := componentType != ComponentCeleryBeat && componentType != 
ComponentInit
+       if scalable && ResolveOverridableValue(comp.ScalingMode, 
tl.ScalingMode).IsExternal() {
+               result.ExternalScaling = true
+               result.Autoscaling = nil
+       }
+
        return result
 }
diff --git a/internal/resolution/resolver_test.go 
b/internal/resolution/resolver_test.go
index eaf64dd..c154616 100644
--- a/internal/resolution/resolver_test.go
+++ b/internal/resolution/resolver_test.go
@@ -633,4 +633,39 @@ func TestResolveComponentSpec_AutoscalingPDB_Inheritance(t 
*testing.T) {
                        t.Error("expected nil PDB when neither set")
                }
        })
+
+       t.Run("external scaling drops inherited autoscaling and keeps PDB", 
func(t *testing.T) {
+               component := &ComponentInput{ScalingMode: 
new(supersetv1alpha1.ScalingModeExternal)}
+               result := ResolveComponentSpec(ComponentCeleryWorker, topLevel, 
component, nil, nil)
+               if !result.ExternalScaling {
+                       t.Error("expected ExternalScaling for scalingMode 
External")
+               }
+               if result.Autoscaling != nil {
+                       t.Error("expected inherited autoscaling to be dropped 
for external scaling")
+               }
+               if result.PodDisruptionBudget == nil {
+                       t.Error("expected inherited PDB to still apply under 
external scaling")
+               }
+       })
+
+       t.Run("top-level External is inherited; Operator opts a component out; 
beat ignores it", func(t *testing.T) {
+               external := &SharedInput{ScalingMode: 
new(supersetv1alpha1.ScalingModeExternal)}
+
+               if result := ResolveComponentSpec(ComponentWebServer, external, 
nil, nil, nil); !result.ExternalScaling {
+                       t.Error("expected web server to inherit top-level 
External")
+               }
+
+               optOut := &ComponentInput{
+                       ScalingMode: new(supersetv1alpha1.ScalingModeOperator),
+                       Autoscaling: 
&supersetv1alpha1.AutoscalingSpec{MaxReplicas: 4},
+               }
+               result := ResolveComponentSpec(ComponentWebServer, external, 
optOut, nil, nil)
+               if result.ExternalScaling || result.Autoscaling == nil || 
result.Autoscaling.MaxReplicas != 4 {
+                       t.Errorf("expected Operator to opt out with its own 
autoscaling, got external=%v autoscaling=%v", result.ExternalScaling, 
result.Autoscaling)
+               }
+
+               if beat := ResolveComponentSpec(ComponentCeleryBeat, external, 
nil, nil, nil); beat.ExternalScaling || beat.Replicas != 1 {
+                       t.Errorf("expected beat to ignore top-level External, 
got external=%v replicas=%d", beat.ExternalScaling, beat.Replicas)
+               }
+       })
 }

Reply via email to