Skip to content

test(server): shut down fixture upstream managers so no watcher or client outlives its test - #1936

Merged
Dumbris merged 1 commit into
mainfrom
test/server-fixtures-shutdown-managers
Nov 19, 2026
Merged

Dumbris merged 1 commit into
mainfrom
test/server-fixtures-shutdown-managers

Conversation

@Dumbris

@Dumbris Dumbris commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Test-only. internal/server fixtures created upstream.Managers and never shut them down. Each one kept its network-recovery watcher (#1931) running, and its clients kept reconnecting to their fixture's closed port, for the rest of the package run. Those reconnects are the stray traffic that #1918 (fresh-process allocation tests) and #1934 (retire-fixture isolation) worked around. This PR fixes the source.

The numbers below come from the end of a full go test -v -race -timeout 60m -coverprofile … -skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint" ./internal/server/ run:

goroutines (*networkRecovery).run startOAuthEventMonitor lumberjack millRun
main 58a824e 3196 1273 44 276
this branch 739 0 0 0

To find the sources, I labelled each watcher goroutine with the test frame that created it (a temporary local patch, not committed). Every leaked watcher came from a direct upstream.NewManager in a test file. createTestProxyWithRuntimeCfg alone accounted for about 70% of them. None came from a runtime or server that wasn't closed.

Changes

  • newTestUpstreamManager / shutdownUpstreamOnCleanup (upstream_fixture_cleanup_test.go): all 37 direct upstream.NewManager calls in the package now call ShutdownAll when the test ends. This includes the shared createTestProxyWithRuntimeCfg.
  • stopUpstreamBeforeFixtureClose: some fixtures start their upstream after the manager exists: startCountingUpstream and the prompt-upstream helpers in mcp_prompt_scope_test.go and scope_retained_effects_test.go. They now remove the client in a cleanup registered after the listener's close, so it runs first: the client disconnects while the stub still listens and never redials a closed port. The old DisconnectAll cleanups in the prompt loops ran after the fixture had already closed.
  • mcp_code_execution_test.go (package server_test) defers the shutdown so it runs before the storage close it depends on.
  • scope_latency_test.go inlines the shutdown, because scope-latency.yml copies that one file onto the merge-base checkout, where the helper doesn't exist.
  • Guard: a new TestMain (leak_guard_main_test.go) fails an otherwise passing run if any (*networkRecovery).run goroutine is still alive after the last test. It polls for up to 10s and prints the first 5 stacks. I checked that it catches a leak: with the helper's shutdown commented out, -run TestAggregatedPrompt_ScopeUsesCanonicalOwner fails with "2 upstream.Manager network-recovery watcher(s) still running".
  • Socket E2E tests: TestE2E_TrayToCore_UnixSocket, TestE2E_DualListener_Concurrent and TestE2E_SocketPermissions never cancelled Start's context or shut the server down, an old workaround for a shutdown race. Each left a runtime and its manager running, and the guard failed the E2E job on those 3 watchers. They now stop through stopSocketE2EServer: cancel, wait for Start to return, then Shutdown. They pass -race -count=3, and a full -race -run TestE2E run leaves 0 watchers.
  • MCPPROXY_NETWORK_RECOVERY=off is not set anywhere.

No production code changed. The leaks were all in test fixtures.

Found, not fixed (production shutdown gap)

The 739 goroutines that remain are mostly 227 × (*Server).forwardRuntimeStatus and 227 × (*Server).listenForRoutingModeRefresh. NewServer starts both (server.go:488, :504), and Server.Shutdown stops neither:

  • listenForRoutingModeRefresh ranges over a SubscribeEvents channel that is never unsubscribed.
  • forwardRuntimeStatus ranges over Runtime.statusCh, which nothing closes.

They sit idle on a channel receive and send no network traffic. They are harmless in a real process, which exits after Shutdown. In tests they are still 2 leaked goroutines per server. I left them for a separate production change.

Verification

  • Full internal/server race run: ok … 1457.449s coverage: 83.5%, and the guard passes.
  • go test -v -race -timeout 10m ./internal/server -run TestE2E: ok … 332.9s, and the guard passes.
  • golangci-lint run --config .github/.golangci.yml --new-from-rev=origin/main ./..., bare and --build-tags server: 0 issues.

…ient outlives its test

internal/server fixtures built upstream.Manager instances and never shut
them down. Each kept its network-recovery watcher (#1931) ticking and its
clients reconnecting to their fixture's closed port for the rest of the
package run: 1273 watchers and 3196 goroutines were still alive after the
last test of a full race run, and the reconnecting clients sent the stray
requests that #1918 and #1934 worked around.

- newTestUpstreamManager / shutdownUpstreamOnCleanup: every direct
  upstream.NewManager in the package now shuts down with ShutdownAll at
  test end (createTestProxyWithRuntimeCfg was 70% of the leak on its own).
- stopUpstreamBeforeFixtureClose: fixtures that start an upstream after
  the manager (startCountingUpstream, prompt-upstream helpers) remove the
  client before the listener closes, so it never redials a closed port.
  The DisconnectAll cleanups these replace ran after the fixture closed.
- mcp_code_execution_test.go (package server_test) defers the shutdown
  before its deferred storage close; scope_latency_test.go inlines it
  because the scope-latency workflow copies that file alone onto the
  merge base.
- TestMain fails a passing run that leaves any (*networkRecovery).run
  goroutine behind (polled for 10s, first stacks printed).

After: 0 watchers and 739 goroutines at the end of the same run.
@cloudflare-workers-and-pages

Copy link
Copy Markdown

@Dumbris
Dumbris enabled auto-merge (squash) November 19, 2026 11:22
@github-actions

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: test/server-fixtures-shutdown-managers

Available Artifacts

  • archive-darwin-amd64 (33 MB)
  • archive-darwin-arm64 (30 MB)
  • archive-linux-amd64 (20 MB)
  • archive-linux-arm64 (18 MB)
  • archive-windows-amd64 (33 MB)
  • archive-windows-arm64 (29 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (29 MB)
  • installer-dmg-darwin-arm64 (26 MB)
  • smart-mcp-proxymcpproxy-goPREPYN.dockerbuild (0 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 44513075638 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@Dumbris
Dumbris merged commit 6251956 into main Nov 19, 2026
52 of 53 checks passed
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Dumbris added a commit that referenced this pull request Nov 19, 2026
TestE2E_TrayToCore_UnixSocket, TestE2E_DualListener_Concurrent and
TestE2E_SocketPermissions never shut their server down, so each left its
upstream manager's network-recovery watcher running. Since the TestMain
leak guard (#1936) that fails the -run TestE2E job on main. Shut each
server down in a defer that runs before the socketE2EMutex unlock.
Dumbris added a commit that referenced this pull request Nov 19, 2026
TestE2E_TrayToCore_UnixSocket, TestE2E_DualListener_Concurrent and
TestE2E_SocketPermissions started a Server and deliberately never shut it
down. Each one left its runtime, upstream manager and network-recovery
watcher running, so the TestMain guard from #1936 failed the E2E job
(`-run TestE2E`) with "3 upstream.Manager network-recovery watcher(s)
still running". #1936's sweep ran with `-skip E2E` and never saw them.

stopSocketE2EServer shuts the server down, cancels its context and waits
for Start to return. It is deferred after the socketE2EMutex unlock, so it
runs while the mutex is held, before the next socket test starts.

Verified: the guard fails with the three tests on the old file and passes
with this change; the CI E2E command passes.
Dumbris added a commit that referenced this pull request Nov 19, 2026
TestE2E_TrayToCore_UnixSocket, TestE2E_DualListener_Concurrent and
TestE2E_SocketPermissions started a Server and deliberately never shut it
down. Each one left its runtime, upstream manager and network-recovery
watcher running, so the TestMain guard from #1936 failed the E2E job
(`-run TestE2E`) with "3 upstream.Manager network-recovery watcher(s)
still running". #1936's sweep ran with `-skip E2E` and never saw them.

stopSocketE2EServer shuts the server down, cancels its context and waits
for Start to return. It is deferred after the socketE2EMutex unlock, so it
runs while the mutex is held, before the next socket test starts.

Verified: the guard fails with the three tests on the old file and passes
with this change; the CI E2E command passes.
Dumbris added a commit that referenced this pull request Nov 20, 2026
…wn (#1941)

## Problem

`NewServer` starts two goroutines that `Server.Shutdown` never stopped:

- `forwardRuntimeStatus` ranges over `Runtime.StatusChannel()`. Nothing
closes that channel.
- `listenForRoutingModeRefresh` ranges over a `SubscribeEvents()`
channel. `Shutdown` never unsubscribed it.

In a real process this does no harm because the process exits. But every
server that is shut down inside a running process (tests, an in-process
restart) leaves two idle goroutines behind for the rest of the process.

## Fix (`internal/server/server.go`)

- `Server` now stores the routing subscription (`routingEventsCh`), and
`Shutdown` unsubscribes it. `UnsubscribeEvents` closes the channel,
which ends the listener's range loop. The listener's own deferred
`UnsubscribeEvents` then finds no subscription left and does nothing.
- The forwarder now `select`s on a server-owned `listenersDone` channel,
which `Shutdown` closes. The runtime's `statusCh` stays open, so a
status send can never hit a closed channel.
- Both steps run inside the existing `s.shutdown` guard, so a second
`Shutdown` is still a no-op and `listenersDone` is closed only once.

## Tests

- New `TestShutdown_StopsServerListenerGoroutines`
(`internal/server/shutdown_listeners_test.go`): builds a server with
`NewServer`, calls `Shutdown`, and polls (10s deadline) until neither
frame is running above the count taken before `NewServer`. It then calls
`Shutdown` a second time. It failed before the fix (`1/1` of each still
running after 10s) and passes after it (`-race -count=5`).
- Full `go test -race -timeout 60m -skip
"E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint"
./internal/server/` passes on both trees. Goroutines still running at
the end of the run (counted by a local-only `TestMain` that was not
committed):

| | total | `forwardRuntimeStatus` | `listenForRoutingModeRefresh` |
|---|---|---|---|
| `main` 58a824e | 3194 | 227 | 227 |
| this branch | 2736 | **0** | **0** |

- golangci-lint v2 with `.github/.golangci.yml`, bare and `--build-tags
server`, with `--new-from-rev=origin/main`: 0 issues.

## Not in this PR

The `TestMain` leak guard from #1936 (`leak_guard_main_test.go`) is not
on `main` yet. Once both PRs land, it can also check these two frames,
since a full run now ends at zero.

## Also: E2E job red on `main` since #1936

The `-run TestE2E` job has failed on `main` since #1936 (6251956,
201d373): `FAIL: 3 upstream.Manager network-recovery watcher(s) still
running`. I traced the creators with pprof labels. All three are the
socket E2E tests (`TestE2E_TrayToCore_UnixSocket`,
`TestE2E_DualListener_Concurrent`, `TestE2E_SocketPermissions`), which
deliberately never shut their server down. Each test now shuts its
server down in a `defer` that runs before the `socketE2EMutex` unlock.
The CI E2E command (`go test -v -race -timeout 10m ./internal/server
-run TestE2E -skip '…'`) now passes locally (255s), and the three tests
pass with `-race -count=3`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants