Repository navigation
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #4638 +/- ##
==========================================
- Coverage 68.90% 68.86% -0.04%
==========================================
Files 508 508
Lines 52593 52636 +43
==========================================
+ Hits 36238 36250 +12
- Misses 13551 13580 +29
- Partials 2804 2806 +2 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Large PR Detected
This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.
How to unblock this PR:
Add a section to your PR description with the following format:
## Large PR Justification
[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformationAlternative:
Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.
See our Contributing Guidelines for more details.
This review will be automatically dismissed once you add the justification section.
Large PR justification has been provided. Thank you!
|
✅ Large PR justification has been provided. The size review has been dismissed and this PR can now proceed with normal review. |
There was a problem hiding this comment.
Pull request overview
This PR fixes MCP session routing in Kubernetes when backendReplicas > 1 by ensuring sessions can be routed back to a specific StatefulSet pod (via headless DNS) after a proxy-runner restart, instead of being re-randomized through the ClusterIP service.
Changes:
- Fix StatefulSet
serviceNameto match the created headless service name so per-pod DNS records are generated. - Add headless-service routing config to the operator/runconfig path and transport layer, and attempt to store a pod-specific headless DNS URL in session metadata.
- Add unit + E2E coverage around multi-replica session routing and proxy-runner restart behavior.
Reviewed changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| test/e2e/thv-operator/virtualmcp/mcpserver_scaling_test.go | New E2E tests for Redis-backed sessions across replicas and proxy-runner restart routing. |
| pkg/transport/types/transport.go | Adds pluggable SessionStorage to transport config for non-local session stores (e.g., Redis). |
| pkg/transport/proxy/transparent/transparent_proxy.go | Adds headless-service routing option and stores per-session backend_url metadata. |
| pkg/transport/proxy/transparent/backend_routing_test.go | Unit tests for storing pod-specific backend_url when headless routing is configured. |
| pkg/transport/http.go | Wires session storage + headless routing options into the HTTP transport’s proxy creation. |
| pkg/transport/factory.go | Threads SessionStorage into transports; adds a transport option for headless routing. |
| pkg/runner/runner.go | Creates Redis session storage from scaling config and passes headless routing settings into transports. |
| pkg/runner/config.go | Extends scaling config with HeadlessService metadata for building per-pod DNS URLs. |
| pkg/container/kubernetes/client.go | Fixes StatefulSet serviceName to mcp-<name>-headless to enable StatefulSet pod DNS. |
| cmd/thv-operator/controllers/mcpserver_runconfig.go | Operator populates new headless routing config into the generated RunConfig. |
| .codespellrc | Adds clientA to ignore list for the new tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
When backendReplicas > 1, the proxy was storing the ClusterIP service
URL as backend_url on session initialize. After a proxy-runner restart,
Redis-recovered sessions were routed through the ClusterIP, which sent
requests to a random pod — one that had never seen the initialize and
returned -32001 ("session not found").
Two root causes fixed:
1. StatefulSet serviceName was set to containerName instead of
mcp-<name>-headless, so Kubernetes never created pod DNS records.
2. On initialize, the proxy now picks a random pod ordinal and stores
its headless DNS URL (e.g. myserver-0.mcp-myserver-headless.default
.svc.cluster.local) as backend_url instead of the ClusterIP. The
Rewrite closure already reads backend_url to route follow-up
requests, so sessions now survive proxy-runner restarts.
The operator populates a new HeadlessServiceConfig (StatefulSet name,
headless service name, namespace, replica count) in ScalingConfig when
backendReplicas > 1. Single-replica and non-Kubernetes deployments are
unaffected.
Fixes #4575
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 13 out of 13 changed files in this pull request and generated 6 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // Inject Redis-backed session storage for cross-replica session sharing. | ||
| if t.sessionStorage != nil { | ||
| proxyOptions = append(proxyOptions, transparent.WithSessionStorage(t.sessionStorage)) | ||
| } | ||
|
|
There was a problem hiding this comment.
proxyOptions appends WithSessionStorage(t.sessionStorage) twice. WithSessionStorage stops and recreates the sessionManager, so applying it twice is redundant work and can have side effects (extra Stop()/recreate) during proxy construction. Remove the duplicate block and keep a single append when sessionStorage != nil.
| // Inject Redis-backed session storage for cross-replica session sharing. | |
| if t.sessionStorage != nil { | |
| proxyOptions = append(proxyOptions, transparent.WithSessionStorage(t.sessionStorage)) | |
| } |
| // WithPodHeadlessService configures pod-specific routing for Kubernetes StatefulSet deployments. | ||
| // When set, each new MCP session is pinned to a specific pod via its headless DNS name | ||
| // (e.g. myserver-0.mcp-myserver-headless.default.svc.cluster.local) so that session routing | ||
| // survives proxy-runner restarts. For single-replica StatefulSets, ordinal 0 is always selected. | ||
| // The option is a no-op when any required field is empty. | ||
| func WithPodHeadlessService(statefulSetName, serviceName, namespace string, replicas int32) Option { | ||
| return func(p *TransparentProxy) { | ||
| if statefulSetName == "" || serviceName == "" || namespace == "" { | ||
| return | ||
| } | ||
| p.headlessService = &podHeadlessService{ | ||
| statefulSetName: statefulSetName, | ||
| serviceName: serviceName, | ||
| namespace: namespace, | ||
| replicas: replicas, | ||
| } |
There was a problem hiding this comment.
WithPodHeadlessService accepts replicas as-is. If replicas is 0 or negative (ScalingConfig.BackendReplicas can be set to 0), pickPodBackendURL will call crypto/rand.Int with a non-positive max and always fall back to targetURI. Consider making the option a no-op unless replicas >= 1 (or clamp replicas to 1) to avoid silently disabling pod routing and to keep behavior deterministic for replicas==1 (always ordinal 0).
| spec := appsv1apply.StatefulSetSpec(). | ||
| WithSelector(metav1apply.LabelSelector(). | ||
| WithMatchLabels(map[string]string{"app": containerName})). | ||
| WithServiceName(containerName). | ||
| WithServiceName(fmt.Sprintf("mcp-%s-headless", containerName)). | ||
| WithTemplate(podTemplateSpec) |
There was a problem hiding this comment.
This change updates StatefulSet spec.serviceName. Kubernetes treats several StatefulSet spec fields (including serviceName) as immutable; if so, server-side apply on an existing StatefulSet will fail during upgrades and the DNS fix won't take effect without a recreate. Consider adding a migration path (detect mismatch and recreate) or document the required rollout step for existing MCPServers.
| github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig: | ||
| description: |- | ||
| HeadlessService holds the information needed to construct pod-specific headless DNS URLs | ||
| for session-affinity routing in multi-replica StatefulSet deployments. | ||
| Populated by the operator when backendReplicas > 1; nil for single-replica deployments. | ||
| +optional |
There was a problem hiding this comment.
The OpenAPI schema is generated as github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig, but the actual Go type is pkg/transport/types.HeadlessServiceConfig. This mismatch will confuse API consumers/codegen and suggests the swagger artifacts were edited or generated incorrectly. Also, the description says this field is nil for single-replica, but the operator code populates HeadlessService whenever BackendReplicas is set (including 1). Regenerate swagger from source and ensure the schema name/description reflect the real type and behavior.
| github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig: | |
| description: |- | |
| HeadlessService holds the information needed to construct pod-specific headless DNS URLs | |
| for session-affinity routing in multi-replica StatefulSet deployments. | |
| Populated by the operator when backendReplicas > 1; nil for single-replica deployments. | |
| +optional | |
| github_com_stacklok_toolhive_pkg_transport_types.HeadlessServiceConfig: | |
| description: |- | |
| HeadlessService holds the information needed to construct pod-specific headless DNS URLs | |
| for session-affinity routing in StatefulSet deployments. | |
| Populated by the operator whenever backendReplicas is set, including single-replica deployments. |
| "github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig": { | ||
| "description": "HeadlessService holds the information needed to construct pod-specific headless DNS URLs\nfor session-affinity routing in multi-replica StatefulSet deployments.\nPopulated by the operator when backendReplicas \u003e 1; nil for single-replica deployments.\n+optional", |
There was a problem hiding this comment.
The OpenAPI JSON defines github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig, but the Go type wired into ScalingConfig is pkg/transport/types.HeadlessServiceConfig. This schema name mismatch can break client generation. Also the description states nil for single-replica, while operator populates HeadlessService whenever BackendReplicas is set. Regenerate swagger.json from code and align the description with actual behavior.
| "github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig": { | |
| "description": "HeadlessService holds the information needed to construct pod-specific headless DNS URLs\nfor session-affinity routing in multi-replica StatefulSet deployments.\nPopulated by the operator when backendReplicas \u003e 1; nil for single-replica deployments.\n+optional", | |
| "github_com_stacklok_toolhive_pkg_transport_types.HeadlessServiceConfig": { | |
| "description": "HeadlessService holds the information needed to construct pod-specific headless DNS URLs\nfor session-affinity routing in StatefulSet deployments.\nPopulated by the operator whenever backendReplicas is set, including single-replica deployments.\n+optional", | |
| "properties": { | |
| "namespace": { | |
| "description": "Namespace is the Kubernetes namespace of the StatefulSet.", | |
| "type": "string" | |
| }, | |
| "replicas": { | |
| "description": "Replicas is the StatefulSet replica count, used to select a random pod ordinal.", | |
| "type": "integer" | |
| }, | |
| "service_name": { | |
| "description": "ServiceName is the name of the headless Kubernetes service (e.g. \"mcp-myserver-headless\").", | |
| "type": "string" | |
| }, | |
| "statefulset_name": { | |
| "description": "StatefulSetName is the name of the backend StatefulSet (equals the MCPServer name).", | |
| "type": "string" | |
| } | |
| }, | |
| "type": "object" | |
| }, | |
| "github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig": { | |
| "description": "HeadlessService holds the information needed to construct pod-specific headless DNS URLs\nfor session-affinity routing in StatefulSet deployments.\nPopulated by the operator whenever backendReplicas is set, including single-replica deployments.\n+optional", |
| }, | ||
| "type": "object" | ||
| }, | ||
| "github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig": { |
There was a problem hiding this comment.
docs.go embeds a schema named github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig, but the referenced Go type is pkg/transport/types.HeadlessServiceConfig. This mismatch likely indicates the swagger artifacts are out of sync with the Go types and can break downstream codegen. Regenerate the swagger artifacts to ensure schema names and descriptions match actual code (including single-replica behavior).
| "github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig": { | |
| "github_com_stacklok_toolhive_pkg_transport_types.HeadlessServiceConfig": { |
|
closed because the approach of the original issue is under review |
JAORMX
left a comment
There was a problem hiding this comment.
So, there's a fundamental issue with the headless service that this PR builds on top of.
The headless service (mcp-<name>-headless) selects the MCP server backend pods directly via app: containerName. That means it points to the StatefulSet pods... which are the raw MCP backends, not the proxy runner. The proxy runner is a Deployment with different labels.
This matters because:
-
For stdio transports, backend pods don't listen on the network at all. The
transportTypeRequiresBackendServicesguard skips service creation for stdio, but the StatefulSet'sspec.serviceNamestill references a service that doesn't exist in that case. -
The headless service exposes backend pods directly to the cluster, bypassing the proxy's auth, session management, and routing logic. Anyone in the namespace can resolve
pod-0.mcp-myserver-headless.ns.svc.cluster.localand hit the backend without going through the proxy. -
The random pod selection happens AFTER the initialize request already went through the ClusterIP. So the initialize lands on pod X (via ClusterIP load balancing), but
pickPodBackendURL()stores pod Y (random headless DNS) asbackend_url. Follow-up requests go to pod Y, which never saw the initialize... and you get-32001 session not found. The copilot reviewer flagged this too.
Before building more on top of the headless service, I think we need to step back and reconsider whether this is the right mechanism for session pinning. The headless service was created before this PR but was never actually wired up (the StatefulSet serviceName didn't even match it). We should figure out the right approach before adding more plumbing on top of a broken foundation.
I'm going to open a separate issue to discuss removing or rethinking the headless service.
|
Opened #4668 to track the headless service cleanup/rethink separately. |
Summary
When backendReplicas > 1, the proxy was storing the ClusterIP service URL as backend_url on session initialize. After a proxy-runner restart, Redis-recovered sessions were routed through the ClusterIP, which sent requests to a random pod — one that had never seen the initialize and returned -32001 ("session not found").
Two root causes fixed:
StatefulSet serviceName was set to containerName instead of mcp--headless, so Kubernetes never created pod DNS records.
On initialize, the proxy now picks a random pod ordinal and stores its headless DNS URL (e.g. myserver-0.mcp-myserver-headless.default .svc.cluster.local) as backend_url instead of the ClusterIP. The Rewrite closure already reads backend_url to route follow-up requests, so sessions now survive proxy-runner restarts.
The operator populates a new HeadlessServiceConfig (StatefulSet name, headless service name, namespace, replica count) in ScalingConfig when backendReplicas > 1. Single-replica and non-Kubernetes deployments are unaffected.
Fixes #4575
Type of change
Test plan
task test)task test-e2e)task lint-fix)Changes
Does this introduce a user-facing change?
Special notes for reviewers
Large PR Justification
This is a complete PR that solves a bug, and is an isolated functionality. Cannot be split.