From 8b3251ea2722e390305004686d996ddd6330ea97 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 18:23:04 -0500 Subject: [PATCH 1/3] fix(mcpx): per-connection writer + bounded write deadline for the supervisor (#2390) --- pkgs/mcpx/internal/mcpclient/supervised.go | 121 ++++++++++-- .../internal/mcpclient/supervised_test.go | 179 ++++++++++++++++++ 2 files changed, 279 insertions(+), 21 deletions(-) diff --git a/pkgs/mcpx/internal/mcpclient/supervised.go b/pkgs/mcpx/internal/mcpclient/supervised.go index a882cf3762..e396dcfb98 100644 --- a/pkgs/mcpx/internal/mcpclient/supervised.go +++ b/pkgs/mcpx/internal/mcpclient/supervised.go @@ -40,6 +40,63 @@ const SupervisorProtocolVersion = 1 // while no daemon is attached (1 MiB, tail-keep; see tailBuffer). const DefaultUnattachedBuffer = 1 << 20 +// DefaultAttachedWriteTimeout is the default bound on a single write to +// the attached daemon (see AttachedWriteTimeout). +const DefaultAttachedWriteTimeout = 5 * time.Second + +// AttachedWriteTimeout bounds every write to the attached daemon's +// connection. A daemon that stops reading must not wedge the supervisor: +// once the socket buffer fills, an unbounded write would block the +// stdout pump forever — the child exit would never surface and detach +// could never proceed (#2390). On expiry the attach is dropped, the +// unwritten bytes go to the tail buffer, and the pump keeps draining +// the child. It is a variable so tests can shorten it. +var AttachedWriteTimeout = DefaultAttachedWriteTimeout + +// connWriter is the per-connection writer for the attached daemon. All +// writes to the attached connection serialise on its own mutex, never +// on the supervisor's state mutex s.mu, and every write carries the +// AttachedWriteTimeout deadline. s.mu only snapshots, publishes, and +// clears the *connWriter pointer. +type connWriter struct { + mu sync.Mutex + conn net.Conn +} + +// Write writes p under the writer mutex with a fresh write deadline. +func (w *connWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.writeLocked(p) +} + +func (w *connWriter) writeLocked(p []byte) (int, error) { + _ = w.conn.SetWriteDeadline(time.Now().Add(AttachedWriteTimeout)) + return w.conn.Write(p) +} + +// flushLocked writes the handshake reply and then the buffered child +// output as one serialised unit. The caller (handleAttach) holds w.mu +// across the publish of w as the attached connection and this flush, so +// no live pump chunk can overtake the reply or the buffered bytes. +func (w *connWriter) flushLocked(reply supervisorReply, buffered []byte) error { + b, err := json.Marshal(reply) + if err != nil { + return err + } + if _, err := w.writeLocked(append(b, '\n')); err != nil { + return err + } + if len(buffered) > 0 { + _, err := w.writeLocked(buffered) + return err + } + return nil +} + +// Close closes the underlying connection. +func (w *connWriter) Close() { w.conn.Close() } + type supervisorHandshake struct { Version int `json:"version"` } @@ -149,7 +206,7 @@ type supervisor struct { ln net.Listener mu sync.Mutex - attached net.Conn + attached *connWriter attachedEver bool reported bool buf *tailBuffer @@ -299,7 +356,12 @@ func (s *supervisor) spawnChild() error { } // pumpStdout moves child stdout to the attached daemon, or into the -// bounded tail buffer while nobody is attached. +// bounded tail buffer while nobody is attached. It never writes while +// holding s.mu (#2390): s.mu only snapshots the attached writer, the +// write itself serialises on the writer's own mutex under a bounded +// deadline, so a stalled daemon can block this pump for at most +// AttachedWriteTimeout — never the supervisor's state, and never +// forever. func (s *supervisor) pumpStdout() { defer close(s.pumpDone) chunk := make([]byte, 32<<10) @@ -308,18 +370,29 @@ func (s *supervisor) pumpStdout() { if n > 0 { data := chunk[:n] s.mu.Lock() - if s.attached != nil { - if _, werr := s.attached.Write(data); werr != nil { + w := s.attached + s.mu.Unlock() + if w != nil { + if _, werr := w.Write(data); werr != nil { // The daemon went away mid-write (e.g. it was - // SIGKILLed): keep the bytes it missed. + // SIGKILLed) or stopped reading until the + // write deadline expired: keep the bytes it + // missed, and drop the attach — but only if + // it still points at this same writer, so a + // newer attach is never cleared by a stale + // pump error. s.buf.Write(data) - s.attached.Close() - s.attached = nil + s.mu.Lock() + if s.attached == w { + s.attached = nil + } + s.mu.Unlock() + w.Close() + s.signal() } } else { s.buf.Write(data) } - s.mu.Unlock() } if err != nil { return @@ -375,20 +448,26 @@ func (s *supervisor) handleAttach(conn net.Conn) { reply.StderrTail = s.stderr.Tail(800) } buffered := s.buf.Drain() - s.attached = conn + // Publish the writer as the attached connection BEFORE the reply + // and buffered flush go out, and hold the writer's mutex across + // the publish and the flush (#2390): the pump snapshots the writer + // under s.mu but serialises its writes on w.mu, so while the flush + // holds w.mu no live chunk can overtake the reply or the buffered + // bytes — and s.mu itself is never held across a connection write, + // so a stalled daemon blocks only this flush, only until the write + // deadline. + w := &connWriter{conn: conn} + w.mu.Lock() + s.attached = w s.attachedEver = true if reply.ChildState == "exited" { s.reported = true } - // The reply and the buffered flush go out under the lock so the - // stdout pump cannot interleave live bytes ahead of them. - werr := writeReply(conn, reply) - if werr == nil && len(buffered) > 0 { - _, werr = conn.Write(buffered) - } s.mu.Unlock() + werr := w.flushLocked(reply, buffered) + w.mu.Unlock() if werr != nil { - s.detach(conn) + s.detach(w) return } if reply.ChildState == "exited" { @@ -397,7 +476,7 @@ func (s *supervisor) handleAttach(conn net.Conn) { // finishWhenDone observes exited && detached and returns. go func() { _, _ = io.Copy(io.Discard, r) - s.detach(conn) + s.detach(w) }() return } @@ -406,17 +485,17 @@ func (s *supervisor) handleAttach(conn net.Conn) { // The daemon detached (clean close or death). The child's // stdin stays open: EOF there is a lifecycle signal a // supervised child must not see just because a daemon left. - s.detach(conn) + s.detach(w) }() } -func (s *supervisor) detach(conn net.Conn) { +func (s *supervisor) detach(w *connWriter) { s.mu.Lock() - if s.attached == conn { + if s.attached == w { s.attached = nil } s.mu.Unlock() - conn.Close() + w.Close() s.signal() } diff --git a/pkgs/mcpx/internal/mcpclient/supervised_test.go b/pkgs/mcpx/internal/mcpclient/supervised_test.go index f473f81db0..fd20e4e1cd 100644 --- a/pkgs/mcpx/internal/mcpclient/supervised_test.go +++ b/pkgs/mcpx/internal/mcpclient/supervised_test.go @@ -1,9 +1,13 @@ package mcpclient_test import ( + "bufio" "context" + "encoding/json" + "errors" "fmt" "io" + "net" "os" "strings" "syscall" @@ -21,6 +25,8 @@ import ( // supervise --socket -- [args...] (supervisor) // noisychild (flood, then echo) // exitchild (one frame, exit 3) +// floodchild (flood > any socket buffer, then exit) +// burstchild (numbered burst, then echo) func TestMain(m *testing.M) { if len(os.Args) > 1 { switch os.Args[1] { @@ -32,11 +38,33 @@ func TestMain(m *testing.M) { case "exitchild": fmt.Println(`{"ready":true}`) os.Exit(3) + case "floodchild": + runFloodChild() + os.Exit(0) + case "burstchild": + runBurstChild() + os.Exit(0) } } os.Exit(m.Run()) } +// runFloodChild writes far more than any socket buffer holds +// (~5 MiB of ~100-byte frames), then exits. +func runFloodChild() { + for i := 0; i < 50000; i++ { + fmt.Printf("{\"n\":%06d}%s\n", i, strings.Repeat(" ", 88)) + } +} + +// runBurstChild writes a small numbered burst, then echoes stdin. +func runBurstChild() { + for i := 0; i < 100; i++ { + fmt.Printf("{\"burst\":%06d}%s\n", i, strings.Repeat(" ", 84)) + } + _, _ = io.Copy(os.Stdout, os.Stdin) +} + func runSuperviseMode(args []string) int { var socket string var child []string @@ -303,3 +331,154 @@ func TestSupervisedChildExitSurfaced(t *testing.T) { } t.Fatal("child pid still alive after exit") } + +// rawAttach dials the supervisor socket and sends the attach +// handshake, retrying briefly while the listener comes up. It does +// not read the reply. +func rawAttach(t *testing.T, sock string) net.Conn { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + conn, err := net.DialTimeout("unix", sock, 2*time.Second) + if err == nil { + if _, err := conn.Write([]byte("{\"version\":1}\n")); err != nil { + conn.Close() + t.Fatalf("write handshake: %v", err) + } + return conn + } + if time.Now().After(deadline) { + t.Fatalf("dial supervisor socket: %v", err) + } + time.Sleep(50 * time.Millisecond) + } +} + +// Regression for #2390: a daemon that attaches and never reads must +// not wedge the supervisor. Before the fix, pumpStdout wrote to the +// attached connection while holding s.mu, so once the socket buffer +// filled, the write blocked forever, the child exit was never +// recorded, and RunSupervisor never returned. Now the write carries a +// bounded deadline, the stalled attach is dropped, the pump drains +// the child to EOF, and the supervisor finishes. +func TestSupervisedStalledReaderAttachDropped(t *testing.T) { + old := mcpclient.AttachedWriteTimeout + mcpclient.AttachedWriteTimeout = 250 * time.Millisecond + defer func() { mcpclient.AttachedWriteTimeout = old }() + + dir := t.TempDir() + sock := mcpclient.SupervisorSocketPath(dir, "flood") + done := make(chan error, 1) + go func() { + done <- mcpclient.RunSupervisor(mcpclient.SupervisorOptions{ + SocketPath: sock, + Command: selfExe(t), + Args: []string{"floodchild"}, + InheritEnv: true, + }) + }() + + // Attach and never read: the stalled daemon. + conn := rawAttach(t, sock) + defer conn.Close() + + select { + case err := <-done: + if err != nil { + t.Fatalf("RunSupervisor: %v", err) + } + case <-time.After(30 * time.Second): + t.Fatal("supervisor did not finish: a stalled daemon wedged the child exit (#2390)") + } + + // The stalled attach was dropped: the supervisor closed the + // connection, so reads drain what was buffered and then hit EOF + // rather than timing out on a live connection. + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + buf := make([]byte, 32<<10) + for { + _, err := conn.Read(buf) + if err != nil { + var nerr net.Error + if errors.As(err, &nerr) && nerr.Timeout() { + t.Fatal("stalled connection still open after supervisor finished: attach was not dropped") + } + break + } + } +} + +// The attach flush keeps its ordering guarantee without holding s.mu +// across the writes (#2390): the daemon receives the handshake reply +// first, then the output buffered while unattached, then live output +// — no live chunk overtakes the flush. +func TestSupervisedAttachFlushOrdering(t *testing.T) { + dir := t.TempDir() + sock := mcpclient.SupervisorSocketPath(dir, "burst") + done := make(chan error, 1) + go func() { + done <- mcpclient.RunSupervisor(mcpclient.SupervisorOptions{ + SocketPath: sock, + Command: selfExe(t), + Args: []string{"burstchild"}, + InheritEnv: true, + }) + }() + // Let the burst land in the unattached tail buffer. + time.Sleep(1 * time.Second) + + conn := rawAttach(t, sock) + defer conn.Close() + _ = conn.SetReadDeadline(time.Now().Add(15 * time.Second)) + r := bufio.NewReader(conn) + + // 1. The handshake reply comes first. + line, err := r.ReadBytes('\n') + if err != nil { + t.Fatalf("read reply: %v", err) + } + var reply struct { + Version int `json:"version"` + PID int `json:"pid"` + } + if err := json.Unmarshal(line, &reply); err != nil { + t.Fatalf("reply is not the handshake reply: %q: %v", line, err) + } + if reply.Version != mcpclient.SupervisorProtocolVersion || reply.PID <= 0 { + t.Fatalf("reply = %+v, want version %d and a child pid", reply, mcpclient.SupervisorProtocolVersion) + } + defer func() { _ = syscall.Kill(reply.PID, syscall.SIGKILL) }() + + // 2. Then the buffered burst, complete and in order. + for i := 0; i < 100; i++ { + line, err := r.ReadBytes('\n') + if err != nil { + t.Fatalf("read buffered frame %d: %v", i, err) + } + want := fmt.Sprintf("{\"burst\":%06d}", i) + if !strings.HasPrefix(string(line), want) { + t.Fatalf("buffered frame %d = %q, want prefix %q (flush ordering broken)", i, line, want) + } + } + + // 3. Then live output: a frame sent now echoes back only after + // everything buffered. + if _, err := conn.Write([]byte("{\"live\":true}\n")); err != nil { + t.Fatalf("write live frame: %v", err) + } + line, err = r.ReadBytes('\n') + if err != nil { + t.Fatalf("read live echo: %v", err) + } + if string(line) != "{\"live\":true}\n" { + t.Fatalf("live frame = %q, want the echo after the buffered burst", line) + } + + conn.Close() + _ = syscall.Kill(reply.PID, syscall.SIGKILL) + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("supervisor did not exit after child exit") + } +} From 3a272fbb7d95e369bb8953cd1575907ab1151fba Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 19:37:03 -0500 Subject: [PATCH 2/3] =?UTF-8?q?fix(mcpx):=20supervisor=20=E2=80=94=20atomi?= =?UTF-8?q?c=20unattached=20buffer=20append=20+=20flush=20barrier=20before?= =?UTF-8?q?=20final=20close=20(#2390,=20Codex=20P2s=20on=20#2861)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/mcpx/internal/mcpclient/supervised.go | 37 +++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/pkgs/mcpx/internal/mcpclient/supervised.go b/pkgs/mcpx/internal/mcpclient/supervised.go index e396dcfb98..d921e48af7 100644 --- a/pkgs/mcpx/internal/mcpclient/supervised.go +++ b/pkgs/mcpx/internal/mcpclient/supervised.go @@ -97,6 +97,23 @@ func (w *connWriter) flushLocked(reply supervisorReply, buffered []byte) error { // Close closes the underlying connection. func (w *connWriter) Close() { w.conn.Close() } +// closeAfterFlush closes the connection only after any in-flight +// initial flush completes (Codex P2 on PR #2861). handleAttach holds +// w.mu across the publish of w and the handshake+buffer flush, so +// acquiring w.mu here is a barrier on that flush: without it, +// finishWhenDone could observe pumpDone (child exited with no further +// stdout during the flush), see attachedEver && !reported, and close +// the connection mid-flush, losing bytes already drained from the +// tail buffer. The barrier is bounded — every flush write carries +// AttachedWriteTimeout, and at finishWhenDone's call sites the stdout +// pump has already exited, so the flush is the only holder it can +// wait on. No connection write happens under s.mu. +func (w *connWriter) closeAfterFlush() { + w.mu.Lock() + w.mu.Unlock() + w.Close() +} + type supervisorHandshake struct { Version int `json:"version"` } @@ -369,8 +386,22 @@ func (s *supervisor) pumpStdout() { n, err := s.stdoutR.Read(chunk) if n > 0 { data := chunk[:n] + // The unattached decision and the tail-buffer append + // are atomic under s.mu (Codex P2 on PR #2861): if the + // snapshot is nil, the append happens while still + // holding s.mu, so a chunk read just before an attach + // is either inside the buffer that attach drains or + // routed to the published writer — never stranded in + // the buffer behind a live stream, which would + // withhold it and reverse stream order. buf.Write is + // a bounded memory append, not a connection write, so + // holding s.mu across it does not restore the #2390 + // hazard. s.mu.Lock() w := s.attached + if w == nil { + s.buf.Write(data) + } s.mu.Unlock() if w != nil { if _, werr := w.Write(data); werr != nil { @@ -390,8 +421,6 @@ func (s *supervisor) pumpStdout() { w.Close() s.signal() } - } else { - s.buf.Write(data) } } if err != nil { @@ -544,7 +573,7 @@ func (s *supervisor) finishWhenDone() { case <-grace.C: } } - attached.Close() + attached.closeAfterFlush() s.mu.Lock() if s.attached == attached { s.attached = nil @@ -564,7 +593,7 @@ func (s *supervisor) finishWhenDone() { attached := s.attached s.mu.Unlock() if attached != nil { - attached.Close() + attached.closeAfterFlush() } if s.ln != nil { s.ln.Close() From f83a26a29ea21764fec6ba759fdedc82268ed93e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 19:43:05 -0500 Subject: [PATCH 3/3] =?UTF-8?q?fix(mcpx):=20supervisor=20=E2=80=94=20route?= =?UTF-8?q?=20failed-write=20recovery=20chunks=20to=20a=20replacement=20at?= =?UTF-8?q?tachment=20(#2390,=20Codex=20P2=20round=202=20on=20#2861)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/mcpx/internal/mcpclient/supervised.go | 33 ++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/pkgs/mcpx/internal/mcpclient/supervised.go b/pkgs/mcpx/internal/mcpclient/supervised.go index d921e48af7..35ce7e08a0 100644 --- a/pkgs/mcpx/internal/mcpclient/supervised.go +++ b/pkgs/mcpx/internal/mcpclient/supervised.go @@ -412,12 +412,41 @@ func (s *supervisor) pumpStdout() { // it still points at this same writer, so a // newer attach is never cleared by a stale // pump error. - s.buf.Write(data) + // + // The recovery is coordinated with attach + // drain/publication (Codex P2 on PR #2861): + // the current writer is snapshotted under + // s.mu, and when there is no replacement the + // tail-buffer append also happens under + // s.mu — atomic with the next attach's + // drain, as in the unattached path above. + // When a newer writer has already replaced + // w, the chunk belongs to the live stream: + // it is routed to that writer (outside + // s.mu, serialised on the writer's mutex, + // behind its initial flush) instead of + // being stranded in the buffer behind the + // live chunks that follow. s.mu.Lock() - if s.attached == w { + cur := s.attached + if cur == w { s.attached = nil } + if cur == nil || cur == w { + s.buf.Write(data) + } s.mu.Unlock() + if cur != nil && cur != w { + if _, rerr := cur.Write(data); rerr != nil { + s.buf.Write(data) + s.mu.Lock() + if s.attached == cur { + s.attached = nil + } + s.mu.Unlock() + cur.Close() + } + } w.Close() s.signal() }