From f08ddaef83eaaee619265a0c347335c5906ad26d Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Mon, 16 Nov 2026 05:42:27 -0600 Subject: [PATCH] feat(mcpx): takeover becomes attach for supervised instances (#9962) --- pkgs/mcpx/internal/daemon/registry_handoff.go | 24 ++++++++++ pkgs/mcpx/internal/daemon/server.go | 3 ++ pkgs/mcpx/internal/daemon/takeover.go | 4 ++ pkgs/mcpx/internal/e2e/takeover_test.go | 44 ++++++++++++++++++ pkgs/mcpx/internal/mcpclient/supervised.go | 12 +++++ pkgs/mcpx/internal/pool/handoff.go | 46 +++++++++++++++++++ pkgs/mcpx/internal/pool/pool.go | 37 ++++++++++++--- 7 files changed, 164 insertions(+), 6 deletions(-) diff --git a/pkgs/mcpx/internal/daemon/registry_handoff.go b/pkgs/mcpx/internal/daemon/registry_handoff.go index c01c77e1f9..9ab3eac721 100644 --- a/pkgs/mcpx/internal/daemon/registry_handoff.go +++ b/pkgs/mcpx/internal/daemon/registry_handoff.go @@ -1,6 +1,7 @@ package daemon import ( + "context" "errors" "sync" "time" @@ -189,3 +190,26 @@ func (a *Adoption) Attach() { func (a *Adoption) WaitOrphanTerminations() { a.orphanWG.Wait() } + +// AdoptSupervised runs the #9962 state-dir scan over every pool: a +// supervised server whose supervisor is already running (left behind +// by a previous daemon) is adopted by attach, so its child keeps its +// PID across the restart and no duplicate is spawned. Called at daemon +// startup and again after a takeover commits — at startup a live +// predecessor may still be attached (the scan then no-ops); after the +// commit the predecessor has detached and the attach succeeds. +func (r *Registry) AdoptSupervised(ctx context.Context) { + r.mu.RLock() + seen := map[*pool.Pool]bool{} + var pools []*pool.Pool + for _, name := range r.order { + if p := r.pools[name]; !seen[p] { + seen[p] = true + pools = append(pools, p) + } + } + r.mu.RUnlock() + for _, p := range pools { + p.AdoptRunningSupervised(ctx) + } +} diff --git a/pkgs/mcpx/internal/daemon/server.go b/pkgs/mcpx/internal/daemon/server.go index 4377a7df98..8ca0e514fc 100644 --- a/pkgs/mcpx/internal/daemon/server.go +++ b/pkgs/mcpx/internal/daemon/server.go @@ -394,6 +394,9 @@ func (s *Server) Listen(tcpPort int) error { } s.endpoint = "http://" + tcpLn.Addr().String() s.started = time.Now() + // Adopt supervised instances a previous daemon left running + // (#9962): their supervisors outlive the daemon by design. + s.reg.AdoptSupervised(context.Background()) return s.publish() } diff --git a/pkgs/mcpx/internal/daemon/takeover.go b/pkgs/mcpx/internal/daemon/takeover.go index 47a42e983c..f80d5d9e0b 100644 --- a/pkgs/mcpx/internal/daemon/takeover.go +++ b/pkgs/mcpx/internal/daemon/takeover.go @@ -772,6 +772,10 @@ func (s *Server) commitTakeover(uc *net.UnixConn, in *takeoverIn, endFd *os.File s.started = t } ad.Attach() + // Supervised instances were not handed off; adopt them now that + // the predecessor's commit has detached it from their supervisors + // (#9962). + s.reg.AdoptSupervised(context.Background()) // Keep the adoption so an orderly exit can wait for the background // orphan terminations Attach just started (#298). Only the committed // path reaches here; the abort path above sends no DELETEs. diff --git a/pkgs/mcpx/internal/e2e/takeover_test.go b/pkgs/mcpx/internal/e2e/takeover_test.go index 7535cf1a0f..740a06d67b 100644 --- a/pkgs/mcpx/internal/e2e/takeover_test.go +++ b/pkgs/mcpx/internal/e2e/takeover_test.go @@ -225,6 +225,50 @@ func TestTakeoverKeepsTheChildAndTheListener(t *testing.T) { } } +const oneSupervisedServer = `{ + "mcpServers": { + "demo": { "command": "FAKE", "mcpx": { "sharing": "shared", "scope": "global", "supervised": true, "description": "a fake supervised server" } } + } +}` + +// Phase 2 of #1384 (#9962): a supervised instance is adopted by attach, +// never handed off. The successor daemon attaches to the still-running +// supervisor, so the stdio child keeps its PID across the restart and no +// pipe/pool handoff frames are exchanged for it. +func TestTakeoverAttachesToSupervisedChild(t *testing.T) { + e := newEnv(t, oneSupervisedServer) + e.envVars = append(e.envVars, "MCPX_DAEMON_WATCH_CONFIG=false") + e.run("call", "demo.echo", `{"message":"before"}`) + before := e.daemonState(t) + child := before.childOf("demo") + if child == 0 { + t.Fatalf("no live supervised child before the takeover: %+v", before) + } + // The supervised child outlives every daemon by design; the test + // owns it, so the test retires it (its supervisor exits with it). + t.Cleanup(func() { + if processExists(child) { + if proc, err := os.FindProcess(child); err == nil { + _ = proc.Kill() + } + } + }) + + s := startSuccessor(t, e) + after := e.awaitSuccessor(t, s) + if got := after.childOf("demo"); got != child { + t.Fatalf("the supervised child was replaced by the takeover: pid %d -> %d", child, got) + } + if out := e.run("call", "demo.echo", `{"message":"after"}`); !strings.Contains(out, "after") { + t.Fatalf("the taken-over daemon did not answer through the supervised child:\n%s", out) + } + s.mainPIDReported(t) + awaitExit(t, before.PID, "the previous daemon") + if !processExists(child) { + t.Fatalf("the supervised child %d died with the previous daemon", child) + } +} + func TestTakeoverRestartsAChangedServerAndKeepsTheRest(t *testing.T) { e := newEnv(t, twoServers) e.envVars = append(e.envVars, "MCPX_DAEMON_WATCH_CONFIG=false") diff --git a/pkgs/mcpx/internal/mcpclient/supervised.go b/pkgs/mcpx/internal/mcpclient/supervised.go index f29ed2cc5c..94296fd3e5 100644 --- a/pkgs/mcpx/internal/mcpclient/supervised.go +++ b/pkgs/mcpx/internal/mcpclient/supervised.go @@ -698,6 +698,18 @@ func NewSupervised(opts SupervisedOptions) (*SupervisedTransport, error) { return newSupervised(opts, nil) } +// AttachSupervised attaches to the server's already-running supervisor +// and never spawns one (#9962). It is the probe a daemon's state-dir +// scan adopts supervised instances through: no socket, a dead socket, +// or a live supervisor's refusal (another daemon attached, version +// mismatch) are all errors, and nothing is started in their place. +func AttachSupervised(opts SupervisedOptions) (*SupervisedTransport, error) { + if opts.StateDir == "" { + opts.StateDir = StateDir() + } + return attachSupervisor(SupervisorSocketPath(opts.StateDir, opts.Name), opts) +} + // spawnFunc starts a supervisor for the socket; nil means re-exec. type spawnFunc func(sock string, opts SupervisedOptions) error diff --git a/pkgs/mcpx/internal/pool/handoff.go b/pkgs/mcpx/internal/pool/handoff.go index d7fc3bcc35..e91b440311 100644 --- a/pkgs/mcpx/internal/pool/handoff.go +++ b/pkgs/mcpx/internal/pool/handoff.go @@ -459,3 +459,49 @@ func (p *Pool) ExecIdentity() string { defer p.execMu.Unlock() return p.exec } + +// AdoptRunningSupervised is the state-dir scan of #9962 (Phase 2 of +// #1384): when a supervisor for this pool's server is already running — +// left behind by a previous daemon — adopt its child as this pool's +// instance by attaching, instead of handing the instance off or +// spawning a duplicate. It reports whether an instance was adopted. +// No live supervisor, a supervisor another daemon is attached to, and +// a pool that already serves the default lane are all quiet no-ops: +// the ordinary spawn path (attach-or-spawn) covers them on first use. +func (p *Pool) AdoptRunningSupervised(ctx context.Context) bool { + if p.cfg == nil || !p.cfg.Stdio() || p.cfg.Mcpx == nil || !p.cfg.Mcpx.Supervised { + return false + } + rs := p.cfg.Scope.Resolve(config.CallContext{}) + p.mu.Lock() + if p.closed || p.starting > 0 || p.findLaneLocked(rs.Key, false) != nil { + p.mu.Unlock() + return false + } + p.starting++ + p.mu.Unlock() + + in, err := p.startLaneMode(ctx, false, rs, true) + + p.mu.Lock() + p.starting-- + if err != nil { + p.cond.Broadcast() + p.mu.Unlock() + return false + } + if p.closed || p.findLaneLocked(rs.Key, false) != nil { + // The pool moved on while the attach was in flight; retire + // the duplicate the same way Acquire does. + p.cond.Broadcast() + p.mu.Unlock() + go func() { _ = in.Client.Close() }() + return false + } + in.key = rs.Key + in.lastUsed = time.Now() + p.instances = append(p.instances, in) + p.cond.Broadcast() + p.mu.Unlock() + return true +} diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index 7b407d2007..6089664111 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -139,8 +139,14 @@ func (i *Instance) Trace() string { return i.trace } func (i *Instance) Root() string { return i.root } // PID returns the child process id for stdio instances, 0 otherwise. +// A supervised instance's child belongs to its supervisor, not to this +// daemon, but the PID is still the child's: the attach handshake reports +// it, and status/takeover observers use it to tell attach from respawn. func (i *Instance) PID() int { - if st, ok := i.transport.(*mcpclient.StdioTransport); ok { + switch st := i.transport.(type) { + case *mcpclient.StdioTransport: + return st.PID() + case *mcpclient.SupervisedTransport: return st.PID() } return 0 @@ -623,6 +629,13 @@ func (p *Pool) subscribeServerEvents(cl *mcpclient.Client) { // serves: its root is stored on the instance at creation and read back // for every restart, never re-resolved (decision 0004 §2). func (p *Pool) startLane(ctx context.Context, legacy bool, rs config.ResolvedScope) (*Instance, error) { + return p.startLaneMode(ctx, legacy, rs, false) +} + +// startLaneMode is startLane with the dial mode threaded through: with +// attachOnly set, a supervised server is adopted from its running +// supervisor or not started at all (#9962). +func (p *Pool) startLaneMode(ctx context.Context, legacy bool, rs config.ResolvedScope, attachOnly bool) (*Instance, error) { sctx, cancel := context.WithTimeout(ctx, p.cfg.StartTimeout) defer cancel() launched := time.Now() @@ -644,7 +657,7 @@ func (p *Pool) startLane(ctx context.Context, legacy bool, rs config.ResolvedSco } execStamp, execIdentity, _ := eff.ExecStateAt(spawnCwd) - tr, err := p.dial(sctx, eff, rs.Root) + tr, err := p.dialMode(sctx, eff, rs.Root, attachOnly) if err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } @@ -688,7 +701,7 @@ func (p *Pool) startLane(ctx context.Context, legacy bool, rs config.ResolvedSco // transport; going straight there saves the two refused POSTs. if cl, tr, err = p.connectSSE(sctx, tr, opts); err == nil { source = mcpclient.SourceCache - } else if tr, err = p.dial(sctx, eff, rs.Root); err != nil { + } else if tr, err = p.dialMode(sctx, eff, rs.Root, attachOnly); err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } } @@ -733,7 +746,7 @@ func (p *Pool) startLane(ctx context.Context, legacy bool, rs config.ResolvedSco // that hears initialize first -- and the cache is what keeps this // from happening on every start. _ = tr.Close() - if tr, err = p.dial(sctx, eff, rs.Root); err != nil { + if tr, err = p.dialMode(sctx, eff, rs.Root, attachOnly); err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } opts.Preference, opts.Cached = mcpclient.ForceLegacy, "" @@ -997,13 +1010,21 @@ func SpawnCwd(configCwd, root string) (cwd, source string) { // callers with no instance being spawned (HTTP session adoption) it is // simply the pool's stored config. func (p *Pool) dial(ctx context.Context, eff *config.Resolved, root string) (mcpclient.Transport, error) { + return p.dialMode(ctx, eff, root, false) +} + +// dialMode is dial with one variation: with attachOnly set, a supervised +// server attaches to its already-running supervisor or fails — it never +// spawns a supervisor (#9962 adoption scan). Unsupervised paths ignore +// the flag. +func (p *Pool) dialMode(ctx context.Context, eff *config.Resolved, root string, attachOnly bool) (mcpclient.Transport, error) { spawnCwd, _ := SpawnCwd(eff.Cwd, root) auth, err := p.resolveAuth() if err != nil { return nil, err } if eff.Stdio() && eff.Mcpx != nil && eff.Mcpx.Supervised { - return mcpclient.NewSupervised(mcpclient.SupervisedOptions{ + opts := mcpclient.SupervisedOptions{ Name: eff.Name, Command: eff.Command, Args: eff.Args, @@ -1011,7 +1032,11 @@ func (p *Pool) dial(ctx context.Context, eff *config.Resolved, root string) (mcp Cwd: spawnCwd, InheritEnv: true, Context: ctx, - }) + } + if attachOnly { + return mcpclient.AttachSupervised(opts) + } + return mcpclient.NewSupervised(opts) } if eff.Stdio() { return mcpclient.NewStdio(mcpclient.StdioOptions{