Skip to content

Route MCP sessions to specific StatefulSet pods via headless DNS - #4638

Closed
yrobla wants to merge 2 commits into
mainfrom
issue-4575
Closed

yrobla wants to merge 2 commits into
mainfrom
issue-4575

Conversation

@yrobla

@yrobla yrobla commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

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:

  1. StatefulSet serviceName was set to containerName instead of mcp--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

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

Changes

File Change

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.

@github-actions github-actions Bot added the size/S Small PR: 100-299 lines changed label Apr 7, 2026
@codecov

codecov Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 55.07246% with 31 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.86%. Comparing base (3a6c0c1) to head (b3af8f3).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/transport/http.go 35.71% 14 Missing and 4 partials ⚠️
...g/transport/proxy/transparent/transparent_proxy.go 73.33% 4 Missing and 4 partials ⚠️
pkg/runner/runner.go 0.00% 3 Missing ⚠️
pkg/transport/factory.go 0.00% 2 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

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

@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 7, 2026
@yrobla
yrobla requested a review from Copilot April 7, 2026 15:58
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 7, 2026
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 7, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 transformation

Alternative:

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.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 7, 2026
@github-actions
github-actions Bot dismissed their stale review April 7, 2026 16:04

Large PR justification has been provided. Thank you!

@github-actions

github-actions Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

✅ Large PR justification has been provided. The size review has been dismissed and this PR can now proceed with normal review.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 serviceName to 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
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 8, 2026
@yrobla
yrobla requested a review from Copilot April 8, 2026 08:27
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 8, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread pkg/transport/http.go
Comment on lines +326 to +330
// Inject Redis-backed session storage for cross-replica session sharing.
if t.sessionStorage != nil {
proxyOptions = append(proxyOptions, transparent.WithSessionStorage(t.sessionStorage))
}

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
// Inject Redis-backed session storage for cross-replica session sharing.
if t.sessionStorage != nil {
proxyOptions = append(proxyOptions, transparent.WithSessionStorage(t.sessionStorage))
}

Copilot uses AI. Check for mistakes.
Comment on lines +242 to +257
// 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,
}

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

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).

Copilot uses AI. Check for mistakes.
Comment on lines 447 to 451
spec := appsv1apply.StatefulSetSpec().
WithSelector(metav1apply.LabelSelector().
WithMatchLabels(map[string]string{"app": containerName})).
WithServiceName(containerName).
WithServiceName(fmt.Sprintf("mcp-%s-headless", containerName)).
WithTemplate(podTemplateSpec)

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment thread docs/server/swagger.yaml
Comment on lines +991 to +996
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

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
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.

Copilot uses AI. Check for mistakes.
Comment thread docs/server/swagger.json
Comment on lines +1043 to +1044
"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",

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
"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",

Copilot uses AI. Check for mistakes.
Comment thread docs/server/docs.go
},
"type": "object"
},
"github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig": {

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

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).

Suggested change
"github_com_stacklok_toolhive_pkg_runner.HeadlessServiceConfig": {
"github_com_stacklok_toolhive_pkg_transport_types.HeadlessServiceConfig": {

Copilot uses AI. Check for mistakes.
@yrobla

yrobla commented Apr 8, 2026

Copy link
Copy Markdown
Contributor Author

closed because the approach of the original issue is under review

@yrobla yrobla closed this Apr 8, 2026

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

  1. For stdio transports, backend pods don't listen on the network at all. The transportTypeRequiresBackendServices guard skips service creation for stdio, but the StatefulSet's spec.serviceName still references a service that doesn't exist in that case.

  2. 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.local and hit the backend without going through the proxy.

  3. 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) as backend_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.

@JAORMX

JAORMX commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator

Opened #4668 to track the headless service cleanup/rethink separately.

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

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Backend routing breaks after proxy runner restart with backendReplicas > 1

5 participants