Skip to content

MCPServer proxy fails its kubelet probes and is restarted while the backend is slow to answer GET / #7000

Closed

Description

@alex-feel

Bug description

The operator gives the MCPServer proxy Deployment startup and readiness probes with a 3 s timeout and a liveness probe with a 5 s timeout (cmd/thv-operator/controllers/mcpserver_controller.go:1613-1646). The proxy answers each probe by pinging the backend inline: HealthChecker.ServeHTTP (pkg/healthcheck/healthcheck.go:128) calls CheckHealth(r.Context()) (:134), which calls mcpPinger.Ping (:111), and the pinger waits up to DefaultPingerTimeout, 5 s (pkg/transport/proxy/transparent/pinger.go:27).

So /health takes as long as the backend's GET /, up to 5 s. When the backend needs 3 s or more, the startup and readiness probes time out; at 5 s, liveness times out too, and three liveness failures in a row make the kubelet restart the proxy container. The handler would have answered 200 (healthy, or degraded once the ping times out, healthcheck.go:142-143), but the kubelet gives up first. docs/arch/03-transport-architecture.md:472 says the proxy's own monitor tolerates about 60 seconds of failures so that it does not kill healthy backends prematurely, while the liveness probe restarts the proxy after three failed probes 10 s apart.

We ran into this with a backend that stopped answering GET / for several seconds while it served a long request. The kubelet restarted the proxy in the middle of that request, although the backend was alive and /health would have reported degraded.

Steps to reproduce

  1. Save the test below as pkg/transport/proxy/transparent/health_probe_slow_backend_test.go. It starts the real TransparentProxy in front of an httptest backend whose GET / waits a set delay, then calls /health with clients that time out like the operator's probes.
  2. Run go test -count=1 -v -run TestHealthAnswersWithinOperatorProbeTimeouts ./pkg/transport/proxy/transparent/
health_probe_slow_backend_test.go
package transparent

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

// kubeletProbe mirrors the probes the operator puts on the proxy Deployment
// (cmd/thv-operator/controllers/mcpserver_controller.go): each is a GET /health
// whose client gives up after TimeoutSeconds.
type kubeletProbe struct {
	name    string
	timeout time.Duration
}

var operatorProbes = []kubeletProbe{
	{name: "startup", timeout: 3 * time.Second},
	{name: "readiness", timeout: 3 * time.Second},
	{name: "liveness", timeout: 5 * time.Second},
}

// startProxyInFrontOf starts the real transparent proxy (health check enabled,
// local workload, streamable-http) in front of a backend whose GET / takes
// backendDelay to answer, and returns the proxy's /health URL.
func startProxyInFrontOf(t *testing.T, backendDelay time.Duration) string {
	t.Helper()

	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		select {
		case <-time.After(backendDelay):
			w.WriteHeader(http.StatusOK)
		case <-r.Context().Done():
		}
	}))
	t.Cleanup(backend.Close)

	proxy := NewTransparentProxy("127.0.0.1", 0, backend.URL, nil, nil, nil,
		true, false, "streamable-http", nil, nil, "", false)
	ctx, cancel := context.WithCancel(context.Background())
	if err := proxy.Start(ctx); err != nil {
		cancel()
		t.Fatalf("start proxy: %v", err)
	}
	t.Cleanup(func() {
		cancel()
		stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer stopCancel()
		_ = proxy.Stop(stopCtx)
	})

	return "http://" + proxy.ListenerAddr() + "/health"
}

