Repository navigation
fix: retirement barrier so retired upstream instances cannot dial or send credentialed requests (Spec 116 PR4; #1564) - #1612
Merged
Conversation
…aunches and writes (Spec 116 PR4) A Gate admits one leaf operation at a time under a read lock (a dial plus the registration of its connection, one connection write, a process start plus its registration). Retire latches under the connection mutex, cancels the gate context, closes tracked connections, kills tracked process groups, waits on a write-lock barrier for sections admitted before the latch, and sweeps again. Transport(base) clones an http.Transport with a gated dialer; WrapTransport wraps an mcp-go transport, preserving exactly the optional capabilities of its kind (stdio, streamable HTTP, SSE) with Unwrap. Tests: ordering, bounded Retire with a hung peer, late registration (both sweeps), no nesting, net/http retry refused, capability parity and pinned mcp-go method sets, and the write benchmark (T4.3, T4.7, T4.10, T4.16, T4.17).
…edentialed requests (Spec 116 PR4; #1564) Every instance that leaves the upstream manager's registry is retired before the call that removed it returns (unregisterLocked -> managed.Client.Retire -> the core client's dial gate): a commit retires removed, replaced and quarantined instances before it publishes, and a restart, ForceReconnectAll or Docker recovery retires the old instance before installing the new one. The gate covers everything an instance sends: - stdio, Docker run and launcher starts run in an admitted section together with the process-group registration; Retire SIGKILLs tracked groups; - every HTTP/SSE branch builds on the instance's gated http.Transport, and the mcp-go client is rebuilt over dialgate.WrapTransport; - OAuth preflight, resource auto-detection, metadata discovery, cache fetch, registration, code exchange and refresh run on the instance transport (oauth.Env, CreateOAuthConfigWithEnv, ValidateOAuthMetadataWithEnv); retired discovery flights are not cached and refused refreshes have no side effects; - the OAuth browser launch and the launcher's reachability probe are gated; manual OAuth shares the registered instance's gate; RefreshOAuthToken and manual OAuth refuse a retired instance; - a call, tools/list or health probe on a retired instance fails as server unavailable and is not charged to the replacement. The FR-024a scan in check-upstream-write-sites.sh rejects ungated HTTP in internal/oauth, internal/upstream/core and internal/transport, and GetTransport() outside core.innerTransport. qa_hooks gains MCPPROXY_QA_PARK_DIAL and MCPPROXY_QA_PARK_OAUTH (comma-separated targets) for the live check. OAuth token binding to the incarnation stays #1607.
Deploying mcpproxy-docs with
|
| Latest commit: |
6dcb3d3
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://a8e84da5.mcpproxy-docs.pages.dev |
| Branch Preview URL: | https://fix-116-pr4-retirement-barri.mcpproxy-docs.pages.dev |
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…1564) - tools/list on an instance retired mid-flight (leader and coalesced waiters) answers ErrInstanceRetired, as a tool call does, and moves no state machine. - A gated connection's Read reports ErrRetired when retirement closed it under the read, so a cut-off discovery fetch is not cached and a cut-off refresh charges no grant. - The refresh coordinator retries a joined retired flight until it gets a non-retirement answer or leads its own flight. - Launcher children stay tracked until Stop reaps them; the retirement kill is launcher.Handle.Kill (process group / the launcher's own Job). - stdio: a child already dead at registration still gets its process group killed (Setpgid: pgid = pid), so descendants do not survive. - FR-024a scan checks every http.Client literal within its own braces. - Tests: in-flight tools/list T4.5, descendant-aware stdio fixture, launcher Stop/Kill, mid-read discovery, coordinator retry, refresh race tests over the gated wrapped transports; docs and spec notes.
…1564) - launcher: Handle.Kill signals the process group recorded at spawn also after the leader exited, so a descendant backgrounded with redirected streams dies on retirement; a group whose number a live process holds as its PID (reused) is left alone. - dialgate: a process registration's kill is serialized with Untrack; no kill runs after Untrack returns. Disconnect and the post-OAuth reconnect untrack the stdio child before the close that reaps it. - Windows: assignProcessTree fails when the Job Object cannot be created or assigned; the stdio launch section kills the child and fails the start (FR-025a). - managed: a probe in flight at retirement produces no Error transition and no failure or retry accounting (FR-026). - oauth: RefreshCoordinator.Do normalizes a nil context before its retry loop. - FR-024a scan tracks brace depth per http.Client literal. - Tests: Docker and launcher launch admission (T4.1) with a launch observer seam; server-to-client ping and SSE connection loss through the production wrappers (T4.17).
…1564) - launcher: a child whose tree cannot be contained (Windows Job Object create/assign failure) is killed and Spawn fails inside the admitted launch section (FR-025a covers the launcher path). - launcher: the reused-group guard keys on a reaped flag set under reapMu right after cmd.Wait, not on Done; Kill runs under the same lock. - dialgate: a Write cut off by retirement reports ErrRetired, so a refresh POST cut mid-write sets no cooldown for the replacement's grant. - manager: StartManualOAuthQuick/WithInfo map a login on an instance retired meanwhile to "server not found" (FR-027) instead of a 500 with the internal retirement text; browser launches reach the launch observer. - FR-024a scan: http.Client with whitespace or a comment before its brace, and spaced selectors, are detected. - Tests: launcher containment and reap-window guard, write cut by retirement (gate and coordinator), manual login retired mid-flight (both entry points), T4.4 code exchange parked through the gated client and RefreshOAuthToken on an instance retired after lookup; zombie-tolerant descendant check. qa_hooks MCPPROXY_QA_PARK_LOGIN for the live check.
…1564) - launcher: reap the leader under reapMu after a non-reaping exit wait (waitid WNOWAIT on Linux, kqueue NOTE_EXIT on Darwin/BSD), so a retirement Kill can never signal a process-group ID released by an unlocked cmd.Wait and reused by an unrelated group; test seams made atomic. - stdio: clear processGroupID before the transport's Close reaps a child the retired gate refused to track, so Connect's failure cleanup cannot signal a released group ID. - FR-024a scanner: join selectors split after the dot (http. / Get(u), http. / Client{}) across blank and comment lines, reset per file. - SC-004: opt-in in-process measurement (MCPPROXY_SC004_MEASURE=1) with a retire observer seam; commit p99 20 ms, retire p99 42 us, but the 320-tool purge takes ~5.5 s (pre-existing per-document bleve deletes, #1617), so T098 is reopened.
…1564) - launcher: when the non-reaping exit wait is unavailable (kqueue refused, waitid denied), reap with a non-blocking wait4 polled under reapMu instead of an unlocked cmd.Wait, so Kill never signals a released and reused process-group ID; Kill is never held up by a live child. - FR-024a scanner: track slice/array/map literals of clients so gated []http.Client{{Transport: x}} passes and elided transport-less elements ([]*http.Client{{...}}, map values) are reported.
…d (Spec 116 PR4 Sol round 6; #1564) The post-reap reuse guard (kill(pgid,0)==ESRCH) could not tell our group from an unrelated group that reused the number and whose leader was reaped too. The reaper now keeps an exited leader a zombie while another member of its group runs (kern.proc.pgrp on macOS, /proc on Linux), so Kill and Stop signal a pinned group ID under reapMu; after the reap the group is never signalled. Where members cannot be listed, the rest of the group is killed just before the reap.
… blocks on Windows too
…et, not the latch
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 38409588483 --repo smart-mcp-proxy/mcpproxy-go
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Scope
Spec 116 PR4 (specs/116-config-commit-consistency, plan §PR4, tasks T080–T099): a per-instance retirement barrier. Once the upstream manager unregisters an instance (removal, endpoint/connection change, quarantine, same-name replacement, restart,
ForceReconnectAll, Docker recovery) it is retired before the removing call returns, and from then on it cannot dial, launch a stdio/Docker/launcher process, write to its connections, run its OAuth client, preflight or discovery helpers, retry throughnet/http, or open the OAuth browser flow. Teardown (MCP close, process-group kill,docker stop) still runs.Builds on PR3's
unregisterLockedand Spec 117'smanaged.Client.Retire()(oneRetirefor both, per research.md). Not in this PR: binding OAuth tokens and refresh flights to the incarnation (#1607);oauth.Envand the coordinator's retired-refusal path are the hooks for it.Design
internal/upstream/dialgate(new):GatewithAdmit(read lock around one leaf operation),DialContext(dial and connection registration in one admitted section, retirement-awaretrack), gatednet.Connwrites,TrackProcess,Transport(base)/HTTPTransport()(per-instance gated*http.Transport), andRetire: latch underconnsMu→ cancel gate context → close tracked conns → kill tracked process groups → write-lock barrier → second sweep.WrapTransportis lock-free and capability-preserving:gatedStdio/gatedStreamableHTTP/gatedSSEforward exactly their kind's optional interfaces (BidirectionalInterface,HTTPConnection,SetConnectionLostHandler,RequiresLegacyProtocol, OAuth handler accessors) plusUnwrap(); a retired wrapper answers server-to-client requests with a JSON-RPC error.core.Clientowns a gate. stdio start (incl. Dockerrun) and launcher spawn run in an admitted section together with process-group registration (the child now runs under the gate context instead ofcontext.Background()); the launcher's reachability probe and the OAuth browser launch are gated; everyCreateHTTPClient/CreateSSEClientbranch builds on the gated transport (HTTPTransportConfig.Gate) and returns a client overWrapTransport; capability assertions go through one helpercore.innerTransport(OAuth handler lookup, Streamable HTTP session snapshot).oauth.Env{Ctx, Transport}threaded throughCreateOAuthConfigWithEnv,ValidateOAuthMetadataWithEnv, the PRM/AS preflights, resource auto-detection, metadata discovery and the discovery cache fetch; the OAuthHTTPClientmcp-go uses for registration, code exchange and refresh runs on the instance transport. A discovery flight refused by a retired gate is not cached (a waiter that joined it runs its own fetch); a refresh refused by a retired gate has no side effects (no latch, cooldown or client clear).unregisterLocked→Retire()closes the gate; calls,tools/listand health probes on a retired instance returnErrInstanceRetired("server unavailable"), are not classified and are not charged to the replacement;RefreshOAuthTokenand manual OAuth refuse retired instances, and the transient manual-OAuth clients share the registered instance's gate.scripts/check-upstream-write-sites.shgains the FR-024a scan (nohttp.Get/Head/Post/PostForm(,http.DefaultClient,http.DefaultTransport, transport-lesshttp.Client{}ininternal/oauth,internal/upstream/core,internal/transport; noGetTransport()ininternal/upstreamoutsidecore/gate.go), allowlistscripts/ungated-http-allowlist.txt(process-default fallbacks only), 13 new self-test cases.MCPPROXY_QA_PARK_DIAL,MCPPROXY_QA_PARK_OAUTH(comma-separated targets).Deviations from the spec (also in tasks.md "PR4 implementation note")
RetireSIGKILLs tracked process groups (Windows: closes the Job) before and after its barrier but does not poll up to 1 s for exit; reaping stays with the transport'sClose. Polling would hold the manager's locks for up to 1 s per stdio removal.CREATE_SUSPENDED→ Job → resume (T093b) and the Windows Job test (T085b/T4.12) are deferred; Windows keeps the existing Job assignment right afterStart, now inside the admitted section.ps/rmbefore a launch,logs,inspect,stop) are not gated: they go to the local Docker daemon, never to the upstream, and are ownership checks or teardown.Retirecan reach stdin, andRetirekills the group before returning.core/gate.go(nottransport_unwrap.go). A streamable-HTTP sessionDELETEon the teardown of a retired instance is refused (nothing reaches the retired endpoint).Lock order
Gate.muis L5 andGate.connsMuL5' (plan §Lock order):Retireruns insideunregisterLockedundercaptureMuW +Manager.muW (L3 → L4 → L5). The read lock is held only around one leaf operation (a dial + registration, one write, a process start + registration), never nested; the wrapper takes no lock; the gate never calls back into the manager or runtime. The barrier therefore waits only for leaf operations whose connections it has already closed (bounded; warning above 1 s).Compatibility
No new dependencies, no wire or config change. Behavioural changes: removed/replaced/quarantined instances stop immediately (in-flight calls on them fail as unavailable); exported oauth helpers keep their signatures (
…WithEnvvariants added). The CLI client and other non-daemon users ofcore.Clientget an open gate that is never retired.Verification
internal/upstream/dialgate,internal/upstream(retire_*_test.go, driving the manager's realunregisterLocked),internal/upstream/core/retire_test.go,internal/oauth/retire_preflight_test.go;-race -count=20atGOMAXPROCS=1and4. Disabling the gate retirement (PR3's flag-only retire) fails 8 of the upstream tests; controls pass either way.go test -race -tags server -timeout 30m -skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint" ./internal/...green;./scripts/test-api-e2e.sh(scratch port) 69/0; golangci-lint v2 bare and--build-tags server: no findings in changed files; Windows/Linux cross-builds,-tags server,-tags qa_hooks,make buildok.bigprofile + custom OAuth config), baseline =origin/main+ the park points only:connect refused: … retired); re-add starts a fresh instance.GETwithAuthorizationto the removed endpoint; PR sends nothing. HTTP remove/replace: 0 requests to the old endpoint in both (PR3's context cancel already covered that window); replacement connects.refresh_token+ client secret to/token; PR sends 0 requests; no browser flow.Fixes #1564
🤖 Generated with Claude Code