Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions pkgs/mcpx/internal/daemon/registry_handoff.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package daemon

import (
"context"
"errors"
"sync"
"time"
Expand Down Expand Up @@ -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)
}
}
3 changes: 3 additions & 0 deletions pkgs/mcpx/internal/daemon/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down
4 changes: 4 additions & 0 deletions pkgs/mcpx/internal/daemon/takeover.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
44 changes: 44 additions & 0 deletions pkgs/mcpx/internal/e2e/takeover_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
12 changes: 12 additions & 0 deletions pkgs/mcpx/internal/mcpclient/supervised.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
46 changes: 46 additions & 0 deletions pkgs/mcpx/internal/pool/handoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
37 changes: 31 additions & 6 deletions pkgs/mcpx/internal/pool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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)
}
Expand Down Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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, ""
Expand Down Expand Up @@ -997,21 +1010,33 @@ 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,
Env: overlay(overlay(eff.Env, p.runtimeEnv()), auth.Env),
Cwd: spawnCwd,
InheritEnv: true,
Context: ctx,
})
}
if attachOnly {
return mcpclient.AttachSupervised(opts)
}
return mcpclient.NewSupervised(opts)
}
if eff.Stdio() {
return mcpclient.NewStdio(mcpclient.StdioOptions{
Expand Down