Skip to content

test(upstream): count only the retire fixture's own endpoint traffic - #1934

Merged
Dumbris merged 5 commits into
mainfrom
fix/retire-fixture-endpoint-isolation
Nov 19, 2026
Merged

Dumbris merged 5 commits into
mainfrom
fix/retire-fixture-endpoint-isolation

Conversation

@Dumbris

@Dumbris Dumbris commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

TestRetire_HTTPDialParked_OldEndpointReceivesNothing/http/remove failed once in the shuffled unit-test job on #1931 (job 135134947938, seed 1795038088268204092) with expected: 0, actual: 3 requests and 0 Authorization headers. This PR makes the retire fixture count only its own endpoint's traffic. It is a test-only change; no production code is touched.

Classification: fixture contamination, not a retirement defect

  • The retired instance did not send it. The instance under test only ever sends Authorization: Bearer qa-secret…, and the CI run counted 0 Authorization headers next to the 3 requests.
  • The test is clean in isolation. On main 898572804: 300/300 runs under -race and 100/100 with GOMAXPROCS=1 (6 subtests each). The full package with the CI seed passes 3/3 on macOS and 6/6 on Linux (Docker, ephemeral port range narrowed to 1,024 ports).
  • Senders seen directly. In a scratch copy, every upstream request was tagged with its server and creating test, and a trap bound the free ports during the retire subtests. With only internal/upstream running, the trap caught 0 requests. With server, runtime, httpapi and four more packages running in parallel, as go test ./... does on CI, it caught 535 requests in two iterations:
    • POST / initialize with no Authorization, tagged e.g. github|TestCallTool_ProfileV3_RestDispatchPreservesTypedRefusal. 29 of the 30 tagged tests are in internal/server; the 30th tag carried a server name but no test name.
    • GET / listen streams and DELETE / closes with stale session ids.
  • Which these are. Clients from internal/server tests keep reconnecting to the ports of their own closed counting upstreams. When the OS reuses one of those ports for this fixture, the traffic lands here.
  • What is shown and what is inferred. The multi-package run shows this traffic exists and has the CI failure's shape: requests without credentials, three per reconnect attempt. That this exact traffic caused the historical CI run is inferred, not traced; the CI job kept no per-request record.

The same class as the stray-client isolation in #1918's dc864055d, here across processes.