func getHealth(url string, timeout time.Duration) (int, string, time.Duration, error) {
	client := &http.Client{Timeout: timeout}
	start := time.Now()
	resp, err := client.Get(url)
	if err != nil {
		return 0, "", time.Since(start), err
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	return resp.StatusCode, string(body), time.Since(start), nil
}

// TestHealthAnswersWithinOperatorProbeTimeouts checks that /health answers each
// operator-generated probe before the probe times out.
func TestHealthAnswersWithinOperatorProbeTimeouts(t *testing.T) {
	cases := []struct {
		name         string
		backendDelay time.Duration
		pingTimeout  string
	}{
		{name: "fast backend", backendDelay: 0},
		{name: "backend GET / takes 4s, default ping timeout", backendDelay: 4 * time.Second},
		{name: "backend GET / takes 7s, default ping timeout", backendDelay: 7 * time.Second},
		{name: "backend GET / takes 7s, TOOLHIVE_HEALTH_CHECK_PING_TIMEOUT=2s", backendDelay: 7 * time.Second, pingTimeout: "2s"},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			if tc.pingTimeout != "" {
				t.Setenv(HealthCheckPingTimeoutEnvVar, tc.pingTimeout)
			}
			url := startProxyInFrontOf(t, tc.backendDelay)

			status, body, elapsed, err := getHealth(url, 30*time.Second)
			t.Logf("GET /health without a client timeout: status=%d after %s body=%s err=%v",
				status, elapsed.Round(100*time.Millisecond), body, err)

			for _, p := range operatorProbes {
				status, _, elapsed, err := getHealth(url, p.timeout)
				if err != nil {
					t.Errorf("%s probe (timeout %s): no answer, failed after %s: %v",
						p.name, p.timeout, elapsed.Round(100*time.Millisecond), err)
					continue
				}
				t.Logf("%s probe (timeout %s): status=%d after %s",
					p.name, p.timeout, status, elapsed.Round(100*time.Millisecond))
				if status < 200 || status >= 400 {
					t.Errorf("%s probe: status %d is a probe failure", p.name, status)
				}
			}
		})
	}
}

Expected behavior

/health answers every probe within its timeout whatever the backend's latency, and reports a slow or unreachable backend as degraded in the body, as it already does once the ping times out.

Actual behavior

Output, trimmed:

=== RUN   .../backend_GET_/_takes_4s,_default_ping_timeout
    GET /health without a client timeout: status=200 after 4s body={"status":"healthy",...,"response_time_ms":4001,...}
    startup probe (timeout 3s): no answer, failed after 3s: ... (Client.Timeout exceeded while awaiting headers)
    readiness probe (timeout 3s): no answer, failed after 3s: ... (Client.Timeout exceeded while awaiting headers)
    liveness probe (timeout 5s): status=200 after 4s
=== RUN   .../backend_GET_/_takes_7s,_default_ping_timeout
    GET /health without a client timeout: status=200 after 5s body={"status":"degraded",...}
    startup probe (timeout 3s): no answer, failed after 3s: ... (Client.Timeout exceeded while awaiting headers)
    readiness probe (timeout 3s): no answer, failed after 3s: ... (Client.Timeout exceeded while awaiting headers)
    liveness probe (timeout 5s): no answer, failed after 5s: ... (Client.Timeout exceeded while awaiting headers)
--- FAIL: TestHealthAnswersWithinOperatorProbeTimeouts (38.05s)
    --- PASS: .../fast_backend (0.01s)
    --- FAIL: .../backend_GET_/_takes_4s,_default_ping_timeout (14.02s)
    --- FAIL: .../backend_GET_/_takes_7s,_default_ping_timeout (16.01s)
    --- PASS: .../backend_GET_/_takes_7s,_TOOLHIVE_HEALTH_CHECK_PING_TIMEOUT=2s (8.01s)

With a 4 s backend the checker itself reports healthy and the 3 s probes still fail. Setting TOOLHIVE_HEALTH_CHECK_PING_TIMEOUT=2s makes every probe pass, so the inline ping is what holds the response.

Environment (if relevant)

  • OS/version: seen in a cluster with an operator-managed MCPServer; reproduced with the unit test above (Go 1.27.0, windows/amd64)
  • ToolHive version: seen on v0.53.0; reproduced at v0.59.0 (1710945) and main (20bc1a1). healthcheck.go, pinger.go, transparent_proxy.go and the probe values are unchanged from v0.53.0 to main; line numbers are at main.

Additional context

A fix is ready and the PR follows: HealthChecker.ServeHTTP stops pinging inline and answers from the last result of the background monitor (monitorHealth, pkg/transport/proxy/transparent/transparent_proxy.go:1458, which already runs CheckHealth on an interval once the server is initialized), keeping the degraded detail in the body. Raising the operator's probe timeouts above the ping timeout would also avoid the restart, but it ties two components' constants together and breaks again when TOOLHIVE_HEALTH_CHECK_PING_TIMEOUT is raised.

Related: #5299 and #5300 (startup probe for slow-starting backends), #4084 and #4108 (the TOOLHIVE_HEALTH_CHECK_* settings); the open #4844 also changes monitorHealth. I can share the full output at both refs if useful.

Activity

  1. added
    needs-triage
    on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions