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
32 changes: 29 additions & 3 deletions pkgs/mcpx/internal/daemon/registry_handoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package daemon

import (
"errors"
"sync"
"time"

"github.com/dezren39/mcpx/internal/defaults"
Expand Down Expand Up @@ -85,6 +86,10 @@ type Adoption struct {
// is contacted about them until Attach, so Abort leaves them entirely
// with the predecessor, which still owns them.
orphanSessions []orphanSession
// orphanWG tracks the background orphan-session terminations Attach
// starts, so a caller (in practice a test, or a shutdown that wants a
// clean slate) can wait for them with WaitOrphanTerminations.
orphanWG sync.WaitGroup
}

// orphanSession is a handed upstream HTTP session whose pool this
Expand Down Expand Up @@ -147,8 +152,18 @@ func (a *Adoption) Abort() {
a.orphanSessions = nil
}

// Attach serves the adopted children, closes the orphans and ends the
// orphaned upstream sessions. Call it only after the handoff has committed.
// Attach serves the adopted children and closes the orphans. Call it only
// after the handoff has committed.
//
// Orphaned upstream sessions are ended in the background, not here: each
// DELETE is bounded only by the per-session delete timeout (5s), so running
// them synchronously in series would delay the successor daemon serving by
// N x 5s — worst exactly when an upstream is unreachable and the DELETE can
// never succeed (#291). Termination is best-effort (a failure already just
// logs upstream.session.orphaned and leaves the session to expire), so
// nothing about correctness needs it done before serving — only the abort
// path needs no DELETE before commit, and Attach runs strictly after
// commit, so starting the sends here preserves that.
func (a *Adoption) Attach() {
for p, ads := range a.byPool {
p.Attach(ads, a.seq[p])
Expand All @@ -157,7 +172,18 @@ func (a *Adoption) Attach() {
o.Close()
}
for _, s := range a.orphanSessions {
pool.TerminateOrphanedSession(s.server, s.h)
a.orphanWG.Add(1)
go func(s orphanSession) {
defer a.orphanWG.Done()
pool.TerminateOrphanedSession(s.server, s.h)
}(s)
Comment on lines +175 to +179

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound orphan-session deletion concurrency

When a removed pool contains many live sessions, this loop starts one goroutine and one outbound DELETE connection for every session at once. Because pool.max has no upper bound and multiple pools may be removed together, a takeover can now create an unbounded connection/FD burst; an upstream with concurrency or rate limits may also reject DELETEs that the previous serial implementation would have completed, leaving sessions alive until expiry. Run the cleanup asynchronously but drain it serially or through a bounded worker pool so serving starts immediately without unbounded fan-out.

Useful? React with 👍 / 👎.

}
a.orphanSessions = nil
}

// WaitOrphanTerminations blocks until every background orphan-session
// termination Attach started has finished. Production serving never waits
// for it; it exists for tests and orderly shutdown.
func (a *Adoption) WaitOrphanTerminations() {
a.orphanWG.Wait()
Comment on lines +187 to +188

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Register orphan cleanup with daemon shutdown

This wait hook cannot actually be used by the orderly-shutdown path: commitTakeover keeps the Adoption only in a local variable and discards it on return, while Server.stopServing waits only for registry pools. If the successor is stopped or restarted shortly after takeover—especially while a DELETE is waiting on a slow upstream—the process can exit with the goroutine still running and silently abandon a termination that would otherwise succeed. Track these jobs on a server-owned wait group (or retain the adoption) and wait for them within the shutdown deadline.

Useful? React with 👍 / 👎.

}
51 changes: 51 additions & 0 deletions pkgs/mcpx/internal/daemon/registry_handoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ type orphanUpstream struct {
issued int
deletes int
deleted []string
// blockDelete, when non-nil, holds a DELETE in the handler until it is
// closed (or the request goes away); deleteStarted is signalled when a
// blocked DELETE arrives. They simulate a blackholed upstream (#291).
blockDelete chan struct{}
deleteStarted chan struct{}
}

func newOrphanUpstream(t *testing.T) *orphanUpstream {
Expand All @@ -33,6 +38,19 @@ func newOrphanUpstream(t *testing.T) *orphanUpstream {
}

func (u *orphanUpstream) serve(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete && u.blockDelete != nil {
if u.deleteStarted != nil {
select {
case u.deleteStarted <- struct{}{}:
default:
}
}
select {
case <-u.blockDelete:
case <-r.Context().Done():
return
}
}
u.mu.Lock()
defer u.mu.Unlock()
sid := r.Header.Get("Mcp-Session-Id")
Expand Down Expand Up @@ -147,6 +165,7 @@ func TestTakeoverTerminatesARemovedServersUpstreamSession(t *testing.T) {
}
ho.Commit()
ad.Attach()
ad.WaitOrphanTerminations()

deletes, deleted := up.counts()
if deletes != 1 {
Expand All @@ -157,6 +176,38 @@ func TestTakeoverTerminatesARemovedServersUpstreamSession(t *testing.T) {
}
}

// #291: ending an orphaned session must not block Attach — and therefore
// the takeover's serving path — when the upstream never answers. The
// DELETE still happens exactly once, in the background, after commit.
func TestTakeoverOrphanTerminationDoesNotBlockAttach(t *testing.T) {
up := newOrphanUpstream(t)
up.blockDelete = make(chan struct{})
up.deleteStarted = make(chan struct{}, 1)
_, ho := detachRemote(t, up.URL)
next := emptyRegistry(t)

ad, err := next.Adopt(ho.Pools)
if err != nil {
t.Fatal(err)
}
ho.Commit()
start := time.Now()
ad.Attach()
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("Attach blocked %v on an unanswering orphan upstream; orphan termination must run off the serving path", elapsed)
}
select {
case <-up.deleteStarted:
case <-time.After(2 * time.Second):
t.Fatal("no orphan DELETE was started in the background after Attach")
}
close(up.blockDelete)
ad.WaitOrphanTerminations()
if deletes, _ := up.counts(); deletes != 1 {
t.Fatalf("upstream saw %d DELETE(s), want exactly 1", deletes)
}
}

// On the abort path the predecessor still owns the session: no DELETE, and
// the predecessor goes on serving it.
func TestAbortedTakeoverLeavesARemovedServersSessionAlone(t *testing.T) {
Expand Down
Loading