Fix

  • The fixture serves its endpoint under a unique path (/fx-<random>/mcp, or /fx-<random>/sse with WithStaticBasePath).
  • It counts a request when its path carries that token, with or without credentials, or when it carries the fixture's own credential on any path. httpServerConfig now gives each fixture a unique bearer.
  • Origin-level OAuth paths are counted whoever sends them, so the fixture fails closed. These are /.well-known/* and mcp-go's default /authorize, /token and /register, which an OAuth attempt may reach without the token or a credential. This was review round 1, from gpt-6.1-sol.
  • Everything else is answered 404 and kept in strays().
  • The handler and every field are in place before Start.
  • The zero-request assertions are unchanged.

New tests:

  • TestRetire_HTTPDialParked_StrayTrafficOnThePortIsNotTheOldEndpoint runs the parked-dial scenario while a stranger sends POST /, GET / and DELETE / to the port. With the old fixture it fails exactly like CI, for both http and sse: expected: 0, actual: 3.
  • TestCountingUpstream_CountsItsEndpointAndItsCredentialAnywhere holds the controls. A request to the endpoint without credentials is counted. The fixture's credential on another path is counted. Origin-level OAuth paths are counted. Strangers on other paths, with or without their own credential, are not counted.

Verification (macOS, -race unless noted)

Run Result
-run 'Retire|CountingUpstream' -count=20 ok
same, GOMAXPROCS=1 -count=10 ok
full package, CI seed, CI skip list exit 0
full package, CI seed, under CPU load, 3 runs exit 0 ×3
full package, -shuffle=on -count=2 ok
golangci-lint v2 (.github/.golangci.yml), bare and --build-tags server, new from origin/main 0 issues each

One earlier full-package run with the CI seed reported FAIL while both lint runs loaded the machine. Its output was not captured: the command kept only the last line. The later runs listed above used the final handler ordering and all passed. That failure is reported here as uncaptured, not as explained.

A note on the barrier itself: disabling the retired checks in dialgate, plus connect cancellation in the managed client, still produced no traffic in the parked scenario, because further guards stop the dial. That is unchanged by this PR. The fixture's detection is covered by the control test above.

Review

Round Reviewer SHA Result
1 opencode gpt-6.1-sol, fixture chunk 8b0057b05 1 medium: origin-level OAuth paths uncounted. Fixed in 6e7f49ad8
2 gpt-6.1-sol, fixture / tests 6e7f49ad8 CLEAN / 2 P2: exact stray counts, missing controls
2 Claude Opus 5.5 6e7f49ad8 same medium, plus 2 low. Fixed in 467da1fd5
3 Claude Opus 5.5 467da1fd5 CLEAN: 11 filter mutations killed; real connects and the full OAuth fallback counted, 0 strays
3 gpt-6.1-sol, tests 467da1fd5 1 P3: shared stray marker. Fixed in c1690a366
4 gpt-6.1-sol c1690a366 P3 fixed; 1 P2: unbounded hook waits. Fixed in e62c7610c. The first try returned no verdict and was not counted
5 gpt-6.1-sol e62c7610c CLEAN
5 Claude Opus 5.5 e62c7610c CLEAN: 13 filter and recording mutations killed

Follow-ups, not blocking:

  • Add a control row for a foreign credential on the endpoint path, so the auth counter's "any Authorization" rule is pinned. Opus low; the request counter already catches it.
  • Rewrap one 113-character comment line.

Not in this PR

The internal/server tests that leave reconnecting clients behind are the source of the stray traffic. They are a separate cleanup.

Merge condition

Both reviewers are clean on e62c7610c. Merge that exact SHA once CI is green; if the head moves, review it again. Auto-merge is not armed.

`go test ./...` runs packages in parallel. Other packages' test clients
keep reconnecting to the ports of their own closed fixtures (POST /
initialize, GET / listen stream, DELETE / close, no credentials). When
the OS hands such a port to the retire fixture, that traffic was counted
as requests to the old endpoint: CI job 135134947938 saw 3 requests and
0 Authorization headers in TestRetire_HTTPDialParked_OldEndpointReceivesNothing/http/remove.

The fixture now serves its endpoint under a path unique to it and
counts a request when its path carries that token (with or without
credentials) or when it carries the fixture's own credential on any
path. Everything else is answered 404 and kept apart as a stray. The
handler is installed before Start. The zero-request assertions are
unchanged.

New tests: the parked-dial scenario with stray traffic on the port
(fails on the old fixture with 0 expected, 3 actual), and the fixture's
controls (endpoint traffic without credentials and the fixture's
credential on another path are both counted).
Review round 1 (gpt-6.1-sol): an OAuth attempt may request
/.well-known/* or mcp-go's default /authorize, /token and /register
without the endpoint's path or a credential. Those paths are now counted
whoever sends them, so the fixture fails closed; the control test
covers them.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: e62c761
Status: ✅  Deploy successful!
Preview URL: https://52283b30.mcpproxy-docs.pages.dev
Branch Preview URL: https://fix-retire-fixture-endpoint.mcpproxy-docs.pages.dev

View logs

Review round 2 (gpt-6.1-sol chunk 2 P2 x2, Opus 5.5 medium + 2 low):
- the stray test and the control test mark their injected traffic with a
  unique query and assert it is present, not that it is the only stray,
  so a real reconnecting client on a reused port cannot fail them;
- the controls check one request at a time with its own counter delta,
  including an authenticated endpoint request, /authorize and /register;
- the control asserts the instance carries the credential the fixture
  recognises and that credentials differ per fixture;
- comment reflowed; note that originOAuthPath must grow if the fixture
  ever advertises OAuth metadata.
Review round 3 (gpt-6.1-sol P3): the two root-path strangers shared a
marker, so a fixture that dropped foreign-credential requests without
recording them would still pass. Each stranger now has its own marker
and all three are asserted. Comment reflowed (Opus 5.5 round 3 note).
Review round 4 (gpt-6.1-sol P2): the parked and in-section waits blocked
forever if Connect failed before reaching its hook. waitHook ends the
wait with the connect error, or after 20 s.
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/retire-fixture-endpoint-isolation

Available Artifacts

  • archive-darwin-amd64 (33 MB)
  • archive-darwin-arm64 (29 MB)
  • archive-linux-amd64 (20 MB)
  • archive-linux-arm64 (18 MB)
  • archive-windows-amd64 (32 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-goMJJVVB.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 44436595651 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@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
Dumbris merged commit 0b228f9 into main Nov 19, 2026
51 checks passed
Dumbris added a commit that referenced this pull request Nov 19, 2026
…ient outlives its test (#1936)

## Summary

Test-only. `internal/server` fixtures created `upstream.Manager`s 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".
- `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.
- `golangci-lint run --config .github/.golangci.yml
--new-from-rev=origin/main ./...`, bare and `--build-tags server`: 0
issues.
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