From b7eda846fb79e59d12f4e9e23cd095612055d0b3 Mon Sep 17 00:00:00 2001 From: xing Date: Sun, 26 Jul 2026 12:47:13 +0800 Subject: [PATCH 1/4] fix(operator): add default resource limits for MCPRemoteProxy Apply proxy-runner defaults when MCPRemoteProxy omits resource requests/limits, merge user overrides on top of those defaults, and keep deployment drift detection aligned with the same effective resource calculation. Closes #3131 --- .../controllers/mcpremoteproxy_controller.go | 5 +- .../controllers/mcpremoteproxy_deployment.go | 10 +- .../mcpremoteproxy_deployment_test.go | 109 ++++++++++++++++++ .../pkg/controllerutil/resources.go | 55 +++++++++ .../pkg/controllerutil/resources_test.go | 32 +++++ 5 files changed, 208 insertions(+), 3 deletions(-) diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go index d07223df07..7979ccd9eb 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go @@ -1907,8 +1907,9 @@ func (r *MCPRemoteProxyReconciler) generatedContainerNeedsUpdate( return true } - // Check if resources have changed - expectedResources := ctrlutil.BuildResourceRequirements(proxy.Spec.Resources) + // Check if resources have changed. Use the same default+override merge as + // deployment generation so drift detection stays consistent. + expectedResources := resourceRequirementsForRemoteProxy(proxy) if !reflect.DeepEqual(container.Resources, expectedResources) { return true } diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go index 1703392bec..494dbc7cad 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go @@ -73,7 +73,7 @@ func (r *MCPRemoteProxyReconciler) deploymentForMCPRemoteProxy( volumeMounts = append(volumeMounts, authServerMounts...) env = append(env, authServerEnvVars...) } - resources := ctrlutil.BuildResourceRequirements(proxy.Spec.Resources) + resources := resourceRequirementsForRemoteProxy(proxy) deploymentLabels, deploymentAnnotations := r.buildDeploymentMetadata(ls, proxy) deploymentTemplateLabels, deploymentTemplateAnnotations := r.buildPodTemplateMetadata(ls, proxy, runConfigChecksum) if configName != "" { @@ -150,6 +150,14 @@ func (r *MCPRemoteProxyReconciler) deploymentForMCPRemoteProxy( return dep } +// resourceRequirementsForRemoteProxy returns effective container resources for +// an MCPRemoteProxy, applying proxy-runner defaults and merging any user overrides. +func resourceRequirementsForRemoteProxy(proxy *mcpv1beta1.MCPRemoteProxy) corev1.ResourceRequirements { + defaultResources := ctrlutil.BuildDefaultProxyRunnerResourceRequirements() + userResources := ctrlutil.BuildResourceRequirements(proxy.Spec.Resources) + return ctrlutil.MergeResourceRequirements(defaultResources, userResources) +} + // buildContainerArgs builds the container arguments for the proxy func (*MCPRemoteProxyReconciler) buildContainerArgs() []string { // The third argument is required by proxyrunner command signature but is ignored diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go index f59612ba09..3ac9b18ccc 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go @@ -24,6 +24,7 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -80,6 +81,12 @@ func TestDeploymentForMCPRemoteProxy(t *testing.T) { // Verify service account assert.Equal(t, proxyRunnerServiceAccountNameForRemoteProxy("basic-proxy"), dep.Spec.Template.Spec.ServiceAccountName) + + // Verify default resource requirements when Spec.Resources is empty + assert.Equal(t, resource.MustParse("50m"), container.Resources.Requests[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("64Mi"), container.Resources.Requests[corev1.ResourceMemory]) + assert.Equal(t, resource.MustParse("200m"), container.Resources.Limits[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("256Mi"), container.Resources.Limits[corev1.ResourceMemory]) }, }, { @@ -107,6 +114,30 @@ func TestDeploymentForMCPRemoteProxy(t *testing.T) { assert.Equal(t, "128Mi", container.Resources.Requests.Memory().String()) }, }, + { + name: "with partial resource overrides", + proxy: v1beta1test.NewMCPRemoteProxy("partial-resources-proxy", "default", + v1beta1test.MutateRemoteProxy(func(p *mcpv1beta1.MCPRemoteProxy) { + p.Spec.Resources = mcpv1beta1.ResourceRequirements{ + Limits: mcpv1beta1.ResourceList{ + CPU: "1", + }, + Requests: mcpv1beta1.ResourceList{ + Memory: "128Mi", + }, + } + }), + ), + validate: func(t *testing.T, dep *appsv1.Deployment) { + t.Helper() + container := dep.Spec.Template.Spec.Containers[0] + // User-provided fields take precedence; missing fields keep defaults. + assert.Equal(t, resource.MustParse("50m"), container.Resources.Requests[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("128Mi"), container.Resources.Requests[corev1.ResourceMemory]) + assert.Equal(t, resource.MustParse("1"), container.Resources.Limits[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("256Mi"), container.Resources.Limits[corev1.ResourceMemory]) + }, + }, { name: "with resource overrides", proxy: v1beta1test.NewMCPRemoteProxy("override-proxy", "default", @@ -334,6 +365,84 @@ func TestBuildResourceRequirements(t *testing.T) { } } + +// TestResourceRequirementsForRemoteProxy tests default injection and merge behavior +func TestResourceRequirementsForRemoteProxy(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + proxy *mcpv1beta1.MCPRemoteProxy + validate func(*testing.T, corev1.ResourceRequirements) + }{ + { + name: "defaults when resources omitted", + proxy: v1beta1test.NewMCPRemoteProxy("defaults-proxy", "default"), + validate: func(t *testing.T, res corev1.ResourceRequirements) { + t.Helper() + assert.Equal(t, resource.MustParse("50m"), res.Requests[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("64Mi"), res.Requests[corev1.ResourceMemory]) + assert.Equal(t, resource.MustParse("200m"), res.Limits[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("256Mi"), res.Limits[corev1.ResourceMemory]) + }, + }, + { + name: "user overrides win over defaults", + proxy: v1beta1test.NewMCPRemoteProxy("override-resources-proxy", "default", + v1beta1test.MutateRemoteProxy(func(p *mcpv1beta1.MCPRemoteProxy) { + p.Spec.Resources = mcpv1beta1.ResourceRequirements{ + Limits: mcpv1beta1.ResourceList{ + CPU: "1", + Memory: "512Mi", + }, + Requests: mcpv1beta1.ResourceList{ + CPU: "100m", + Memory: "128Mi", + }, + } + }), + ), + validate: func(t *testing.T, res corev1.ResourceRequirements) { + t.Helper() + assert.Equal(t, resource.MustParse("100m"), res.Requests[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("128Mi"), res.Requests[corev1.ResourceMemory]) + assert.Equal(t, resource.MustParse("1"), res.Limits[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("512Mi"), res.Limits[corev1.ResourceMemory]) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := resourceRequirementsForRemoteProxy(tt.proxy) + if tt.validate != nil { + tt.validate(t, result) + } + }) + } +} + +// TestMCPRemoteProxyDeploymentNeedsUpdate_Resources detects resource drift with defaults +func TestMCPRemoteProxyDeploymentNeedsUpdate_Resources(t *testing.T) { + t.Parallel() + + scheme := testutil.NewScheme(t) + proxy := v1beta1test.NewMCPRemoteProxy("resources-drift-proxy", "default") + reconciler := &MCPRemoteProxyReconciler{ + Scheme: scheme, + PlatformDetector: ctrlutil.NewSharedPlatformDetector(), + } + + deployment := reconciler.deploymentForMCPRemoteProxy(t.Context(), proxy, "test-checksum") + require.NotNil(t, deployment) + assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) + + // Simulate a deployment created before defaults existed. + deployment.Spec.Template.Spec.Containers[0].Resources = corev1.ResourceRequirements{} + assert.True(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) +} + // TestBuildHeaderForwardSecretEnvVars tests the buildHeaderForwardSecretEnvVars function func TestBuildHeaderForwardSecretEnvVars(t *testing.T) { t.Parallel() diff --git a/cmd/thv-operator/pkg/controllerutil/resources.go b/cmd/thv-operator/pkg/controllerutil/resources.go index abedfad873..23adc81c69 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources.go +++ b/cmd/thv-operator/pkg/controllerutil/resources.go @@ -17,6 +17,15 @@ import ( "github.com/stacklok/toolhive/pkg/secrets" ) +// Default proxy-runner resource values used when a CR omits resource requests/limits. +// These keep remote proxy containers bounded while remaining overrideable per CR. +const ( + DefaultProxyRunnerCPURequest = "50m" + DefaultProxyRunnerCPULimit = "200m" + DefaultProxyRunnerMemoryRequest = "64Mi" + DefaultProxyRunnerMemoryLimit = "256Mi" +) + // BuildResourceRequirements builds Kubernetes resource requirements from CRD spec // Shared between MCPServer and MCPRemoteProxy func BuildResourceRequirements(resourceSpec mcpv1beta1.ResourceRequirements) corev1.ResourceRequirements { @@ -45,6 +54,52 @@ func BuildResourceRequirements(resourceSpec mcpv1beta1.ResourceRequirements) cor return resources } +// BuildDefaultProxyRunnerResourceRequirements returns the default resource +// requirements for proxy-runner containers (MCPRemoteProxy). +func BuildDefaultProxyRunnerResourceRequirements() corev1.ResourceRequirements { + return corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse(DefaultProxyRunnerCPURequest), + corev1.ResourceMemory: resource.MustParse(DefaultProxyRunnerMemoryRequest), + }, + Limits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse(DefaultProxyRunnerCPULimit), + corev1.ResourceMemory: resource.MustParse(DefaultProxyRunnerMemoryLimit), + }, + } +} + +// MergeResourceRequirements merges user-provided resource requirements on top of +// defaults. User values take precedence for any field that is explicitly set. +func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev1.ResourceRequirements { + merged := corev1.ResourceRequirements{ + Requests: corev1.ResourceList{}, + Limits: corev1.ResourceList{}, + } + + for resourceName, quantity := range defaults.Requests { + merged.Requests[resourceName] = quantity.DeepCopy() + } + for resourceName, quantity := range defaults.Limits { + merged.Limits[resourceName] = quantity.DeepCopy() + } + for resourceName, quantity := range user.Requests { + merged.Requests[resourceName] = quantity.DeepCopy() + } + for resourceName, quantity := range user.Limits { + merged.Limits[resourceName] = quantity.DeepCopy() + } + + if len(merged.Requests) == 0 { + merged.Requests = nil + } + if len(merged.Limits) == 0 { + merged.Limits = nil + } + + return merged +} + // BuildHealthProbe builds a Kubernetes health probe configuration // Shared between MCPServer and MCPRemoteProxy func BuildHealthProbe( diff --git a/cmd/thv-operator/pkg/controllerutil/resources_test.go b/cmd/thv-operator/pkg/controllerutil/resources_test.go index 6405014336..3e053016bf 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources_test.go +++ b/cmd/thv-operator/pkg/controllerutil/resources_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" "github.com/stacklok/toolhive/pkg/secrets" ) @@ -353,3 +354,34 @@ func TestMergeStringMaps(t *testing.T) { }) } } + +func TestBuildDefaultProxyRunnerResourceRequirements(t *testing.T) { + t.Parallel() + + res := BuildDefaultProxyRunnerResourceRequirements() + assert.Equal(t, resource.MustParse("50m"), res.Requests[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("64Mi"), res.Requests[corev1.ResourceMemory]) + assert.Equal(t, resource.MustParse("200m"), res.Limits[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("256Mi"), res.Limits[corev1.ResourceMemory]) +} + +func TestMergeResourceRequirements(t *testing.T) { + t.Parallel() + + defaults := BuildDefaultProxyRunnerResourceRequirements() + user := corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceMemory: resource.MustParse("128Mi"), + }, + Limits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("1"), + }, + } + + merged := MergeResourceRequirements(defaults, user) + assert.Equal(t, resource.MustParse("50m"), merged.Requests[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("128Mi"), merged.Requests[corev1.ResourceMemory]) + assert.Equal(t, resource.MustParse("1"), merged.Limits[corev1.ResourceCPU]) + assert.Equal(t, resource.MustParse("256Mi"), merged.Limits[corev1.ResourceMemory]) +} + From c1dfc621265fac5ce5580988e8430b731ddbdc91 Mon Sep 17 00:00:00 2001 From: Chris Burns <29541485+ChrisJBurns@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:46:12 -0700 Subject: [PATCH 2/4] Harden MCPRemoteProxy resource defaulting Address review feedback on the default resource limits change: - Clamp the defaulted side of a request/limit pair so a partial override (e.g. only requests.memory: 512Mi) cannot produce a request above the default limit, which the apiserver rejects. - Compare resources with equality.Semantic.DeepEqual in drift detection so non-canonical overrides such as cpu "0.2" do not trigger a perpetual reconcile/update loop. - Document the defaults on the CRD field and in the operator architecture doc, and regenerate CRD manifests and API docs. - Fix gofmt and codespell failures. Co-Authored-By: xing Co-Authored-By: Claude Opus 5.5 (1M context) --- .../api/v1beta1/mcpremoteproxy_types.go | 5 +- .../controllers/mcpremoteproxy_controller.go | 2 +- .../mcpremoteproxy_deployment_test.go | 69 +++++++++-- .../pkg/controllerutil/resources.go | 38 ++++-- .../pkg/controllerutil/resources_test.go | 116 ++++++++++++++++-- ...oolhive.stacklok.dev_mcpremoteproxies.yaml | 14 ++- ...oolhive.stacklok.dev_mcpremoteproxies.yaml | 14 ++- docs/arch/09-operator-architecture.md | 3 + docs/operator/crd-api.md | 2 +- 9 files changed, 221 insertions(+), 42 deletions(-) diff --git a/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go b/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go index 8308172371..cc8e441c46 100644 --- a/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go @@ -128,7 +128,10 @@ type MCPRemoteProxySpec struct { // +optional TelemetryConfigRef *MCPTelemetryConfigReference `json:"telemetryConfigRef,omitempty"` - // Resources defines the resource requirements for the proxy container + // Resources defines the resource requirements for the proxy container. + // Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, + // limits of 200m CPU and 256Mi memory. When only one side of a request/limit + // pair is set, the defaulted side is adjusted so the request never exceeds the limit. // +optional Resources ResourceRequirements `json:"resources,omitempty"` diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go index 7979ccd9eb..be09eb5dca 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go @@ -1910,7 +1910,7 @@ func (r *MCPRemoteProxyReconciler) generatedContainerNeedsUpdate( // Check if resources have changed. Use the same default+override merge as // deployment generation so drift detection stays consistent. expectedResources := resourceRequirementsForRemoteProxy(proxy) - if !reflect.DeepEqual(container.Resources, expectedResources) { + if !equality.Semantic.DeepEqual(container.Resources, expectedResources) { return true } diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go index 3ac9b18ccc..b51f29e1dd 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go @@ -365,7 +365,6 @@ func TestBuildResourceRequirements(t *testing.T) { } } - // TestResourceRequirementsForRemoteProxy tests default injection and merge behavior func TestResourceRequirementsForRemoteProxy(t *testing.T) { t.Parallel() @@ -427,20 +426,66 @@ func TestResourceRequirementsForRemoteProxy(t *testing.T) { func TestMCPRemoteProxyDeploymentNeedsUpdate_Resources(t *testing.T) { t.Parallel() - scheme := testutil.NewScheme(t) - proxy := v1beta1test.NewMCPRemoteProxy("resources-drift-proxy", "default") - reconciler := &MCPRemoteProxyReconciler{ - Scheme: scheme, - PlatformDetector: ctrlutil.NewSharedPlatformDetector(), + newReconciler := func(t *testing.T) *MCPRemoteProxyReconciler { + t.Helper() + return &MCPRemoteProxyReconciler{ + Scheme: testutil.NewScheme(t), + PlatformDetector: ctrlutil.NewSharedPlatformDetector(), + } } - deployment := reconciler.deploymentForMCPRemoteProxy(t.Context(), proxy, "test-checksum") - require.NotNil(t, deployment) - assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) + t.Run("freshly built deployment does not need update", func(t *testing.T) { + t.Parallel() + reconciler := newReconciler(t) + proxy := v1beta1test.NewMCPRemoteProxy("resources-drift-proxy", "default") + + deployment := reconciler.deploymentForMCPRemoteProxy(t.Context(), proxy, "test-checksum") + require.NotNil(t, deployment) + assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) + }) + + t.Run("deployment created before defaults existed needs update", func(t *testing.T) { + t.Parallel() + reconciler := newReconciler(t) + proxy := v1beta1test.NewMCPRemoteProxy("resources-drift-proxy", "default") + + deployment := reconciler.deploymentForMCPRemoteProxy(t.Context(), proxy, "test-checksum") + require.NotNil(t, deployment) + deployment.Spec.Template.Spec.Containers[0].Resources = corev1.ResourceRequirements{} + assert.True(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) + }) + + t.Run("non-canonical overrides do not drift after apiserver round-trip", func(t *testing.T) { + t.Parallel() + reconciler := newReconciler(t) + proxy := v1beta1test.NewMCPRemoteProxy("resources-canonical-proxy", "default", + v1beta1test.MutateRemoteProxy(func(p *mcpv1beta1.MCPRemoteProxy) { + p.Spec.Resources = mcpv1beta1.ResourceRequirements{ + Limits: mcpv1beta1.ResourceList{CPU: "0.2", Memory: "1024Mi"}, + Requests: mcpv1beta1.ResourceList{CPU: "1000m"}, + } + }), + ) + + deployment := reconciler.deploymentForMCPRemoteProxy(t.Context(), proxy, "test-checksum") + require.NotNil(t, deployment) + + // The apiserver stores quantities in canonical form, so the object read + // back on the next reconcile is not reflect.DeepEqual to the one we built. + container := &deployment.Spec.Template.Spec.Containers[0] + container.Resources.Limits = canonicalizeResourceList(container.Resources.Limits) + container.Resources.Requests = canonicalizeResourceList(container.Resources.Requests) - // Simulate a deployment created before defaults existed. - deployment.Spec.Template.Spec.Containers[0].Resources = corev1.ResourceRequirements{} - assert.True(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) + assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) + }) +} + +func canonicalizeResourceList(in corev1.ResourceList) corev1.ResourceList { + out := make(corev1.ResourceList, len(in)) + for name, quantity := range in { + out[name] = resource.MustParse(quantity.String()) + } + return out } // TestBuildHeaderForwardSecretEnvVars tests the buildHeaderForwardSecretEnvVars function diff --git a/cmd/thv-operator/pkg/controllerutil/resources.go b/cmd/thv-operator/pkg/controllerutil/resources.go index 23adc81c69..d9c598c23d 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources.go +++ b/cmd/thv-operator/pkg/controllerutil/resources.go @@ -18,12 +18,12 @@ import ( ) // Default proxy-runner resource values used when a CR omits resource requests/limits. -// These keep remote proxy containers bounded while remaining overrideable per CR. +// These keep remote proxy containers bounded while remaining overridable per CR. const ( - DefaultProxyRunnerCPURequest = "50m" - DefaultProxyRunnerCPULimit = "200m" - DefaultProxyRunnerMemoryRequest = "64Mi" - DefaultProxyRunnerMemoryLimit = "256Mi" + defaultProxyRunnerCPURequest = "50m" + defaultProxyRunnerCPULimit = "200m" + defaultProxyRunnerMemoryRequest = "64Mi" + defaultProxyRunnerMemoryLimit = "256Mi" ) // BuildResourceRequirements builds Kubernetes resource requirements from CRD spec @@ -59,18 +59,23 @@ func BuildResourceRequirements(resourceSpec mcpv1beta1.ResourceRequirements) cor func BuildDefaultProxyRunnerResourceRequirements() corev1.ResourceRequirements { return corev1.ResourceRequirements{ Requests: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse(DefaultProxyRunnerCPURequest), - corev1.ResourceMemory: resource.MustParse(DefaultProxyRunnerMemoryRequest), + corev1.ResourceCPU: resource.MustParse(defaultProxyRunnerCPURequest), + corev1.ResourceMemory: resource.MustParse(defaultProxyRunnerMemoryRequest), }, Limits: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse(DefaultProxyRunnerCPULimit), - corev1.ResourceMemory: resource.MustParse(DefaultProxyRunnerMemoryLimit), + corev1.ResourceCPU: resource.MustParse(defaultProxyRunnerCPULimit), + corev1.ResourceMemory: resource.MustParse(defaultProxyRunnerMemoryLimit), }, } } // MergeResourceRequirements merges user-provided resource requirements on top of // defaults. User values take precedence for any field that is explicitly set. +// +// A defaulted value never contradicts a user value: when the user sets only one +// side of a request/limit pair, the defaulted side is clamped so the request does +// not exceed the limit, which the API server would otherwise reject. A user who +// sets both sides inconsistently gets their values unchanged. func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev1.ResourceRequirements { merged := corev1.ResourceRequirements{ Requests: corev1.ResourceList{}, @@ -90,6 +95,21 @@ func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev merged.Limits[resourceName] = quantity.DeepCopy() } + for resourceName, request := range merged.Requests { + limit, hasLimit := merged.Limits[resourceName] + if !hasLimit || request.Cmp(limit) <= 0 { + continue + } + _, userSetRequest := user.Requests[resourceName] + _, userSetLimit := user.Limits[resourceName] + switch { + case userSetRequest && !userSetLimit: + merged.Limits[resourceName] = request.DeepCopy() + case userSetLimit && !userSetRequest: + merged.Requests[resourceName] = limit.DeepCopy() + } + } + if len(merged.Requests) == 0 { merged.Requests = nil } diff --git a/cmd/thv-operator/pkg/controllerutil/resources_test.go b/cmd/thv-operator/pkg/controllerutil/resources_test.go index 3e053016bf..c2eb199aef 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources_test.go +++ b/cmd/thv-operator/pkg/controllerutil/resources_test.go @@ -368,20 +368,116 @@ func TestBuildDefaultProxyRunnerResourceRequirements(t *testing.T) { func TestMergeResourceRequirements(t *testing.T) { t.Parallel() - defaults := BuildDefaultProxyRunnerResourceRequirements() - user := corev1.ResourceRequirements{ - Requests: corev1.ResourceList{ - corev1.ResourceMemory: resource.MustParse("128Mi"), + tests := []struct { + name string + user corev1.ResourceRequirements + wantRequests map[corev1.ResourceName]string + wantLimits map[corev1.ResourceName]string + }{ + { + name: "empty user keeps defaults", + user: corev1.ResourceRequirements{}, + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "50m", corev1.ResourceMemory: "64Mi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "200m", corev1.ResourceMemory: "256Mi", + }, + }, + { + name: "partial user values override matching fields only", + user: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("128Mi")}, + Limits: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("1")}, + }, + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "50m", corev1.ResourceMemory: "128Mi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "1", corev1.ResourceMemory: "256Mi", + }, + }, + { + name: "user request above default limit raises the defaulted limit", + user: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("500m"), + corev1.ResourceMemory: resource.MustParse("512Mi"), + }, + }, + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "500m", corev1.ResourceMemory: "512Mi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "500m", corev1.ResourceMemory: "512Mi", + }, + }, + { + name: "user limit below default request lowers the defaulted request", + user: corev1.ResourceRequirements{ + Limits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("20m"), + corev1.ResourceMemory: resource.MustParse("32Mi"), + }, + }, + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "20m", corev1.ResourceMemory: "32Mi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "20m", corev1.ResourceMemory: "32Mi", + }, }, - Limits: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse("1"), + { + name: "inconsistent user values are passed through unchanged", + user: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("1")}, + Limits: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("500m")}, + }, + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "1", corev1.ResourceMemory: "64Mi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "500m", corev1.ResourceMemory: "256Mi", + }, }, } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + merged := MergeResourceRequirements(BuildDefaultProxyRunnerResourceRequirements(), tt.user) + assertResourceList(t, tt.wantRequests, merged.Requests) + assertResourceList(t, tt.wantLimits, merged.Limits) + }) + } +} + +func TestMergeResourceRequirements_DoesNotAliasInputs(t *testing.T) { + t.Parallel() + + defaults := BuildDefaultProxyRunnerResourceRequirements() + user := corev1.ResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("100m")}, + } + merged := MergeResourceRequirements(defaults, user) - assert.Equal(t, resource.MustParse("50m"), merged.Requests[corev1.ResourceCPU]) - assert.Equal(t, resource.MustParse("128Mi"), merged.Requests[corev1.ResourceMemory]) - assert.Equal(t, resource.MustParse("1"), merged.Limits[corev1.ResourceCPU]) - assert.Equal(t, resource.MustParse("256Mi"), merged.Limits[corev1.ResourceMemory]) + merged.Requests[corev1.ResourceCPU] = resource.MustParse("2") + merged.Limits[corev1.ResourceMemory] = resource.MustParse("2Gi") + + assert.Equal(t, "100m", user.Requests.Cpu().String()) + assert.Equal(t, "256Mi", defaults.Limits.Memory().String()) } +func assertResourceList(t *testing.T, want map[corev1.ResourceName]string, got corev1.ResourceList) { + t.Helper() + + assert.Len(t, got, len(want)) + for name, wantQuantity := range want { + gotQuantity, ok := got[name] + if assert.True(t, ok, "missing %s", name) { + assert.Zero(t, gotQuantity.Cmp(resource.MustParse(wantQuantity)), + "%s: want %s, got %s", name, wantQuantity, gotQuantity.String()) + } + } +} diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml index 11deebb6b1..16d64ba3e0 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml @@ -1466,8 +1466,11 @@ spec: type: object type: object resources: - description: Resources defines the resource requirements for the proxy - container + description: |- + Resources defines the resource requirements for the proxy container. + Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, + limits of 200m CPU and 256Mi memory. When only one side of a request/limit + pair is set, the defaulted side is adjusted so the request never exceeds the limit. properties: limits: description: Limits describes the maximum amount of compute resources @@ -3244,8 +3247,11 @@ spec: type: object type: object resources: - description: Resources defines the resource requirements for the proxy - container + description: |- + Resources defines the resource requirements for the proxy container. + Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, + limits of 200m CPU and 256Mi memory. When only one side of a request/limit + pair is set, the defaulted side is adjusted so the request never exceeds the limit. properties: limits: description: Limits describes the maximum amount of compute resources diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml index e57f084023..b5e03ac2e5 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml @@ -1469,8 +1469,11 @@ spec: type: object type: object resources: - description: Resources defines the resource requirements for the proxy - container + description: |- + Resources defines the resource requirements for the proxy container. + Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, + limits of 200m CPU and 256Mi memory. When only one side of a request/limit + pair is set, the defaulted side is adjusted so the request never exceeds the limit. properties: limits: description: Limits describes the maximum amount of compute resources @@ -3247,8 +3250,11 @@ spec: type: object type: object resources: - description: Resources defines the resource requirements for the proxy - container + description: |- + Resources defines the resource requirements for the proxy container. + Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, + limits of 200m CPU and 256Mi memory. When only one side of a request/limit + pair is set, the defaulted side is adjusted so the request never exceeds the limit. properties: limits: description: Limits describes the maximum amount of compute resources diff --git a/docs/arch/09-operator-architecture.md b/docs/arch/09-operator-architecture.md index 44759a87f7..dcac56dfcc 100644 --- a/docs/arch/09-operator-architecture.md +++ b/docs/arch/09-operator-architecture.md @@ -327,9 +327,12 @@ Defines a proxy for remote MCP servers with authentication, authorization, audit - `authzConfig` - Authorization policies - `telemetryConfigRef` - Reference to shared MCPTelemetryConfig (replaces deprecated inline `telemetry`) - `toolConfigRef` - Tool filtering and renaming +- `resources` - CPU/memory requests and limits for the proxy container OIDC is optional — omit `oidcConfigRef` for unauthenticated proxies. +**Default resources**: the proxy container is always bounded. Any field left unset in `resources` takes its default (requests: 50m CPU / 64Mi memory; limits: 200m CPU / 256Mi memory), and user values override per field. When only one side of a request/limit pair is set, the defaulted side is adjusted so the request never exceeds the limit (for example, `requests.memory: 512Mi` alone yields a 512Mi memory limit rather than the 256Mi default). Proxies that predate these defaults roll once on operator upgrade to pick them up. + **Combined auth pattern**: `authServerRef` and `externalAuthConfigRef` can be used together on the same MCPRemoteProxy to enable both incoming client authentication (embedded auth server) and outgoing remote service authentication (e.g., AWS STS) simultaneously. This is the primary use case for `authServerRef` on MCPRemoteProxy. If both fields point to an `embeddedAuthServer` resource, the controller produces a validation error. ```yaml diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index 9e8e9996f8..945efdd92e 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -3187,7 +3187,7 @@ _Appears in:_ | `audit` _[api.v1beta1.AuditConfig](#apiv1beta1auditconfig)_ | Audit defines audit logging configuration for the proxy | | Optional: \{\}
| | `toolConfigRef` _[api.v1beta1.ToolConfigRef](#apiv1beta1toolconfigref)_ | ToolConfigRef references a MCPToolConfig resource for tool filtering and renaming.
The referenced MCPToolConfig must exist in the same namespace as this MCPRemoteProxy.
Cross-namespace references are not supported for security and isolation reasons.
If specified, this allows filtering and overriding tools from the remote MCP server. | | Optional: \{\}
| | `telemetryConfigRef` _[api.v1beta1.MCPTelemetryConfigReference](#apiv1beta1mcptelemetryconfigreference)_ | TelemetryConfigRef references an MCPTelemetryConfig resource for shared telemetry configuration.
The referenced MCPTelemetryConfig must exist in the same namespace as this MCPRemoteProxy.
Cross-namespace references are not supported for security and isolation reasons. | | Optional: \{\}
| -| `resources` _[api.v1beta1.ResourceRequirements](#apiv1beta1resourcerequirements)_ | Resources defines the resource requirements for the proxy container | | Optional: \{\}
| +| `resources` _[api.v1beta1.ResourceRequirements](#apiv1beta1resourcerequirements)_ | Resources defines the resource requirements for the proxy container.
Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory,
limits of 200m CPU and 256Mi memory. When only one side of a request/limit
pair is set, the defaulted side is adjusted so the request never exceeds the limit. | | Optional: \{\}
| | `serviceAccount` _string_ | ServiceAccount is the name of an already existing service account to use by the proxy.
If not specified, a ServiceAccount will be created automatically and used by the proxy. | | Optional: \{\}
| | `podTemplateSpec` _[RawExtension](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#rawextension-runtime-pkg)_ | PodTemplateSpec defines the pod template to use for the MCPRemoteProxy
This allows for customizing the pod configuration beyond what is provided by the other fields.
Note that to modify the specific container the remote proxy runs in, you must specify
the `toolhive` container name in the PodTemplateSpec.
This field accepts a PodTemplateSpec object as JSON/YAML. | | Type: object
Optional: \{\}
| | `trustProxyHeaders` _boolean_ | TrustProxyHeaders indicates whether to trust X-Forwarded-* headers from reverse proxies
When enabled, the proxy will use X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port,
and X-Forwarded-Prefix headers to construct endpoint URLs | false | Optional: \{\}
| From 1e7687914349c10d09087663c784aa52f226bfb2 Mon Sep 17 00:00:00 2001 From: Chris Burns <29541485+ChrisJBurns@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:20:17 +0000 Subject: [PATCH 3/4] Clamp resource defaults against podTemplateSpec The podTemplateSpec is applied as a strategic merge patch after the defaults are set, and that patch merges requests and limits key by key. A podTemplateSpec that set only requests kept the default limits, so the request could exceed the limit and the apiserver rejected the Deployment. On main the same CR was valid because there were no defaults to collide with. Add a generic controllerutil.BuildContainerResourceRequirements that layers defaults, the CRD resources field and the podTemplateSpec container resources (podTemplateSpec wins), then clamps. A null entry in the podTemplateSpec drops that key, matching what the patch does. Defaults are passed in so VirtualMCPServer can adopt it later. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../api/v1beta1/mcpremoteproxy_types.go | 7 +- .../controllers/mcpremoteproxy_controller.go | 5 +- .../controllers/mcpremoteproxy_deployment.go | 21 ++- .../mcpremoteproxy_deployment_test.go | 3 +- .../mcpremoteproxy_podtemplatespec_test.go | 120 ++++++++++++++++++ .../pkg/controllerutil/resources.go | 102 +++++++++++++++ .../pkg/controllerutil/resources_test.go | 84 ++++++++++++ ...oolhive.stacklok.dev_mcpremoteproxies.yaml | 14 +- ...oolhive.stacklok.dev_mcpremoteproxies.yaml | 14 +- docs/arch/09-operator-architecture.md | 2 +- docs/operator/crd-api.md | 2 +- 11 files changed, 354 insertions(+), 20 deletions(-) diff --git a/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go b/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go index cc8e441c46..01dcc90ed8 100644 --- a/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go @@ -130,8 +130,11 @@ type MCPRemoteProxySpec struct { // Resources defines the resource requirements for the proxy container. // Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, - // limits of 200m CPU and 256Mi memory. When only one side of a request/limit - // pair is set, the defaulted side is adjusted so the request never exceeds the limit. + // limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" + // container through podTemplateSpec take precedence over this field. + // When the user sets only one side of a request/limit pair, here or in + // podTemplateSpec, the defaulted side is adjusted so the request does not + // exceed the limit. Requests and limits the user sets explicitly are used as given. // +optional Resources ResourceRequirements `json:"resources,omitempty"` diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go index be09eb5dca..076c03c23d 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go @@ -1909,7 +1909,10 @@ func (r *MCPRemoteProxyReconciler) generatedContainerNeedsUpdate( // Check if resources have changed. Use the same default+override merge as // deployment generation so drift detection stays consistent. - expectedResources := resourceRequirementsForRemoteProxy(proxy) + expectedResources, err := resourceRequirementsForRemoteProxy(proxy) + if err != nil { + return true + } if !equality.Semantic.DeepEqual(container.Resources, expectedResources) { return true } diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go index 494dbc7cad..7b7558eae6 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go @@ -73,7 +73,11 @@ func (r *MCPRemoteProxyReconciler) deploymentForMCPRemoteProxy( volumeMounts = append(volumeMounts, authServerMounts...) env = append(env, authServerEnvVars...) } - resources := resourceRequirementsForRemoteProxy(proxy) + resources, err := resourceRequirementsForRemoteProxy(proxy) + if err != nil { + log.FromContext(ctx).Error(err, "Failed to build resource requirements") + return nil + } deploymentLabels, deploymentAnnotations := r.buildDeploymentMetadata(ls, proxy) deploymentTemplateLabels, deploymentTemplateAnnotations := r.buildPodTemplateMetadata(ls, proxy, runConfigChecksum) if configName != "" { @@ -151,11 +155,16 @@ func (r *MCPRemoteProxyReconciler) deploymentForMCPRemoteProxy( } // resourceRequirementsForRemoteProxy returns effective container resources for -// an MCPRemoteProxy, applying proxy-runner defaults and merging any user overrides. -func resourceRequirementsForRemoteProxy(proxy *mcpv1beta1.MCPRemoteProxy) corev1.ResourceRequirements { - defaultResources := ctrlutil.BuildDefaultProxyRunnerResourceRequirements() - userResources := ctrlutil.BuildResourceRequirements(proxy.Spec.Resources) - return ctrlutil.MergeResourceRequirements(defaultResources, userResources) +// an MCPRemoteProxy: proxy-runner defaults, overridden per field by +// spec.resources and then by any resources podTemplateSpec sets on the proxy +// container. +func resourceRequirementsForRemoteProxy(proxy *mcpv1beta1.MCPRemoteProxy) (corev1.ResourceRequirements, error) { + return ctrlutil.BuildContainerResourceRequirements( + ctrlutil.BuildDefaultProxyRunnerResourceRequirements(), + proxy.Spec.Resources, + proxy.Spec.PodTemplateSpec, + mcpRemoteProxyContainerName, + ) } // buildContainerArgs builds the container arguments for the proxy diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go index b51f29e1dd..289301545d 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go @@ -414,7 +414,8 @@ func TestResourceRequirementsForRemoteProxy(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - result := resourceRequirementsForRemoteProxy(tt.proxy) + result, err := resourceRequirementsForRemoteProxy(tt.proxy) + require.NoError(t, err) if tt.validate != nil { tt.validate(t, result) } diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go index bf048e025a..b3fe847afc 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go @@ -10,7 +10,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -237,6 +239,124 @@ func TestMCPRemoteProxyPodTemplateSpecDriftDetection(t *testing.T) { assert.True(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) } +// Resources set through podTemplateSpec are layered over the defaults before +// the strategic merge patch runs. Otherwise a podTemplateSpec that sets only +// requests keeps the default limits and produces request > limit, which the +// apiserver rejects. +func TestMCPRemoteProxyPodTemplateSpecResources(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + resources mcpv1beta1.ResourceRequirements + podTemplateSpec string + wantRequests corev1.ResourceList + wantLimits corev1.ResourceList + }{ + { + name: "requests above the default limits raise the defaulted limits", + podTemplateSpec: `{"spec":{"containers":[{"name":"toolhive",` + + `"resources":{"requests":{"cpu":"1","memory":"512Mi"}}}]}}`, + wantRequests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("1"), + corev1.ResourceMemory: resource.MustParse("512Mi"), + }, + wantLimits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("1"), + corev1.ResourceMemory: resource.MustParse("512Mi"), + }, + }, + { + name: "limits below the default requests lower the defaulted requests", + podTemplateSpec: `{"spec":{"containers":[{"name":"toolhive",` + + `"resources":{"limits":{"cpu":"20m","memory":"32Mi"}}}]}}`, + wantRequests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("20m"), + corev1.ResourceMemory: resource.MustParse("32Mi"), + }, + wantLimits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("20m"), + corev1.ResourceMemory: resource.MustParse("32Mi"), + }, + }, + { + name: "podTemplateSpec wins over spec.resources", + resources: mcpv1beta1.ResourceRequirements{ + Limits: mcpv1beta1.ResourceList{Memory: "1Gi"}, + }, + podTemplateSpec: `{"spec":{"containers":[{"name":"toolhive",` + + `"resources":{"limits":{"memory":"768Mi"}}}]}}`, + wantRequests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("50m"), + corev1.ResourceMemory: resource.MustParse("64Mi"), + }, + wantLimits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("200m"), + corev1.ResourceMemory: resource.MustParse("768Mi"), + }, + }, + { + name: "null removes the default limit", + podTemplateSpec: `{"spec":{"containers":[{"name":"toolhive",` + + `"resources":{"limits":{"memory":null}}}]}}`, + wantRequests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("50m"), + corev1.ResourceMemory: resource.MustParse("64Mi"), + }, + wantLimits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("200m"), + }, + }, + { + name: "resources on another container are ignored", + podTemplateSpec: `{"spec":{"containers":[{"name":"sidecar","image":"busybox:latest",` + + `"resources":{"requests":{"memory":"1Gi"}}}]}}`, + wantRequests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("50m"), + corev1.ResourceMemory: resource.MustParse("64Mi"), + }, + wantLimits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("200m"), + corev1.ResourceMemory: resource.MustParse("256Mi"), + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + proxy := &mcpv1beta1.MCPRemoteProxy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "template-proxy", + Namespace: "default", + }, + Spec: mcpv1beta1.MCPRemoteProxySpec{ + RemoteURL: "https://mcp.example.com", + Resources: tt.resources, + PodTemplateSpec: rawPodTemplateSpecJSON(t, tt.podTemplateSpec), + }, + } + reconciler := &MCPRemoteProxyReconciler{ + Scheme: testutil.NewScheme(t), + PlatformDetector: ctrlutil.NewSharedPlatformDetector(), + } + + deployment := reconciler.deploymentForMCPRemoteProxy(t.Context(), proxy, "test-checksum") + require.NotNil(t, deployment) + + container, ok := findContainerByName(deployment.Spec.Template.Spec.Containers, mcpRemoteProxyContainerName) + require.True(t, ok) + assert.True(t, equality.Semantic.DeepEqual(tt.wantRequests, container.Resources.Requests), + "requests: want %v, got %v", tt.wantRequests, container.Resources.Requests) + assert.True(t, equality.Semantic.DeepEqual(tt.wantLimits, container.Resources.Limits), + "limits: want %v, got %v", tt.wantLimits, container.Resources.Limits) + + assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum")) + }) + } +} + // Scheduling can arrive from either resourceOverrides.proxyDeployment or // podTemplateSpec. Drift detection must account for both, so an override-only // comparison would report false drift on a podTemplateSpec-supplied value. diff --git a/cmd/thv-operator/pkg/controllerutil/resources.go b/cmd/thv-operator/pkg/controllerutil/resources.go index d9c598c23d..91d342073c 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources.go +++ b/cmd/thv-operator/pkg/controllerutil/resources.go @@ -5,11 +5,13 @@ package controllerutil import ( "context" + "encoding/json" "fmt" "strings" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" "sigs.k8s.io/controller-runtime/pkg/log" @@ -120,6 +122,106 @@ func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev return merged } +// BuildContainerResourceRequirements returns the resources to set on a +// controller-generated container before the user's podTemplateSpec is applied. +// +// Values are layered in increasing precedence: defaults, then the CRD's +// resources field, then any resources the podTemplateSpec sets on the container +// named containerName. The result goes through MergeResourceRequirements, so a +// defaulted value never pushes a request above a limit the user chose, or a +// limit below a request the user chose, whichever field the user set it in. +// +// The podTemplateSpec is still applied afterwards as a strategic merge patch. +// That re-sets the same values, except that a null entry deletes a key. A key +// the podTemplateSpec deletes is dropped here too, so no default stands in for +// it and it takes no part in clamping. +// +// It returns an error if podTemplateSpec is not valid JSON. +func BuildContainerResourceRequirements( + defaults corev1.ResourceRequirements, + specResources mcpv1beta1.ResourceRequirements, + podTemplateSpec *runtime.RawExtension, + containerName string, +) (corev1.ResourceRequirements, error) { + user := BuildResourceRequirements(specResources) + + templateResources, err := podTemplateContainerResources(podTemplateSpec, containerName) + if err != nil { + return corev1.ResourceRequirements{}, err + } + + defaults = *defaults.DeepCopy() + user.Requests = overlayResourceList(user.Requests, defaults.Requests, templateResources.Requests) + user.Limits = overlayResourceList(user.Limits, defaults.Limits, templateResources.Limits) + + return MergeResourceRequirements(defaults, user), nil +} + +// podTemplateResourceLists holds a container's resources as written in a +// podTemplateSpec patch. Pointer values keep a null entry (a strategic merge +// patch deletion) distinct from an explicit quantity. +type podTemplateResourceLists struct { + Requests map[corev1.ResourceName]*resource.Quantity `json:"requests,omitempty"` + Limits map[corev1.ResourceName]*resource.Quantity `json:"limits,omitempty"` +} + +// podTemplateContainerResources extracts the resources the podTemplateSpec +// patch sets on the named container. It returns empty lists if there is no +// patch or the patch does not mention that container. +func podTemplateContainerResources( + podTemplateSpec *runtime.RawExtension, + containerName string, +) (podTemplateResourceLists, error) { + if podTemplateSpec == nil || len(podTemplateSpec.Raw) == 0 { + return podTemplateResourceLists{}, nil + } + + var patch struct { + Spec struct { + Containers []struct { + Name string `json:"name"` + Resources podTemplateResourceLists `json:"resources"` + } `json:"containers"` + } `json:"spec"` + } + if err := json.Unmarshal(podTemplateSpec.Raw, &patch); err != nil { + return podTemplateResourceLists{}, fmt.Errorf("failed to read container resources from PodTemplateSpec: %w", err) + } + + for _, container := range patch.Spec.Containers { + if container.Name == containerName { + return container.Resources, nil + } + } + return podTemplateResourceLists{}, nil +} + +// overlayResourceList applies podTemplateSpec entries on top of base. A +// quantity overrides the base value; a null entry removes the key from both +// base and defaults, matching the strategic merge patch that runs later. +func overlayResourceList( + base, defaults corev1.ResourceList, + overlay map[corev1.ResourceName]*resource.Quantity, +) corev1.ResourceList { + if len(overlay) == 0 { + return base + } + + result := corev1.ResourceList{} + for resourceName, quantity := range base { + result[resourceName] = quantity.DeepCopy() + } + for resourceName, quantity := range overlay { + if quantity == nil { + delete(result, resourceName) + delete(defaults, resourceName) + continue + } + result[resourceName] = quantity.DeepCopy() + } + return result +} + // BuildHealthProbe builds a Kubernetes health probe configuration // Shared between MCPServer and MCPRemoteProxy func BuildHealthProbe( diff --git a/cmd/thv-operator/pkg/controllerutil/resources_test.go b/cmd/thv-operator/pkg/controllerutil/resources_test.go index c2eb199aef..ade276ef6c 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources_test.go +++ b/cmd/thv-operator/pkg/controllerutil/resources_test.go @@ -8,9 +8,12 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/runtime" + mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" "github.com/stacklok/toolhive/pkg/secrets" ) @@ -469,6 +472,87 @@ func TestMergeResourceRequirements_DoesNotAliasInputs(t *testing.T) { assert.Equal(t, "256Mi", defaults.Limits.Memory().String()) } +func TestBuildContainerResourceRequirements(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + specResources mcpv1beta1.ResourceRequirements + podTemplateSpec *runtime.RawExtension + wantRequests map[corev1.ResourceName]string + wantLimits map[corev1.ResourceName]string + wantErr bool + }{ + { + name: "no spec resources and no podTemplateSpec yields defaults", + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "50m", corev1.ResourceMemory: "64Mi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "200m", corev1.ResourceMemory: "256Mi", + }, + }, + { + name: "podTemplateSpec overrides spec resources and drives clamping", + specResources: mcpv1beta1.ResourceRequirements{ + Requests: mcpv1beta1.ResourceList{CPU: "100m", Memory: "128Mi"}, + }, + podTemplateSpec: &runtime.RawExtension{Raw: []byte(`{"spec":{"containers":[{"name":"main",` + + `"resources":{"requests":{"memory":"1Gi"}}}]}}`)}, + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "100m", corev1.ResourceMemory: "1Gi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "200m", corev1.ResourceMemory: "1Gi", + }, + }, + { + name: "null in podTemplateSpec drops the default and the spec value", + specResources: mcpv1beta1.ResourceRequirements{ + Requests: mcpv1beta1.ResourceList{Memory: "512Mi"}, + }, + podTemplateSpec: &runtime.RawExtension{Raw: []byte(`{"spec":{"containers":[{"name":"main",` + + `"resources":{"requests":{"memory":null},"limits":{"memory":null}}}]}}`)}, + wantRequests: map[corev1.ResourceName]string{corev1.ResourceCPU: "50m"}, + wantLimits: map[corev1.ResourceName]string{corev1.ResourceCPU: "200m"}, + }, + { + name: "podTemplateSpec without the target container is ignored", + podTemplateSpec: &runtime.RawExtension{Raw: []byte(`{"spec":{"nodeSelector":{"disk":"ssd"}}}`)}, + wantRequests: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "50m", corev1.ResourceMemory: "64Mi", + }, + wantLimits: map[corev1.ResourceName]string{ + corev1.ResourceCPU: "200m", corev1.ResourceMemory: "256Mi", + }, + }, + { + name: "invalid podTemplateSpec returns an error", + podTemplateSpec: &runtime.RawExtension{Raw: []byte(`{"spec":`)}, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + defaults := BuildDefaultProxyRunnerResourceRequirements() + got, err := BuildContainerResourceRequirements(defaults, tt.specResources, tt.podTemplateSpec, "main") + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assertResourceList(t, tt.wantRequests, got.Requests) + assertResourceList(t, tt.wantLimits, got.Limits) + + // The caller's defaults must not be modified. + assert.Equal(t, BuildDefaultProxyRunnerResourceRequirements(), defaults) + }) + } +} + func assertResourceList(t *testing.T, want map[corev1.ResourceName]string, got corev1.ResourceList) { t.Helper() diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml index 16d64ba3e0..02ddbfe492 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml @@ -1469,8 +1469,11 @@ spec: description: |- Resources defines the resource requirements for the proxy container. Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, - limits of 200m CPU and 256Mi memory. When only one side of a request/limit - pair is set, the defaulted side is adjusted so the request never exceeds the limit. + limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" + container through podTemplateSpec take precedence over this field. + When the user sets only one side of a request/limit pair, here or in + podTemplateSpec, the defaulted side is adjusted so the request does not + exceed the limit. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources @@ -3250,8 +3253,11 @@ spec: description: |- Resources defines the resource requirements for the proxy container. Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, - limits of 200m CPU and 256Mi memory. When only one side of a request/limit - pair is set, the defaulted side is adjusted so the request never exceeds the limit. + limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" + container through podTemplateSpec take precedence over this field. + When the user sets only one side of a request/limit pair, here or in + podTemplateSpec, the defaulted side is adjusted so the request does not + exceed the limit. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml index b5e03ac2e5..51b4416d4e 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml @@ -1472,8 +1472,11 @@ spec: description: |- Resources defines the resource requirements for the proxy container. Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, - limits of 200m CPU and 256Mi memory. When only one side of a request/limit - pair is set, the defaulted side is adjusted so the request never exceeds the limit. + limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" + container through podTemplateSpec take precedence over this field. + When the user sets only one side of a request/limit pair, here or in + podTemplateSpec, the defaulted side is adjusted so the request does not + exceed the limit. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources @@ -3253,8 +3256,11 @@ spec: description: |- Resources defines the resource requirements for the proxy container. Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, - limits of 200m CPU and 256Mi memory. When only one side of a request/limit - pair is set, the defaulted side is adjusted so the request never exceeds the limit. + limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" + container through podTemplateSpec take precedence over this field. + When the user sets only one side of a request/limit pair, here or in + podTemplateSpec, the defaulted side is adjusted so the request does not + exceed the limit. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources diff --git a/docs/arch/09-operator-architecture.md b/docs/arch/09-operator-architecture.md index dcac56dfcc..acbdc7aaa4 100644 --- a/docs/arch/09-operator-architecture.md +++ b/docs/arch/09-operator-architecture.md @@ -331,7 +331,7 @@ Defines a proxy for remote MCP servers with authentication, authorization, audit OIDC is optional — omit `oidcConfigRef` for unauthenticated proxies. -**Default resources**: the proxy container is always bounded. Any field left unset in `resources` takes its default (requests: 50m CPU / 64Mi memory; limits: 200m CPU / 256Mi memory), and user values override per field. When only one side of a request/limit pair is set, the defaulted side is adjusted so the request never exceeds the limit (for example, `requests.memory: 512Mi` alone yields a 512Mi memory limit rather than the 256Mi default). Proxies that predate these defaults roll once on operator upgrade to pick them up. +**Default resources**: unless the user removes them, the proxy container gets default requests and limits (requests: 50m CPU / 64Mi memory; limits: 200m CPU / 256Mi memory). User values override them per field, from `resources` or from the `toolhive` container in `podTemplateSpec`, with `podTemplateSpec` taking precedence. The controller layers all three sources before it applies the `podTemplateSpec` strategic merge patch. When the user sets only one side of a request/limit pair, the defaulted side is adjusted so the request does not exceed the limit. For example, `requests.memory: 512Mi` on its own yields a 512Mi memory limit rather than the 256Mi default. A `null` in `podTemplateSpec` removes that default instead. Proxies that predate these defaults roll once on operator upgrade to pick them up. **Combined auth pattern**: `authServerRef` and `externalAuthConfigRef` can be used together on the same MCPRemoteProxy to enable both incoming client authentication (embedded auth server) and outgoing remote service authentication (e.g., AWS STS) simultaneously. This is the primary use case for `authServerRef` on MCPRemoteProxy. If both fields point to an `embeddedAuthServer` resource, the controller produces a validation error. diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index 945efdd92e..107005f1c9 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -3187,7 +3187,7 @@ _Appears in:_ | `audit` _[api.v1beta1.AuditConfig](#apiv1beta1auditconfig)_ | Audit defines audit logging configuration for the proxy | | Optional: \{\}
| | `toolConfigRef` _[api.v1beta1.ToolConfigRef](#apiv1beta1toolconfigref)_ | ToolConfigRef references a MCPToolConfig resource for tool filtering and renaming.
The referenced MCPToolConfig must exist in the same namespace as this MCPRemoteProxy.
Cross-namespace references are not supported for security and isolation reasons.
If specified, this allows filtering and overriding tools from the remote MCP server. | | Optional: \{\}
| | `telemetryConfigRef` _[api.v1beta1.MCPTelemetryConfigReference](#apiv1beta1mcptelemetryconfigreference)_ | TelemetryConfigRef references an MCPTelemetryConfig resource for shared telemetry configuration.
The referenced MCPTelemetryConfig must exist in the same namespace as this MCPRemoteProxy.
Cross-namespace references are not supported for security and isolation reasons. | | Optional: \{\}
| -| `resources` _[api.v1beta1.ResourceRequirements](#apiv1beta1resourcerequirements)_ | Resources defines the resource requirements for the proxy container.
Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory,
limits of 200m CPU and 256Mi memory. When only one side of a request/limit
pair is set, the defaulted side is adjusted so the request never exceeds the limit. | | Optional: \{\}
| +| `resources` _[api.v1beta1.ResourceRequirements](#apiv1beta1resourcerequirements)_ | Resources defines the resource requirements for the proxy container.
Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory,
limits of 200m CPU and 256Mi memory. Resources set on the "toolhive"
container through podTemplateSpec take precedence over this field.
When the user sets only one side of a request/limit pair, here or in
podTemplateSpec, the defaulted side is adjusted so the request does not
exceed the limit. Requests and limits the user sets explicitly are used as given. | | Optional: \{\}
| | `serviceAccount` _string_ | ServiceAccount is the name of an already existing service account to use by the proxy.
If not specified, a ServiceAccount will be created automatically and used by the proxy. | | Optional: \{\}
| | `podTemplateSpec` _[RawExtension](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#rawextension-runtime-pkg)_ | PodTemplateSpec defines the pod template to use for the MCPRemoteProxy
This allows for customizing the pod configuration beyond what is provided by the other fields.
Note that to modify the specific container the remote proxy runs in, you must specify
the `toolhive` container name in the PodTemplateSpec.
This field accepts a PodTemplateSpec object as JSON/YAML. | | Type: object
Optional: \{\}
| | `trustProxyHeaders` _boolean_ | TrustProxyHeaders indicates whether to trust X-Forwarded-* headers from reverse proxies
When enabled, the proxy will use X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port,
and X-Forwarded-Prefix headers to construct endpoint URLs | false | Optional: \{\}
| From b290710854ed458a5d5a17e37c0a4501da561d09 Mon Sep 17 00:00:00 2001 From: Chris Burns <29541485+ChrisJBurns@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:04:52 +0000 Subject: [PATCH 4/4] Keep Kubernetes request defaulting for limits When a container sets a limit without a request, Kubernetes copies the limit into the request at Pod creation. Filling that gap with our default request instead silently turned a limits-only proxy from Guaranteed into Burstable QoS and shrank its reservation (for example from 2Gi to 64Mi) on upgrade. Drop the default request whenever the user sets a limit without one, in spec.resources or podTemplateSpec. That leaves raising a defaulted limit to meet a user's request as the only remaining adjustment. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../api/v1beta1/mcpremoteproxy_types.go | 7 +++-- .../mcpremoteproxy_deployment_test.go | 6 ++-- .../mcpremoteproxy_podtemplatespec_test.go | 16 +++++------ .../pkg/controllerutil/resources.go | 28 +++++++++++-------- .../pkg/controllerutil/resources_test.go | 15 +++++----- ...oolhive.stacklok.dev_mcpremoteproxies.yaml | 14 ++++++---- ...oolhive.stacklok.dev_mcpremoteproxies.yaml | 14 ++++++---- docs/arch/09-operator-architecture.md | 2 +- docs/operator/crd-api.md | 2 +- 9 files changed, 57 insertions(+), 47 deletions(-) diff --git a/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go b/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go index 01dcc90ed8..a99151b4e0 100644 --- a/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpremoteproxy_types.go @@ -132,9 +132,10 @@ type MCPRemoteProxySpec struct { // Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, // limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" // container through podTemplateSpec take precedence over this field. - // When the user sets only one side of a request/limit pair, here or in - // podTemplateSpec, the defaulted side is adjusted so the request does not - // exceed the limit. Requests and limits the user sets explicitly are used as given. + // A limit set without a request, here or in podTemplateSpec, drops the + // default request so Kubernetes copies the limit into the request as usual. + // A request set without a limit raises the default limit to match if the + // request is above it. Requests and limits the user sets explicitly are used as given. // +optional Resources ResourceRequirements `json:"resources,omitempty"` diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go index 289301545d..93b4d94913 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go @@ -131,8 +131,10 @@ func TestDeploymentForMCPRemoteProxy(t *testing.T) { validate: func(t *testing.T, dep *appsv1.Deployment) { t.Helper() container := dep.Spec.Template.Spec.Containers[0] - // User-provided fields take precedence; missing fields keep defaults. - assert.Equal(t, resource.MustParse("50m"), container.Resources.Requests[corev1.ResourceCPU]) + // User-provided fields take precedence; missing fields keep defaults, + // except the CPU request, which Kubernetes copies from the user's CPU + // limit at Pod creation. + assert.NotContains(t, container.Resources.Requests, corev1.ResourceCPU) assert.Equal(t, resource.MustParse("128Mi"), container.Resources.Requests[corev1.ResourceMemory]) assert.Equal(t, resource.MustParse("1"), container.Resources.Limits[corev1.ResourceCPU]) assert.Equal(t, resource.MustParse("256Mi"), container.Resources.Limits[corev1.ResourceMemory]) diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go index b3fe847afc..87919f3888 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_podtemplatespec_test.go @@ -267,16 +267,15 @@ func TestMCPRemoteProxyPodTemplateSpecResources(t *testing.T) { }, }, { - name: "limits below the default requests lower the defaulted requests", + // Kubernetes copies the limits into the missing requests at Pod + // creation, as it does without defaults. + name: "limits without requests drop the default requests", podTemplateSpec: `{"spec":{"containers":[{"name":"toolhive",` + - `"resources":{"limits":{"cpu":"20m","memory":"32Mi"}}}]}}`, - wantRequests: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse("20m"), - corev1.ResourceMemory: resource.MustParse("32Mi"), - }, + `"resources":{"limits":{"cpu":"20m","memory":"2Gi"}}}]}}`, + wantRequests: nil, wantLimits: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("20m"), - corev1.ResourceMemory: resource.MustParse("32Mi"), + corev1.ResourceMemory: resource.MustParse("2Gi"), }, }, { @@ -287,8 +286,7 @@ func TestMCPRemoteProxyPodTemplateSpecResources(t *testing.T) { podTemplateSpec: `{"spec":{"containers":[{"name":"toolhive",` + `"resources":{"limits":{"memory":"768Mi"}}}]}}`, wantRequests: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse("50m"), - corev1.ResourceMemory: resource.MustParse("64Mi"), + corev1.ResourceCPU: resource.MustParse("50m"), }, wantLimits: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("200m"), diff --git a/cmd/thv-operator/pkg/controllerutil/resources.go b/cmd/thv-operator/pkg/controllerutil/resources.go index 91d342073c..d46f1ca086 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources.go +++ b/cmd/thv-operator/pkg/controllerutil/resources.go @@ -74,10 +74,16 @@ func BuildDefaultProxyRunnerResourceRequirements() corev1.ResourceRequirements { // MergeResourceRequirements merges user-provided resource requirements on top of // defaults. User values take precedence for any field that is explicitly set. // -// A defaulted value never contradicts a user value: when the user sets only one -// side of a request/limit pair, the defaulted side is clamped so the request does -// not exceed the limit, which the API server would otherwise reject. A user who -// sets both sides inconsistently gets their values unchanged. +// A defaulted value never contradicts a user value: +// - When the user sets a limit without a request, the default request is +// dropped so Kubernetes copies the limit into the request at Pod creation, +// as it would with no defaults. This keeps a limits-only container's QoS +// class and its reservation unchanged. +// - When the user sets a request without a limit and the request is above +// the default limit, the limit is raised to match the request, which the +// API server would otherwise reject. +// +// A user who sets both sides inconsistently gets their values unchanged. func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev1.ResourceRequirements { merged := corev1.ResourceRequirements{ Requests: corev1.ResourceList{}, @@ -95,6 +101,9 @@ func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev } for resourceName, quantity := range user.Limits { merged.Limits[resourceName] = quantity.DeepCopy() + if _, userSetRequest := user.Requests[resourceName]; !userSetRequest { + delete(merged.Requests, resourceName) + } } for resourceName, request := range merged.Requests { @@ -102,13 +111,8 @@ func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev if !hasLimit || request.Cmp(limit) <= 0 { continue } - _, userSetRequest := user.Requests[resourceName] - _, userSetLimit := user.Limits[resourceName] - switch { - case userSetRequest && !userSetLimit: + if _, userSetLimit := user.Limits[resourceName]; !userSetLimit { merged.Limits[resourceName] = request.DeepCopy() - case userSetLimit && !userSetRequest: - merged.Requests[resourceName] = limit.DeepCopy() } } @@ -128,8 +132,8 @@ func MergeResourceRequirements(defaults, user corev1.ResourceRequirements) corev // Values are layered in increasing precedence: defaults, then the CRD's // resources field, then any resources the podTemplateSpec sets on the container // named containerName. The result goes through MergeResourceRequirements, so a -// defaulted value never pushes a request above a limit the user chose, or a -// limit below a request the user chose, whichever field the user set it in. +// defaulted value never contradicts a request or limit the user chose, +// whichever field the user set it in. // // The podTemplateSpec is still applied afterwards as a strategic merge patch. // That re-sets the same values, except that a null entry deletes a key. A key diff --git a/cmd/thv-operator/pkg/controllerutil/resources_test.go b/cmd/thv-operator/pkg/controllerutil/resources_test.go index ade276ef6c..cb9ecc3276 100644 --- a/cmd/thv-operator/pkg/controllerutil/resources_test.go +++ b/cmd/thv-operator/pkg/controllerutil/resources_test.go @@ -393,8 +393,9 @@ func TestMergeResourceRequirements(t *testing.T) { Requests: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("128Mi")}, Limits: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("1")}, }, + // No CPU request: Kubernetes copies the user's CPU limit at Pod creation. wantRequests: map[corev1.ResourceName]string{ - corev1.ResourceCPU: "50m", corev1.ResourceMemory: "128Mi", + corev1.ResourceMemory: "128Mi", }, wantLimits: map[corev1.ResourceName]string{ corev1.ResourceCPU: "1", corev1.ResourceMemory: "256Mi", @@ -416,18 +417,18 @@ func TestMergeResourceRequirements(t *testing.T) { }, }, { - name: "user limit below default request lowers the defaulted request", + // Kubernetes copies a limit into a missing request at Pod creation, so + // a limits-only container keeps its QoS class and reservation. + name: "user limit without a request drops the default request", user: corev1.ResourceRequirements{ Limits: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("20m"), - corev1.ResourceMemory: resource.MustParse("32Mi"), + corev1.ResourceMemory: resource.MustParse("2Gi"), }, }, - wantRequests: map[corev1.ResourceName]string{ - corev1.ResourceCPU: "20m", corev1.ResourceMemory: "32Mi", - }, + wantRequests: map[corev1.ResourceName]string{}, wantLimits: map[corev1.ResourceName]string{ - corev1.ResourceCPU: "20m", corev1.ResourceMemory: "32Mi", + corev1.ResourceCPU: "20m", corev1.ResourceMemory: "2Gi", }, }, { diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml index 02ddbfe492..0cc7d0d035 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpremoteproxies.yaml @@ -1471,9 +1471,10 @@ spec: Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" container through podTemplateSpec take precedence over this field. - When the user sets only one side of a request/limit pair, here or in - podTemplateSpec, the defaulted side is adjusted so the request does not - exceed the limit. Requests and limits the user sets explicitly are used as given. + A limit set without a request, here or in podTemplateSpec, drops the + default request so Kubernetes copies the limit into the request as usual. + A request set without a limit raises the default limit to match if the + request is above it. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources @@ -3255,9 +3256,10 @@ spec: Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" container through podTemplateSpec take precedence over this field. - When the user sets only one side of a request/limit pair, here or in - podTemplateSpec, the defaulted side is adjusted so the request does not - exceed the limit. Requests and limits the user sets explicitly are used as given. + A limit set without a request, here or in podTemplateSpec, drops the + default request so Kubernetes copies the limit into the request as usual. + A request set without a limit raises the default limit to match if the + request is above it. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml index 51b4416d4e..188f1f55cd 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpremoteproxies.yaml @@ -1474,9 +1474,10 @@ spec: Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" container through podTemplateSpec take precedence over this field. - When the user sets only one side of a request/limit pair, here or in - podTemplateSpec, the defaulted side is adjusted so the request does not - exceed the limit. Requests and limits the user sets explicitly are used as given. + A limit set without a request, here or in podTemplateSpec, drops the + default request so Kubernetes copies the limit into the request as usual. + A request set without a limit raises the default limit to match if the + request is above it. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources @@ -3258,9 +3259,10 @@ spec: Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory, limits of 200m CPU and 256Mi memory. Resources set on the "toolhive" container through podTemplateSpec take precedence over this field. - When the user sets only one side of a request/limit pair, here or in - podTemplateSpec, the defaulted side is adjusted so the request does not - exceed the limit. Requests and limits the user sets explicitly are used as given. + A limit set without a request, here or in podTemplateSpec, drops the + default request so Kubernetes copies the limit into the request as usual. + A request set without a limit raises the default limit to match if the + request is above it. Requests and limits the user sets explicitly are used as given. properties: limits: description: Limits describes the maximum amount of compute resources diff --git a/docs/arch/09-operator-architecture.md b/docs/arch/09-operator-architecture.md index acbdc7aaa4..f0c1d6995d 100644 --- a/docs/arch/09-operator-architecture.md +++ b/docs/arch/09-operator-architecture.md @@ -331,7 +331,7 @@ Defines a proxy for remote MCP servers with authentication, authorization, audit OIDC is optional — omit `oidcConfigRef` for unauthenticated proxies. -**Default resources**: unless the user removes them, the proxy container gets default requests and limits (requests: 50m CPU / 64Mi memory; limits: 200m CPU / 256Mi memory). User values override them per field, from `resources` or from the `toolhive` container in `podTemplateSpec`, with `podTemplateSpec` taking precedence. The controller layers all three sources before it applies the `podTemplateSpec` strategic merge patch. When the user sets only one side of a request/limit pair, the defaulted side is adjusted so the request does not exceed the limit. For example, `requests.memory: 512Mi` on its own yields a 512Mi memory limit rather than the 256Mi default. A `null` in `podTemplateSpec` removes that default instead. Proxies that predate these defaults roll once on operator upgrade to pick them up. +**Default resources**: unless the user removes them, the proxy container gets default requests and limits (requests: 50m CPU / 64Mi memory; limits: 200m CPU / 256Mi memory). User values override them per field, from `resources` or from the `toolhive` container in `podTemplateSpec`, with `podTemplateSpec` taking precedence. The controller layers all three sources before it applies the `podTemplateSpec` strategic merge patch. If the user sets a limit without a request, the default request is dropped, so Kubernetes copies the limit into the request at Pod creation, as it would with no defaults. A limits-only proxy therefore keeps its QoS class and reservation. If the user sets a request without a limit and the request is above the default limit, the limit is raised to match. For example, `requests.memory: 512Mi` on its own yields a 512Mi memory limit rather than the 256Mi default. A `null` in `podTemplateSpec` removes that default instead. Proxies that predate these defaults roll once on operator upgrade to pick them up. **Combined auth pattern**: `authServerRef` and `externalAuthConfigRef` can be used together on the same MCPRemoteProxy to enable both incoming client authentication (embedded auth server) and outgoing remote service authentication (e.g., AWS STS) simultaneously. This is the primary use case for `authServerRef` on MCPRemoteProxy. If both fields point to an `embeddedAuthServer` resource, the controller produces a validation error. diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index 107005f1c9..1d133dbb64 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -3187,7 +3187,7 @@ _Appears in:_ | `audit` _[api.v1beta1.AuditConfig](#apiv1beta1auditconfig)_ | Audit defines audit logging configuration for the proxy | | Optional: \{\}
| | `toolConfigRef` _[api.v1beta1.ToolConfigRef](#apiv1beta1toolconfigref)_ | ToolConfigRef references a MCPToolConfig resource for tool filtering and renaming.
The referenced MCPToolConfig must exist in the same namespace as this MCPRemoteProxy.
Cross-namespace references are not supported for security and isolation reasons.
If specified, this allows filtering and overriding tools from the remote MCP server. | | Optional: \{\}
| | `telemetryConfigRef` _[api.v1beta1.MCPTelemetryConfigReference](#apiv1beta1mcptelemetryconfigreference)_ | TelemetryConfigRef references an MCPTelemetryConfig resource for shared telemetry configuration.
The referenced MCPTelemetryConfig must exist in the same namespace as this MCPRemoteProxy.
Cross-namespace references are not supported for security and isolation reasons. | | Optional: \{\}
| -| `resources` _[api.v1beta1.ResourceRequirements](#apiv1beta1resourcerequirements)_ | Resources defines the resource requirements for the proxy container.
Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory,
limits of 200m CPU and 256Mi memory. Resources set on the "toolhive"
container through podTemplateSpec take precedence over this field.
When the user sets only one side of a request/limit pair, here or in
podTemplateSpec, the defaulted side is adjusted so the request does not
exceed the limit. Requests and limits the user sets explicitly are used as given. | | Optional: \{\}
| +| `resources` _[api.v1beta1.ResourceRequirements](#apiv1beta1resourcerequirements)_ | Resources defines the resource requirements for the proxy container.
Unset fields fall back to defaults: requests of 50m CPU and 64Mi memory,
limits of 200m CPU and 256Mi memory. Resources set on the "toolhive"
container through podTemplateSpec take precedence over this field.
A limit set without a request, here or in podTemplateSpec, drops the
default request so Kubernetes copies the limit into the request as usual.
A request set without a limit raises the default limit to match if the
request is above it. Requests and limits the user sets explicitly are used as given. | | Optional: \{\}
| | `serviceAccount` _string_ | ServiceAccount is the name of an already existing service account to use by the proxy.
If not specified, a ServiceAccount will be created automatically and used by the proxy. | | Optional: \{\}
| | `podTemplateSpec` _[RawExtension](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#rawextension-runtime-pkg)_ | PodTemplateSpec defines the pod template to use for the MCPRemoteProxy
This allows for customizing the pod configuration beyond what is provided by the other fields.
Note that to modify the specific container the remote proxy runs in, you must specify
the `toolhive` container name in the PodTemplateSpec.
This field accepts a PodTemplateSpec object as JSON/YAML. | | Type: object
Optional: \{\}
| | `trustProxyHeaders` _boolean_ | TrustProxyHeaders indicates whether to trust X-Forwarded-* headers from reverse proxies
When enabled, the proxy will use X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port,
and X-Forwarded-Prefix headers to construct endpoint URLs | false | Optional: \{\}
|