Skip to content

fix(upstream): reconnect remote servers as soon as the network returns - #1931

Merged
Dumbris merged 13 commits into
mainfrom
fix/1929-network-recovery
Nov 18, 2026
Merged

Dumbris merged 13 commits into
mainfrom
fix/1929-network-recovery

Conversation

@Dumbris

@Dumbris Dumbris commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Description

Release 1 of the recovery work for #1929: remote HTTP/SSE upstreams come back on their own within seconds of the network returning, instead of sitting in Error for up to 30 minutes after a laptop wakes.

Cause. While the machine sleeps, every reconnect attempt fails on DNS lookups or timeouts and advances the backoff. After 20 failures the client gives up and only the supervisor's 30-minute probe retries it (types.GaveUpProbeInterval). Nothing reset that when the network came back. On top of that, an HTTP initialize timeout was rewritten into the stdio-only text "produced no stderr output … help banner" without wrapping the deadline. So it was not even recognised as a network failure.

Changes

  • Network failures are recorded as such. A connect failure before any upstream answered (DNS, dial, refused, timeout; core.IsNetworkError) is recorded with StateManager.SetNetworkError and reported as ConnectionInfo.NetworkFailure. It advances the backoff exactly as before, and every other state write clears it.
  • A connectivity watcher in the upstream manager (internal/upstream/network_recovery.go) handles servers whose current failure is a network failure:
    • It probes each server's host, or the HTTP proxy it goes through, with a bare TCP dial: every 10 s, and every 30 s after 5 minutes of failures. The probe sends no request and no credentials.
    • When probes that were failing start to succeed, the outage is over: the watcher resets the backoff and reconnects at once.
    • A system wake (a tick far later than scheduled, measured on the wall clock) or a change of the machine's network addresses gives one attempt on the current ladder once the host answers. The normal backoff then resumes ([Bug]: Upstream reconnect has no backoff — supervisor re-dials failed servers every 30s forever, hammering dead remotes (~9k req/day) #1013).
    • It reconnects one server at most every 30 s; a restore inside that window is deferred, not dropped.
  • The watcher leaves alone servers that are disabled or quarantined, awaiting sign-in, failed on credentials or OAuth, parked as permanently broken (Deterministic, unrecoverable connection failures retry forever (55 attempts / 19h on one server) #1145), inside a Retry-After window ([Bug]: connect retries ignore Retry-After on 429 (remaining ask from #1013) #1040), logged out, retired, removed or local (stdio). A server whose host answers all along while the server itself keeps failing is left to the normal backoff.
  • Retry budget: the first 3 watcher reconnects after a server last connected are immediate and may reset the backoff. After that no reset is granted and the spacing doubles up to 30 minutes, so a remote that is only reachable on and off, or a network that keeps changing, cannot keep restarting the short retry ladder. The budget is restored by any successful connect, and the spacing is measured on the wall clock so sleep time counts.
  • Expired OAuth tokens: the recovery lifts the OAuth refresh coordinator's transient cooldown for the server's credential (RefreshCoordinator.ClearTransientCooldown). Refreshes that failed while offline therefore do not make the reconnect wait up to 5 minutes. A revoked grant stays latched.
  • Proxies: behind an http:// proxy, an https upstream is probed with CONNECT and must get a 2xx back. A plain-http upstream, or one behind an https:// or SOCKS proxy, is probed at the proxy only.
  • Lifecycle: reconnects the watcher starts are bounded by the manager's shutdown context and the health loop's stop channel, and are waited for on shutdown. The backoff clear is atomic with the eligibility check (StateManager.ClearNetworkBackoff).
  • Kill switch: MCPPROXY_NETWORK_RECOVERY=off turns the watcher off.
  • HTTP/SSE initialize timeout: the error now names the host (never the path, query or userinfo) and keeps the typed deadline in the chain. It is classified MCPX_HTTP_TIMEOUT, not the stdio handshake timeout.
  • Docs: "Reconnecting after a failure" in docs/configuration/upstream-servers.md, and the new variable in docs/configuration/environment-variables.md.

Not in this release (from the issue's proposal list): reconnect_on_use on by default, pausing the retry loop while offline, a configurable maximum backoff, and native OS wake/network notifications. Hence Refs, not Closes.

Testing

  • I have tested these changes locally
  • I have added/updated tests that prove my fix is effective or my feature works
  • All existing tests pass

End to end (internal/upstream/network_recovery_integration_test.go). Real managed clients reach the repo's OAuth/MCP test server through a TCP relay the test turns off and on.

Case Result after the network returned
Static-header + OAuth server, both gave up during the outage, production watcher settings both Ready in 3.0 s (limit 60 s)
Same test with the reconnect neutered fails: still in Error past 60 s
OAuth token expired overnight, plus a refresh cooldown left by an offline refresh Ready in 302 ms, token refreshed
Same test with the cooldown lift removed fails: does not recover within 60 s
Repeated network changes, 3 cycles (short and gave-up outages), both servers 26–203 ms each, at most one watcher reconnect per server per return, none while down
Rejected static header / rejected OAuth token exactly one watcher reconnect, then back to awaiting sign-in / the OAuth path, no loop

Unit tests run the watcher on a fake clock, covering:

  • outage then restore, a single failed probe, and a dead-but-reachable remote that is never reset;
  • wake and network change;
  • deferral inside the spacing, and the slow probe cadence;
  • the budget: an intermittent remote gets exactly 3 resets and at most 12 reconnects in 2 h, a flapping network is budgeted and never resets, a connection restores the budget, and a connection missed between ticks still counts;
  • a backwards clock step;
  • probes shared per address, and the CONNECT probe through a fake proxy.

Managed-client tests cover:

  • eligibility, including disabled, quarantined, logged out, Retry-After, OAuth, terminal and retired servers;
  • that the atomic backoff clear never overwrites a newer state;
  • that shutdown and Disconnect are honoured;
  • that the refresh cooldown is lifted.

The refresh-coordinator tests show the cooldown clear keeps the terminal latch. The core test checks the HTTP timeout wording and its classified code.

Live, on the real mcpproxy serve binary built at d4187a1c4. A static-header upstream sat behind a relay process that was killed and restarted; the core was frozen with SIGSTOP/SIGCONT as a stand-in for sleep.

Scenario Back to Ready
60 s outage 6.8 s
Network returned while the core was frozen 60 s 0.29 s after resume ("System wake detected", 67 s gap)
Three 40 s outages 4.8 s, 4.9 s, 4.8 s

Not covered: a real macOS sleep/wake cycle. SIGSTOP stands in for it, and wake is detected from the clock, not from native OS notifications.

Race and lint:

  • go test -race ./internal/upstream/... ./internal/oauth/... passes at 3d04f8ae2; ./internal/upstream/... again at d4187a1c4, and ./internal/upstream at 41b0117cb.
  • golangci-lint with .github/.golangci.yml, bare and with --build-tags server: 0 issues.

Independent review by an Opus 5.5 agent with fresh context, three rounds:

  • Round 1: 3 MAJOR and 4 MINOR findings, all fixed.
  • Round 2: CLEAN, with 2 MINOR fixed.
  • Round 3: CLEAN, with 1 MINOR fixed.

Release QA follow-up (881713a3d, db3083075, 2468ca3a3).

Connected OAuth server with a stalled token refresh (QA cooldown-503):

  • The scenario: an OAuth server stays connected while its token is expired and the token endpoint answers 503, so every refresh fails and the refresh cooldown grows. Then the network drops.
  • Before, recovery waited out that cooldown: 136.5 s and 166.1 s to the first successful call on the QA harness.
  • The watcher now handles this state too. When the network demonstrably returns, it lifts the cooldown and runs one refresh, without touching the connection. invalid_grant stays latched; quarantined, disabled and logged-out servers are excluded; the same budget applies.
  • An outage first noticed by the health check, or by a failing call, is now recorded as a network failure. The watcher also keeps an outage it already observed across brief state changes.

Operator wording (verified live on a 41b0117cb core and a new core side by side):

  • A network outage was a red failure; it now reads amber Reconnecting: <cause>, with CLI STATUS Connecting and the next attempt time in health.detail. doctor no longer lists it, and the Web UI shows an amber "Reconnecting automatically" panel.
  • An expired token whose refresh is being retried now shows "Token refresh pending", not "Token expired" + Sign in.
  • A genuine sign-in still shows "Sign-in required" + Sign in.

Results:

  • Integration test of the QA scenario: first successful call 0.25 s after restore (fails past 60 s without the refresh mode).
  • Same with a health-check-noticed outage: 0.25 s (fails past 60 s without the round-4 fixes).
  • QA harness at db3083075 (same production code as head 2468ca3a3):
    • cooldown-503 (180 s / 30 s): 13.2 s and 14.5 s, PASS;
    • long outage (120 s / 180 s): 4.8 s and 6.1 s, PASS;
    • 65-minute outage, static server: 1605.8 s on main versus 2.2 s with this PR;
    • 4 sleep/wake cycles: 8/8 calls within 1.5 s.

Review: Opus 5.5 rounds 4 and 5. Round 4 found 1 MAJOR and 3 MINOR, all fixed except the refresh-cap note below; round 5 was CLEAN.

Windows (da121e773, f65e58892): the integration tests timed out on the Windows runner. Windows words socket failures differently ("actively refused", "forcibly closed by the remote host"), so an outage was not recognised. The classifiers now decide a typed *net.OpError by type: a timeout is a soft miss, anything else is a hard failure. The Windows phrases were added too. A TLS alert from the peer (Op "remote error", e.g. a rejected client certificate) is excluded, because it is a credential fault. Opus round 6: CLEAN.

Single-server surface /mcp/s/<server> stale after a token stall (99bf90d3c, 8c35f9c27; QA int8 observation, reproduced on main 6370f1f):

  • The defect predates this PR. A catalogue rebuild (servers.changed) that ran while a connected server's tools/list failed, because its token refresh was failing, published the catalogue without that server's tools.
  • Nothing republished them after the server recovered on the same connection. /mcp/s/<server> listed only describe_tool, and its tools answered "tool not found", while /mcp router calls worked.
  • On main the surface was still stale more than 120 s after the token endpoint recovered.
  • The fix has three parts:
    • upstream.Manager.DiscoverToolsWithFailures names the connected servers whose listing failed.
    • While any exist, the direct rebuild is retried (5 s doubling to 30 s), at most 6 times. Each retry lists every connected server, so a server that fails for good cannot keep the fleet polled.
    • Every upstream OAuth token save (Runtime.AddTokenSavedObserver, any refresh path) rebuilds at once while such a server is pending. This covers the network watcher's direct refresh, which emits no oauth.token_refreshed, and the time after the retries stop.
  • Tests:
    • TestSingleServerSurface_RecoversAfterATransientListingFailure
    • TestDirectRebuildRetry_BacksOffAndStopsOnClose
    • TestDirectRebuildRetry_GivesUpThenRebuildsOnTokenRefresh
    • TestTokenSavedObserversRunOffTheSavePath

Clocks on the 8c35f9c27 tree (isolated live core plus fixtures, T0 = token endpoint healthy or network back, calls polled every ~0.5 s):

Scenario Token refresh Router call Catalogue republished Scoped call
cooldown-503, 180 s of 503s then a 30 s outage +0.3 s +0.9 s not needed +0.0 s
long outage, 120 s of 503s then a 180 s outage via reconnect +0.8 s +0.4 s +0.8 s
45 s of 503s, rebuild during the stall +32.9 s +33.0 s +32.9 s +33.0 s
195 s stall, past the retry budget +122.9 s +123.0 s +122.9 s (1 ms after) +123.0 s

The scoped surface now republishes within 1 ms of the refresh. The 33 s and 123 s rows measure the refresh manager's provider backoff after an outage of the token endpoint alone, with the network up, which this PR leaves as it was.

Review: Opus round 7 asked for the retry cap, the timer-reference fix and the TLS-alert exclusion, all done. Round 8: CLEAN. Race tests pass for ./internal/server (40 m timeout), ./internal/runtime and ./internal/upstream/.... Lint reports 0 new issues in both editions.

Known gaps, by the reviewer and me:

  • A plain-http upstream, or one behind an https:// or SOCKS proxy, is probed at the proxy only, so a local proxy that stays up still hides an outage there.
  • A microsecond window lets a manual Disconnect of a server whose health loop never started (never connected) be followed by the watcher's reconnect.
  • The early refresh does not consult the refresh manager's "max retries exceeded" state. After that cap, a restore or wake can still send one refresh, within the watcher budget. The reviewer accepted this.
  • A mistyped host is worded "Reconnecting: …" (status stays needs_config, action Edit URL).
  • Aggregated prompts are rebuilt only on servers.changed, so a server whose prompts/list failed during a token stall stays missing from them until the next server change (follow-up).
  • (Opus r8) The rebuild retry attempts are counted for all servers together, not per server. A second server whose listing fails for a reason other than connection or OAuth, after the attempts are used up, recovers only on a token save or a servers.changed. Several token saves at once can also queue back-to-back rebuilds, which directRefreshMu serialises.
  • During an outage the Web UI still shows the catalog sentence "…at the configured URL"; the CLI table has no retry time (it is in -o json).

Refs #1929

A remote upstream that failed because the network was gone (a laptop
asleep overnight) kept failing while it was gone. Every failure advanced
its backoff until the client gave up after 20 attempts and retried only
every 30 minutes. When the machine woke and the network was back, nothing
shortened that wait: the server stayed in Error for up to 30 minutes
although a manual Restart connected at once.

- Connect failures that happen before any upstream answered (DNS, dial,
  refused, timeout) are recorded as network failures
  (StateManager.SetNetworkError, ConnectionInfo.NetworkFailure). They
  advance the backoff exactly as before.
- A connectivity watcher in the upstream manager probes such servers with
  a bare TCP dial to their host, or to the HTTP proxy they use: every 10s,
  every 30s after 5 minutes of failures. Probes that failed and then
  succeed reset the backoff and reconnect the server, so it is back within
  one probe interval. A system wake (a tick far later than scheduled) or a
  change of the machine's network addresses gives a server one attempt on
  its current ladder once its host answers.
- The watcher never touches a server awaiting sign-in, failed on
  credentials or OAuth, parked as permanently broken, inside a Retry-After
  window, or logged out, and it reconnects one server at most every 30s.
  A server whose host answers all along while it keeps failing is left to
  the normal backoff (#1013). MCPPROXY_NETWORK_RECOVERY=off disables it.
- An HTTP/SSE initialize timeout no longer reports the stdio-only "produced
  no stderr output ... help banner" text, and it keeps the typed deadline,
  so it is classified as a network failure.

Refs #1929
@cloudflare-workers-and-pages

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

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 99d8643
Status: ✅  Deploy successful!
Preview URL: https://03579dc1.mcpproxy-docs.pages.dev
Branch Preview URL: https://fix-1929-network-recovery.mcpproxy-docs.pages.dev

View logs

…kens at once

Review round 1 (Opus) on the connectivity watcher:

- An OAuth token that expired overnight could not be refreshed on recovery:
  refreshes that failed while the machine was offline leave the refresh
  coordinator's transient cooldown (up to 5 min) on the credential, and the
  reconnect's reactive refresh was answered from it without a request.
  BeginNetworkRecovery now lifts that cooldown
  (RefreshCoordinator.ClearTransientCooldown); a revoked grant stays latched.
- Backoff resets were unbounded for a remote that is only intermittently
  reachable, and every network change granted an attempt. Reconnects are now
  budgeted per server: the first three after the server was last seen
  connected are immediate and may reset the backoff; past that no reset is
  granted and the spacing doubles up to the 30-minute give-up interval. A
  successful connection restores the budget.
- A quarantined (or disabled) server could be reconnected after an
  inspection exemption expired. Both are now ineligible.
- The backoff clear is atomic with the eligibility check
  (StateManager.ClearNetworkBackoff) instead of a full Reset, so a connect
  that started or failed differently meanwhile is never overwritten.
- Reconnects the watcher starts are bounded by the manager's shutdown
  context, honour the health loop's stop channel, and are waited for before
  the watcher exits.
- Through an HTTP proxy an https upstream is probed with CONNECT, so a
  proxy that stays up while the network behind it is down does not hide the
  outage.
- The HTTP initialize-timeout text no longer matches the stdio handshake
  diagnostic; it classifies as MCPX_HTTP_TIMEOUT.

Refs #1929
…n the wall clock

Review round 2 (Opus), two MINOR points:

- The reconnect budget was restored only when a 10s tick happened to see
  the server connected, and its spacing ran on the monotonic clock, which
  stops while a Mac sleeps. A night of dark wakes that connected briefly
  could spend the budget and defer the morning's recovery by up to 30
  minutes of awake time. The managed client now counts connects that
  reached Ready (ConnectSuccessCount); any change since the last tick
  restores the budget, and trigger spacing is measured on the wall clock.
- ReconnectAfterNetworkRecovery re-checks eligibility and reads the health
  loop's stop channel together under the client lock that Disconnect
  takes, so a Disconnect that lands first is not undone.

Refs #1929
Review round 3 (Opus), MINOR: trigger spacing is measured on the wall
clock, so a clock stepped backwards (NTP, a manual date change) read as a
negative elapsed time and deferred a server's recovery by the size of the
jump. A negative elapsed time now counts as elapsed, for the trigger
spacing and the probe cadence.

Refs #1929
…; show outages as temporary

Release QA blocker (run2 cooldown-503): an OAuth server stays connected
while its token has expired and the token endpoint answers 5xx, so every
refresh fails transiently and the refresh cooldown grows to minutes; after
a network drop the first successful tool call came 136-166 s after the
network returned. The connectivity watcher only handled servers in Error.

- Refresh mode: a connected server whose OAuth refresh failed transiently
  (RefreshCoordinator.TransientlyFailing: no success since, no terminal
  latch) is now watched too. When the network demonstrably comes back the
  refresh cooldown is lifted and one proactive refresh runs through the
  coordinator (single flight); the connection is left alone. Revoked grants
  (invalid_grant) stay latched, disabled/quarantined/logged-out servers are
  excluded, and the same per-server budget bounds it. The integration test
  reproducing the scenario recovers in ~0.25 s (it fails past 60 s without
  this mode).

Operator diagnostics, so an outage no longer reads as a hard failure or a
sign-in requirement:
- Health: an Error caused by a network failure is amber "Reconnecting:
  <cause>", status "connecting" while retries continue (CLI STATUS
  "Connecting"), with when the next attempt is due; it becomes an
  attention item (status error) again after the client gives up. Restart
  and Edit URL stay offered.
- Health: an expired OAuth token whose refresh is being retried after a
  temporary failure is "Token refresh pending" with the next refresh
  attempt, not "Token expired" + Sign in. HealthRefreshState also reports
  transient coordinator failures outside the proactive schedule.
- doctor: a self-resolving outage is not listed as an upstream connection
  error.
- Web UI: the server page shows an amber "Reconnecting automatically"
  panel with the retry detail instead of a red "Server Error".

Refs #1929
Review round 4 (Opus):

- MAJOR: a live connection that failed on the network (health ping, tool
  call, list) was recorded with SetError, without the network flag, so the
  connectivity watcher dropped the server and wiped the outage it had
  observed; the QA scenario could still take minutes. setErrorIfCurrentConnection
  now records such failures of remote servers (typed network errors, or a
  hard network fault flattened into an error string, e.g. inside an OAuth
  token error) with SetNetworkError. The watcher also keeps a server's probe
  history while it is briefly not actionable but unhealthy, and clears it
  only once the server is healthy, so an observed outage or restore is not
  lost.
- MINOR: a wrong host (action Edit URL) keeps status needs_config instead
  of connecting.
- MINOR: the Web UI shows "Reconnecting automatically" only for a degraded
  "connecting" health (a network failure), not for every connect attempt.

A new integration test runs the blocker with an outage longer than the
health interval and a network-flavoured refresh cooldown at its cap; the
first tool call succeeds ~1 s after the network returns.

Refs #1929
Review round 5 (Opus), MINOR: TestNetworkRecovery_StalledRefreshLongOutage
injected its in-outage refresh failure without ObservedRefreshToken, so the
coordinator skipped the flight as superseded, the cooldown kept its 503
text and the server stayed Ready: the test only re-ran the refresh-mode
path. It now passes the stored refresh token (as the RefreshManager's retry
does), waits for the health check to move the server to Error, asserts the
network flag, and restores the network at that moment - the timing in which
the server used to fall out of the watcher. First successful call ~0.25 s
after the restore; with the round-4 fixes removed it misses the 60 s bound.

Refs #1929
CI (windows-latest) showed the network-recovery integration tests time out
waiting for the outage to be noticed: Windows words a refused dial
"connectex: No connection could be made because the target machine
actively refused it." and a dropped connection "wsarecv: An existing
connection was forcibly closed by the remote host.", which none of the
text classifiers knew. A connected server's health check therefore never
noticed a network drop on Windows and the server stayed Ready.

isConnectionError, isTransientHealthCheckError (hard failures),
isRemoteNetworkFailure and the health calculator's connection patterns and
summaries now include the Windows wordings, verbatim from the CI log.

Refs #1929
Review round 6 (Opus), MINOR: Windows words other network failures
differently again ("A socket operation was attempted to an unreachable
network.", "…did not properly respond after a period of time"), so a
phrase list cannot keep up. isConnectionError now treats any *net.OpError
as a connection error, and isTransientHealthCheckError decides a typed
socket error by type: a timeout is a soft miss, anything else is hard.
The health calculator's connection patterns gain the last Windows wording.

Refs #1929
… failure

Release QA (integration 2965f50b2): /mcp call_tool_read qa-oauth:echo worked
while /mcp/s/qa-oauth listed only describe_tool and echo answered "tool not
found". Reproduced independently on main 6370f1f with isolated fixtures:
a direct-catalog rebuild (any servers.changed) that runs while a CONNECTED
server's tools/list fails transiently - here its OAuth token refresh was
failing - publishes the catalog without that server's tools. The server
then recovers on the same connection, no servers.changed follows, and the
direct and single-server surfaces stay stale (still stale 120 s after the
token endpoint recovered on main).

- upstream.Manager.DiscoverToolsWithFailures reports the connected,
  enabled, non-quarantined servers whose tools/list did not succeed.
- The direct rebuild retries while any such server exists: 5 s, doubling,
  capped at 30 s; a rebuild where every connected server listed clears it;
  Close stops it. Nothing stale is served in between.
- An oauth.token_refreshed event rebuilds at once when a retry is pending,
  so the surfaces come back the moment the token does.

Isolated repro, token endpoint failing then healthy: first successful
token refresh +34.1 s (the refresh manager's own backoff), /mcp/s/qa-oauth
republished 1 ms after it. Regression tests drive the single-server
surface through a transient listing failure and recovery, and the retry's
backoff and Close.

Refs #1929
…ken save

Review r7 on GH #1929:
- Each retry of the direct rebuild lists every connected server, so a server
  whose tools/list fails for good kept the whole fleet re-listed every 30 s.
  The retry now stops after 6 attempts (about two minutes); the failed state
  is kept, so the next OAuth token save or servers.changed still rebuilds.
- A retry timer's callback no longer clears a newer timer's reference.
- A TLS alert from the peer ("remote error: tls: certificate required") is a
  credential fault, not a socket failure: the typed *net.OpError rule skips
  Op "remote error" and falls back to the text rules.

Release QA clocks showed the network watcher's direct token refresh emits no
oauth.token_refreshed, so the scoped surface waited for the retry timer. A
runtime token-saved observer (every refresh path, run off the save path) now
triggers the pending rebuild; it also covers the case after the retries stop.
@Dumbris
Dumbris force-pushed the fix/1929-network-recovery branch from 3c9585c to 8c35f9c Compare November 18, 2026 16:42
@Dumbris
Dumbris enabled auto-merge (squash) November 18, 2026 17:06
@Dumbris
Dumbris disabled auto-merge November 18, 2026 18:37
CI on #1931 (Build Binaries linux/arm64): TestNetworkRecovery_StaticHeaderAnd
OAuthRecoverWithin60s left oauth-upstream in Error with "endpoint deprecated
(410 Gone)" after the network returned. Both isDeprecatedEndpointError copies
(core and managed) matched "410", "gone", "removed" and similar anywhere in
the error text, so a reconnect failure naming an address such as
127.0.0.1:41039 was turned into ErrEndpointDeprecated on the OAuth initialize
path: not a network failure, so recovery stopped. With the test relay pinned
to 127.0.0.1:41039 the old classifier fails with exactly that message and the
new one recovers in about 8 s; the CI run's relay port was not logged.

Both copies now call transport.LooksLikeDeprecatedEndpoint:
- the typed ErrEndpointDeprecated anywhere in the chain, or an HTTPError,
  decide by status (410 only);
- a socket, DNS, url.Error or context failure is never a deprecation,
  whatever address or URL its text names;
- when the text carries a response status ("status 500: ...", "status code:
  410"), that number alone decides, so a 5xx/4xx body saying "gone away",
  "removed" or "order 410" does not;
- otherwise "410 gone" and the existing phrases.

The status-keyed rule and its non-410 body tests are by Codex.
@Dumbris
Dumbris enabled auto-merge (squash) November 18, 2026 18:52
@Dumbris
Dumbris disabled auto-merge November 18, 2026 19:42
…g saved

Windows CI on #1931 (Build Binaries windows/amd64):
TestNetworkRecovery_ConnectedServerWithStalledRefreshRecovers recovered (first
call 253 ms after the network returned, token refreshed) and then still read
TransientlyFailing=true. A successful refresh commits the new token to bbolt
and only then calls NoteTokenSavedFor, which clears the transient state.
Readers see the committed meta page while the writer is still syncing, and
the sync is slow on Windows, so a tool call could already succeed with the new
token while the coordinator still said the refresh was failing.

RefreshCoordinator.BeginTokenSaveFor marks a successful token response as
being stored; while any save is in progress TransientlyFailing and
TransientRefreshStatus report nothing. All three save paths
(PersistentTokenStore, coordinatedMemoryTokenStore, the stored-DCR refresh
in core) begin before the write and end, deferred, after NoteTokenSavedFor.
A save that fails or is discarded leaves the earlier transient state as it
was. The test assertions are unchanged.

Tests: the persist hook observes no transient failure during a save (fails
without the change); an ended save without success keeps the failure. The
integration test passes -count=20 and GOMAXPROCS=1 -count=20 under -race.
@Dumbris
Dumbris enabled auto-merge (squash) November 18, 2026 20:44
@github-actions

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/1929-network-recovery

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-goK6QXUZ.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 44385534618 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

codecov-commenter commented Nov 18, 2026 •

Copy link
Copy Markdown

@Dumbris
Dumbris merged commit 8985728 into main Nov 18, 2026
64 of 66 checks passed
Dumbris added a commit that referenced this pull request Nov 19, 2026
…1934)

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