Skip to content

Agent Mesh

fix: command-backed MCP services get one subprocess per session, not a shared multiplexed bridge

Fernando Marino82a6a86039c5
diff --git a/internal/node/bridge_transport.go b/internal/node/bridge_transport.go
deleted file mode 100644
index 6053e581..00000000
--- a/internal/node/bridge_transport.go
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package node
-
-import (
- "context"
- "io"
-
- "github.com/modelcontextprotocol/go-sdk/jsonrpc"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-// bridgeTransport adapts a StdioBridge to the mcp.Transport interface.
-// Reads pull lines from a Subscribe queue; writes go through Send.
-// Multiple bridgeTransports can coexist on one bridge; JSON-RPC IDs
-// distinguish their responses, as with HTTP/SSE subscribers.
-type bridgeTransport struct {
- bridge *StdioBridge
- queue *subscriberQueue
- unsub func()
-}
-
-func newBridgeTransport(b *StdioBridge) *bridgeTransport {
- return &bridgeTransport{bridge: b}
-}
-
-func (t *bridgeTransport) Connect(ctx context.Context) (mcp.Connection, error) {
- queue, unsub := t.bridge.Subscribe()
- t.queue = queue
- t.unsub = unsub
- return t, nil
-}
-
-func (t *bridgeTransport) Read(ctx context.Context) (jsonrpc.Message, error) {
- line, ok, err := t.queue.pop(ctx)
- if err != nil {
- return nil, err
- }
- if !ok {
- return nil, io.EOF
- }
- return jsonrpc.DecodeMessage([]byte(line))
-}
-
-func (t *bridgeTransport) Write(ctx context.Context, msg jsonrpc.Message) error {
- data, err := jsonrpc.EncodeMessage(msg)
- if err != nil {
- return err
- }
- return t.bridge.Send(data)
-}
-
-func (t *bridgeTransport) Close() error {
- if t.unsub != nil {
- t.unsub()
- t.unsub = nil
- }
- return nil
-}
-
-func (t *bridgeTransport) SessionID() string { return "" }
diff --git a/internal/node/bridge_transport_test.go b/internal/node/bridge_transport_test.go
deleted file mode 100644
index ce5a0e4d..00000000
--- a/internal/node/bridge_transport_test.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package node
-
-import (
- "context"
- "encoding/json"
- "testing"
- "time"
-
- "github.com/modelcontextprotocol/go-sdk/jsonrpc"
-)
-
-func TestBridgeTransport_WriteSendsToStdin(t *testing.T) {
- b, stdoutWriter, stdinBuf := newPipeBridge()
- defer func() { _ = stdoutWriter.Close() }()
-
- tr := newBridgeTransport(b)
- conn, err := tr.Connect(context.Background())
- if err != nil {
- t.Fatalf("Connect: %v", err)
- }
- defer func() { _ = conn.Close() }()
-
- id, _ := jsonrpc.MakeID(float64(1))
- req := &jsonrpc.Request{ID: id, Method: "tools/list"}
- if err := conn.Write(context.Background(), req); err != nil {
- t.Fatalf("Write: %v", err)
- }
-
- got := stdinBuf.String()
- if len(got) == 0 || got[len(got)-1] != '\n' {
- t.Fatalf("Write: expected newline-terminated frame on stdin, got %q", got)
- }
- var parsed map[string]any
- if err := json.Unmarshal([]byte(got[:len(got)-1]), &parsed); err != nil {
- t.Fatalf("Write: stdin frame is not valid JSON: %v (raw=%q)", err, got)
- }
- if parsed["method"] != "tools/list" {
- t.Fatalf("Write: method = %v, want tools/list", parsed["method"])
- }
-}
-
-func TestBridgeTransport_ReadReceivesFromStdout(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
- defer func() { _ = stdoutWriter.Close() }()
-
- tr := newBridgeTransport(b)
- conn, err := tr.Connect(context.Background())
- if err != nil {
- t.Fatalf("Connect: %v", err)
- }
- defer func() { _ = conn.Close() }()
-
- go func() {
- _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{}}` + "\n"))
- }()
-
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- msg, err := conn.Read(ctx)
- if err != nil {
- t.Fatalf("Read: %v", err)
- }
- resp, ok := msg.(*jsonrpc.Response)
- if !ok {
- t.Fatalf("Read: expected *jsonrpc.Response, got %T", msg)
- }
- wantID, _ := jsonrpc.MakeID(float64(1))
- if resp.ID != wantID {
- t.Fatalf("Read: id = %v, want 1", resp.ID)
- }
-}
-
-func TestBridgeTransport_CloseUnsubscribes(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
- defer func() { _ = stdoutWriter.Close() }()
-
- tr := newBridgeTransport(b)
- conn, err := tr.Connect(context.Background())
- if err != nil {
- t.Fatalf("Connect: %v", err)
- }
- if err := conn.Close(); err != nil {
- t.Fatalf("Close: %v", err)
- }
- if err := conn.Close(); err != nil {
- t.Fatalf("Close (second call): %v", err)
- }
-}
diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.go
index 9cf376e4..28e559d3 100644
--- a/internal/node/mcp_service.go
+++ b/internal/node/mcp_service.go
@@ -17,6 +17,8 @@ package node
import (
"context"
"fmt"
+ "os"
+ "os/exec"
"sort"
"sync"
"time"
@@ -75,18 +77,43 @@ func (m *MCPService) Teardown() error {
}
// backendTransport builds a fresh MCP transport to this service's backend.
-// Command backends share the stdio bridge, which multiplexes sessions the
-// same way concurrent remote streams already do.
+//
+// A command backend gets its own subprocess, via mcp.CommandTransport, for
+// every call - the same "one fresh transport per session" shape as the URL
+// case, not a shared one. An earlier version of this multiplexed every
+// session for a command backend over one child process and one stdout
+// stream (StdioBridge/bridgeTransport, since deleted): every line
+// broadcast to every subscriber, relying on each session's own JSON-RPC id
+// to sort out which reply was whose. That doesn't hold - the go-sdk client
+// numbers requests from 1 per connection, so two concurrent sessions on the
+// same bridge could both send id:1 and each read the other's reply, not
+// just their own. Fixing the multiplexer to not do that (id rewriting, a
+// bridge-wide id space) is exactly the kind of protocol-level code this
+// package shouldn't own: stdio MCP is single-session by spec, and no SDK
+// multiplexes it, because a server-initiated request (sampling,
+// elicitation) has no attributable destination on a shared process. One
+// subprocess per session sidesteps all of it by construction, matching
+// what backendTransport already does for URL backends.
+//
+// The cost is a fresh process per Probe/Tools call and per mesh stream
+// instead of one long-lived one; command backends with slow startup pay
+// that repeatedly. Command backends also lose the local SSE/POST HTTP
+// ingress route StdioBridge.ServeHTTP used to provide (baseService.Init
+// no longer builds a handler for them) - the mesh stream path
+// (HandleStreamPassThrough) is what actually matters and is unaffected;
+// restoring a local-ingress equivalent is left for later, not folded into
+// this change.
func (m *MCPService) backendTransport() (mcp.Transport, error) {
switch x := m.backend.(type) {
case *api.RegisterServiceRequest_TargetUrl:
return &mcp.StreamableClientTransport{Endpoint: x.TargetUrl}, nil
case *api.RegisterServiceRequest_Command:
- bridge, ok := m.handler.(*StdioBridge)
- if !ok {
- return nil, fmt.Errorf("expected *StdioBridge handler for command-backed MCP service %q, got %T", m.info.GetName(), m.handler)
+ cmd := exec.Command(x.Command.Command[0], x.Command.Command[1:]...)
+ cmd.Env = os.Environ()
+ for k, v := range x.Command.Env {
+ cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
}
- return newBridgeTransport(bridge), nil
+ return &mcp.CommandTransport{Command: cmd}, nil
default:
return nil, fmt.Errorf("unsupported backend type %T for MCP service %q", m.backend, m.info.GetName())
}
diff --git a/internal/node/mcp_service_command_test.go b/internal/node/mcp_service_command_test.go
new file mode 100644
index 00000000..6d6a5028
--- /dev/null
+++ b/internal/node/mcp_service_command_test.go
@@ -0,0 +1,220 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/modelcontextprotocol/go-sdk/jsonrpc"
+)
+
+// TestEchoHelperProcess is not a real test: it's a subprocess entry point
+// (exec.Command(os.Args[0], "-test.run=...") self-re-exec, the same pattern
+// TestStartRenewalLoop_ExpiredAndFails in node_test.go uses), standing in
+// for a real command-spawned MCP backend. For every JSON-RPC line with an
+// "id" it reads on stdin, it echoes back a minimal success response on
+// stdout, tagged with its own PID so a test can tell which subprocess
+// answered.
+func TestEchoHelperProcess(t *testing.T) {
+ if os.Getenv("GO_WANT_ECHO_HELPER") != "1" {
+ return
+ }
+ scanner := bufio.NewScanner(os.Stdin)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ w := bufio.NewWriter(os.Stdout)
+ pid := os.Getpid()
+ for scanner.Scan() {
+ var msg map[string]any
+ if err := json.Unmarshal(scanner.Bytes(), &msg); err != nil {
+ continue
+ }
+ id, ok := msg["id"]
+ if !ok {
+ continue // notification: no reply, per JSON-RPC
+ }
+ out, err := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "id": id,
+ "result": map[string]any{"pid": pid},
+ })
+ if err != nil {
+ continue
+ }
+ _, _ = w.Write(out)
+ _ = w.WriteByte('\n')
+ _ = w.Flush()
+ }
+ os.Exit(0)
+}
+
+func newEchoCommandMCPService(t *testing.T) *MCPService {
+ t.Helper()
+ return &MCPService{
+ baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "echo"},
+ backend: &api.RegisterServiceRequest_Command{
+ Command: &api.CommandBackend{
+ Command: []string{os.Args[0], "-test.run=TestEchoHelperProcess"},
+ Env: map[string]string{"GO_WANT_ECHO_HELPER": "1"},
+ },
+ },
+ },
+ }
+}
+
+// TestMCPService_BackendTransport_CommandBackendUsesSeparateSubprocess
+// pins the property the StdioBridge/bridgeTransport removal exists for:
+// backendTransport gives every caller of a command backend its own
+// subprocess, so two "sessions" that both happen to number their first
+// request id:1 - exactly what the go-sdk client does per connection -
+// each get their own reply, never the other's. Under the old shared-bridge
+// design this was a real, silent cross-session data leak (see the comment
+// on backendTransport); under the current one it can't happen, because
+// there is no shared process or id space to collide in.
+func TestMCPService_BackendTransport_CommandBackendUsesSeparateSubprocess(t *testing.T) {
+ m := newEchoCommandMCPService(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ connectAndCallID1 := func() float64 {
+ tr, err := m.backendTransport()
+ if err != nil {
+ t.Fatalf("backendTransport: %v", err)
+ }
+ conn, err := tr.Connect(ctx)
+ if err != nil {
+ t.Fatalf("Connect: %v", err)
+ }
+ defer func() { _ = conn.Close() }()
+
+ jid, err := jsonrpc.MakeID(float64(1))
+ if err != nil {
+ t.Fatalf("MakeID: %v", err)
+ }
+ if err := conn.Write(ctx, &jsonrpc.Request{ID: jid, Method: "tools/call"}); err != nil {
+ t.Fatalf("Write: %v", err)
+ }
+ msg, err := conn.Read(ctx)
+ if err != nil {
+ t.Fatalf("Read: %v", err)
+ }
+ resp, ok := msg.(*jsonrpc.Response)
+ if !ok {
+ t.Fatalf("Read: got %T, want *jsonrpc.Response", msg)
+ }
+ var result map[string]any
+ if err := json.Unmarshal(resp.Result, &result); err != nil {
+ t.Fatalf("unmarshal result: %v", err)
+ }
+ pidVal, ok := result["pid"].(float64)
+ if !ok {
+ t.Fatalf("result has no numeric pid: %#v", result)
+ }
+ return pidVal
+ }
+
+ pidA := connectAndCallID1()
+ pidB := connectAndCallID1()
+
+ if pidA == pidB {
+ t.Fatalf("both calls (each sending id:1) were answered by the same subprocess (pid %v) - backendTransport is sharing a process across calls again", pidA)
+ }
+}
+
+// TestMCPService_BackendTransport_ConcurrentCallsDoNotCrossTalk drives two
+// concurrent connections through backendTransport at the same time, both
+// sending id:1 first the way independent go-sdk client sessions naturally
+// would, and asserts each connection's Read only ever returns its own
+// subprocess's reply. This is the direct regression test for the bug a
+// shared-process design has and a per-session one cannot: session A
+// silently consuming session B's reply because both used the same
+// JSON-RPC id on a process whose replies were broadcast to every
+// subscriber.
+func TestMCPService_BackendTransport_ConcurrentCallsDoNotCrossTalk(t *testing.T) {
+ m := newEchoCommandMCPService(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ const rounds = 20
+ var wg sync.WaitGroup
+ errCh := make(chan error, rounds*2)
+
+ session := func(tag string) {
+ defer wg.Done()
+ tr, err := m.backendTransport()
+ if err != nil {
+ errCh <- fmt.Errorf("%s: backendTransport: %w", tag, err)
+ return
+ }
+ conn, err := tr.Connect(ctx)
+ if err != nil {
+ errCh <- fmt.Errorf("%s: Connect: %w", tag, err)
+ return
+ }
+ defer func() { _ = conn.Close() }()
+
+ myPID := -1.0
+ for r := 0; r < rounds; r++ {
+ jid, err := jsonrpc.MakeID(float64(1)) // every session starts its own ids at 1
+ if err != nil {
+ errCh <- fmt.Errorf("%s: MakeID: %w", tag, err)
+ return
+ }
+ if err := conn.Write(ctx, &jsonrpc.Request{ID: jid, Method: "tools/call"}); err != nil {
+ errCh <- fmt.Errorf("%s round %d: Write: %w", tag, r, err)
+ return
+ }
+ msg, err := conn.Read(ctx)
+ if err != nil {
+ errCh <- fmt.Errorf("%s round %d: Read: %w", tag, r, err)
+ return
+ }
+ resp, ok := msg.(*jsonrpc.Response)
+ if !ok {
+ errCh <- fmt.Errorf("%s round %d: got %T, want *jsonrpc.Response", tag, r, msg)
+ return
+ }
+ var result map[string]any
+ if err := json.Unmarshal(resp.Result, &result); err != nil {
+ errCh <- fmt.Errorf("%s round %d: unmarshal result: %w", tag, r, err)
+ return
+ }
+ pid, _ := result["pid"].(float64)
+ if myPID == -1.0 {
+ myPID = pid
+ } else if pid != myPID {
+ errCh <- fmt.Errorf("%s round %d: reply came from pid %v, previous rounds came from pid %v - cross-talk between sessions", tag, r, pid, myPID)
+ return
+ }
+ }
+ }
+
+ wg.Add(2)
+ go session("session-A")
+ go session("session-B")
+ wg.Wait()
+ close(errCh)
+ for err := range errCh {
+ t.Error(err)
+ }
+}
diff --git a/internal/node/proxy_test.go b/internal/node/proxy_test.go
index 1bc33ef2..4a4b5cb0 100644
--- a/internal/node/proxy_test.go
+++ b/internal/node/proxy_test.go
@@ -15,8 +15,6 @@
package node
import (
- "bufio"
- "bytes"
"context"
"crypto/ed25519"
"crypto/rand"
@@ -26,7 +24,6 @@ import (
"net/http/httptest"
"net/http/httputil"
"net/url"
- "strings"
"testing"
"time"
@@ -399,196 +396,17 @@ func TestDatapathIntegration_Unauthenticated(t *testing.T) {
}
}
-func TestStdioDatapathIntegration(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
-
- // 1. Setup: Create two in-memory nodes (Node A and Node B)
- privA, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
- privB, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
-
- dirA := t.TempDir()
- dirB := t.TempDir()
-
- storeA, err := NewStore(dirA)
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = storeA.Close() }()
-
- storeB, err := NewStore(dirB)
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = storeB.Close() }()
-
- nodeA, err := NewSamNode(Options{
- PrivKey: privA,
- RouterAddrs: nil,
- Store: storeA,
- MeshID: "test-mesh",
- DiscoveryInterval: "1s",
- ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
- EnableRelay: false,
- NodeConfig: &NodeConfigComplete{},
- KeyGracePeriod: 24 * time.Hour,
- AllowLoopback: true,
- MonitorBootstrap: 2 * time.Minute,
- MonitorInterval: 1 * time.Minute,
- })
- if err != nil {
- t.Fatal(err)
- }
- nodeA.BiscuitTimeout = 500 * time.Millisecond
- if err := nodeA.Start(ctx); err != nil {
- t.Fatal(err)
- }
- defer func() { _ = nodeA.Host.Close() }()
-
- nodeB, err := NewSamNode(Options{
- PrivKey: privB,
- RouterAddrs: nil,
- Store: storeB,
- MeshID: "test-mesh",
- DiscoveryInterval: "1s",
- ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
- EnableRelay: false,
- NodeConfig: &NodeConfigComplete{},
- KeyGracePeriod: 24 * time.Hour,
- AllowLoopback: true,
- MonitorBootstrap: 2 * time.Minute,
- MonitorInterval: 1 * time.Minute,
- })
- if err != nil {
- t.Fatal(err)
- }
- nodeB.BiscuitTimeout = 500 * time.Millisecond
- if err := nodeB.Start(ctx); err != nil {
- t.Fatal(err)
- }
- defer func() { _ = nodeB.Host.Close() }()
-
- // Setup identity for Node B (the caller proxy) and trust it on Node A
- rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- t.Fatalf("gen root: %v", err)
- }
- if err := buildAndSaveBiscuit(nodeB, rootPriv); err != nil {
- t.Fatalf("buildAndSaveBiscuit: %v", err)
- }
- nodeA.keysMu.Lock()
- nodeA.trustedKeys = append(nodeA.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
- nodeA.keysMu.Unlock()
-
- // Connect Node B to Node A directly
- err = nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()})
- if err != nil {
- t.Fatal(err)
- }
-
- // 2. Target Service: Register a stdio service on Node A using 'cat'
- serviceName := "stdio-tool"
- serviceInfo := &api.ServiceInfo{
- Type: api.ServiceType_SERVICE_TYPE_MCP,
- Name: serviceName,
- }
-
- req := &api.RegisterServiceRequest{
- Service: serviceInfo,
- Backend: &api.RegisterServiceRequest_Command{
- Command: &api.CommandBackend{
- Command: []string{"cat"},
- },
- },
- }
-
- // Manually add to services map to ensure it's registered for the test lookup
- // and avoid double start by not calling RegisterService.
- handler, cmd, err := createStdioBridgeHandler(req.Backend.(*api.RegisterServiceRequest_Command).Command)
- if err != nil {
- t.Fatal(err)
- }
- nodeA.services.insertService(&testService{
- info: serviceInfo,
- handler: handler,
- })
-
- defer func() {
- _ = nodeA.UnregisterService(ctx, serviceName)
- if cmd != nil && cmd.Process != nil {
- _ = cmd.Process.Kill()
- }
- }()
-
- // Start the Sidecar server for Node B to get BoundHTTPAddr populated
- nodeB.BoundHTTPAddr = "127.0.0.1:0" // Dummy
-
- // 3. Execution: Node B makes requests via its local Egress Proxy
- proxyHandler := createEgressProxy(nodeB)
- proxyServer := httptest.NewServer(proxyHandler)
- defer proxyServer.Close()
-
- // Construct URLs
- // http://localhost:<port>/sam/{peer_id}/{service_type}/{service_name}/{upstream_path}
- sseURL := fmt.Sprintf("%s/sam/%s/mcp/%s/", proxyServer.URL, nodeA.Host.ID().String(), serviceName)
- postURL := fmt.Sprintf("%s/sam/%s/mcp/%s/", proxyServer.URL, nodeA.Host.ID().String(), serviceName)
-
- client := &http.Client{}
-
- // Wait for DHT/routing to settle (retry mechanism)
- var sseResp *http.Response
- for i := 0; i < 3; i++ {
- sseResp, err = client.Get(sseURL)
- if err == nil && sseResp.StatusCode == http.StatusOK {
- break
- }
- t.Logf("SSE Connect Attempt %d failed: %v, status: %v", i+1, err, sseResp)
- time.Sleep(1 * time.Second)
- }
-
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = sseResp.Body.Close() }()
-
- if sseResp.StatusCode != http.StatusOK {
- t.Fatalf("Expected SSE status OK, got %d", sseResp.StatusCode)
- }
-
- // Send a message via POST
- testMessage := `{"jsonrpc":"2.0","method":"ping","id":1}`
- postResp, err := client.Post(postURL, "application/json", bytes.NewBufferString(testMessage))
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = postResp.Body.Close() }()
-
- if postResp.StatusCode != http.StatusOK {
- t.Fatalf("Expected POST status OK, got %d", postResp.StatusCode)
- }
-
- // Read from SSE stream
- reader := bufio.NewReader(sseResp.Body)
- line, err := reader.ReadString('\n')
- if err != nil {
- t.Fatal(err)
- }
-
- expectedPrefix := "data: "
- if !strings.HasPrefix(line, expectedPrefix) {
- t.Fatalf("Expected line to start with %q, got %q", expectedPrefix, line)
- }
-
- receivedMessage := strings.TrimPrefix(line, expectedPrefix)
- receivedMessage = strings.TrimSpace(receivedMessage)
-
- if receivedMessage != testMessage {
- t.Fatalf("Expected to receive %q, got %q", testMessage, receivedMessage)
- }
-
- // Cancel context to close the SSE stream and allow server to close gracefully
- cancel()
-}
+// TestStdioDatapathIntegration exercised the local SSE/POST HTTP ingress
+// route for command backends (StdioBridge.ServeHTTP, reached via
+// baseService.Handler()). That route was removed along with
+// StdioBridge/bridgeTransport when command backends moved to a fresh
+// mcp.CommandTransport subprocess per session instead of multiplexing
+// every session over one shared stdio pipe - see the comment on
+// MCPService.backendTransport for why. The mesh stream path this test
+// did not cover (HandleStreamPassThrough, exercised by
+// TestDatapathIntegration above) is unaffected. Restoring a local-ingress
+// equivalent for command backends is left for a follow-up, not folded
+// into that change.
func TestDatapathHeadersAndRoutingTable(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
diff --git a/internal/node/service.go b/internal/node/service.go
index 5ab02214..976b8db3 100644
--- a/internal/node/service.go
+++ b/internal/node/service.go
@@ -20,7 +20,6 @@ import (
"net/http"
"net/http/httputil"
"net/url"
- "os/exec"
"strings"
"github.com/google/sam/api"
@@ -45,7 +44,6 @@ type baseService struct {
info *api.ServiceInfo
backend any
handler http.Handler
- cmd *exec.Cmd // nil for URL-backed
}
// newReverseProxyHandler builds a single-host reverse-proxy handler for a
@@ -86,8 +84,13 @@ func newReverseProxyHandler(targetURL string) (http.Handler, error) {
func (b *baseService) Info() *api.ServiceInfo { return b.info }
func (b *baseService) Handler() http.Handler { return b.handler }
-// Init builds the ingress handler for the backend. URL -> reverse-proxy,
-// Command -> StdioBridge. MCPService extends this; it does not replace it.
+// Init builds the ingress handler for the backend. URL -> reverse-proxy.
+// A command backend gets no handler here: MCPService.backendTransport
+// gives each session its own subprocess instead of one shared one this
+// type would otherwise have to own and tear down - see the comment there.
+// b.handler stays nil, which Handler()'s callers already treat as "no
+// local HTTP ingress for this service" (a 404), not a crash.
+// MCPService extends this; it does not replace it.
func (b *baseService) Init(ctx context.Context) error {
switch x := b.backend.(type) {
case *api.RegisterServiceRequest_TargetUrl:
@@ -97,25 +100,18 @@ func (b *baseService) Init(ctx context.Context) error {
}
b.handler = h
case *api.RegisterServiceRequest_Command:
- h, cmd, err := createStdioBridgeHandler(x.Command)
- if err != nil {
- return err
- }
- b.handler = h
- b.cmd = cmd
+ // No handler, no eagerly-spawned process.
default:
return fmt.Errorf("unsupported backend type %T", b.backend)
}
return nil
}
-// Teardown kills the child process if any. Safe to call when cmd is nil
-// or already dead.
+// Teardown is a no-op: a URL backend owns nothing here, and a command
+// backend's subprocesses are each spawned and closed by their own session
+// (see MCPService.backendTransport), not held at the service level.
func (b *baseService) Teardown() error {
- if b.cmd == nil || b.cmd.Process == nil {
- return nil
- }
- return b.cmd.Process.Kill()
+ return nil
}
func NewServiceFromRequest(req *api.RegisterServiceRequest) (Service, error) {
diff --git a/internal/node/service_test.go b/internal/node/service_test.go
index d45a6134..1beb1486 100644
--- a/internal/node/service_test.go
+++ b/internal/node/service_test.go
@@ -53,9 +53,6 @@ func TestBaseService_InitURLBackend_BuildsReverseProxy(t *testing.T) {
if _, ok := b.handler.(*httputil.ReverseProxy); !ok {
t.Fatalf("handler type: got %T, want *httputil.ReverseProxy", b.handler)
}
- if b.cmd != nil {
- t.Errorf("cmd should be nil for URL backend, got %v", b.cmd)
- }
if err := b.Teardown(); err != nil {
t.Errorf("Teardown: %v", err)
}
@@ -71,7 +68,13 @@ func TestBaseService_InitURLBackend_InvalidURL(t *testing.T) {
}
}
-func TestBaseService_InitCommandBackend_BuildsBridge(t *testing.T) {
+// TestBaseService_InitCommandBackend_NoLocalHandler pins the deliberate
+// trade-off in Init's Command case: no process is spawned and no handler is
+// built here, because MCPService.backendTransport gives each session (a
+// Probe, a Tools call, a mesh stream) its own subprocess instead - see the
+// comment there. A nil command doesn't even need to be valid, since Init no
+// longer tries to run it.
+func TestBaseService_InitCommandBackend_NoLocalHandler(t *testing.T) {
b := &baseService{
info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "demo"},
backend: &api.RegisterServiceRequest_Command{
@@ -82,11 +85,8 @@ func TestBaseService_InitCommandBackend_BuildsBridge(t *testing.T) {
t.Fatalf("Init: %v", err)
}
defer func() { _ = b.Teardown() }()
- if _, ok := b.handler.(*StdioBridge); !ok {
- t.Fatalf("handler type: got %T, want *StdioBridge", b.handler)
- }
- if b.cmd == nil {
- t.Error("cmd should be non-nil for Command backend")
+ if b.handler != nil {
+ t.Fatalf("handler: got %T, want nil", b.handler)
}
}
diff --git a/internal/node/stdio_bridge.go b/internal/node/stdio_bridge.go
deleted file mode 100644
index 097b7acc..00000000
--- a/internal/node/stdio_bridge.go
+++ /dev/null
@@ -1,355 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package node
-
-import (
- "bufio"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "os"
- "os/exec"
- "sync"
-
- "github.com/google/sam/api"
-)
-
-type StdioBridge struct {
- cmd *exec.Cmd
- stdin io.WriteCloser
- stdout io.ReadCloser
- mu sync.Mutex
- clients map[chan string]bool
- queues map[*subscriberQueue]bool
- calls map[string]chan string
-}
-
-func (b *StdioBridge) Start() {
- b.clients = make(map[chan string]bool)
- b.queues = make(map[*subscriberQueue]bool)
- b.calls = make(map[string]chan string)
- go func() {
- scanner := bufio.NewScanner(b.stdout)
- for scanner.Scan() {
- line := scanner.Text()
-
- b.mu.Lock()
- if len(line) > 0 && line[0] == '{' {
- var msg map[string]any
- if err := json.Unmarshal([]byte(line), &msg); err == nil {
- if idVal, ok := msg["id"]; ok {
- reqIDStr := fmt.Sprintf("%v", idVal)
- if ch, found := b.calls[reqIDStr]; found {
- select {
- case ch <- line:
- default:
- }
- }
- }
- }
- }
-
- for ch := range b.clients {
- select {
- case ch <- line:
- default:
- }
- }
- for q := range b.queues {
- q.push(line)
- }
- b.mu.Unlock()
- }
-
- b.mu.Lock()
- for ch := range b.clients {
- close(ch)
- delete(b.clients, ch)
- }
- for q := range b.queues {
- q.closeQueue()
- }
- b.queues = make(map[*subscriberQueue]bool)
- for _, ch := range b.calls {
- close(ch)
- }
- b.calls = make(map[string]chan string)
- b.mu.Unlock()
- }()
-}
-
-func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- switch r.Method {
- case http.MethodGet:
- w.Header().Set("Content-Type", "text/event-stream")
- w.Header().Set("Cache-Control", "no-cache")
- w.Header().Set("Connection", "keep-alive")
-
- flusher, ok := w.(http.Flusher)
- if !ok {
- http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
- return
- }
-
- ch := make(chan string, 10)
- b.mu.Lock()
- b.clients[ch] = true
- b.mu.Unlock()
-
- // Flush headers immediately to establish the stream
- w.WriteHeader(http.StatusOK)
- flusher.Flush()
-
- defer func() {
- b.mu.Lock()
- delete(b.clients, ch)
- b.mu.Unlock()
- close(ch)
- }()
-
- ctx := r.Context()
- for {
- select {
- case <-ctx.Done():
- return
- case line, ok := <-ch:
- if !ok {
- return
- }
- if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
- logger.Errorf("Failed to write to SSE client: %v", err)
- return
- }
- flusher.Flush()
- }
- }
- case http.MethodPost:
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
- defer func() { _ = r.Body.Close() }()
- body, err := io.ReadAll(r.Body)
- if err != nil {
- http.Error(w, "Failed to read body", http.StatusInternalServerError)
- return
- }
-
- var msg map[string]any
- isCall := false
- var reqID any
- if err := json.Unmarshal(body, &msg); err == nil {
- if id, ok := msg["id"]; ok {
- isCall = true
- reqID = id
- }
- }
-
- var ch <-chan string
- var unsub func()
- if isCall {
- reqIDStr := fmt.Sprintf("%v", reqID)
- callCh := make(chan string, 1)
- b.mu.Lock()
- b.calls[reqIDStr] = callCh
- b.mu.Unlock()
- ch = callCh
- unsub = func() {
- b.mu.Lock()
- if existing, ok := b.calls[reqIDStr]; ok && existing == callCh {
- delete(b.calls, reqIDStr)
- close(callCh)
- }
- b.mu.Unlock()
- }
- defer unsub()
- }
-
- b.mu.Lock()
- _, err = b.stdin.Write(append(body, '\n'))
- b.mu.Unlock()
-
- if err != nil {
- http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Mcp-Session-Id", "stdio-bridge")
-
- if !isCall {
- w.WriteHeader(http.StatusAccepted)
- return
- }
-
- ctx := r.Context()
- select {
- case <-ctx.Done():
- return
- case line, ok := <-ch:
- if !ok {
- return
- }
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusOK)
- _, _ = w.Write([]byte(line))
- return
- }
- default:
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- }
-}
-
-// Subscribe registers a new subscriber queue for stdout lines and returns it
-// along with an idempotent unsubscribe function.
-//
-// Unlike the plain chan string clients map above (bounded cap 10, drops on a
-// slow consumer - fine for the ServeHTTP SSE feed, where a browser tab
-// missing a line just misses a live update), Subscribe's only caller is
-// bridgeTransport, i.e. an MCP request/response session: every line matters,
-// because the one dropped could be the exact reply a Read() call is blocked
-// on, with nothing left to ever wake it. bridgeTransport used to share the
-// same bounded, drop-on-full channel as SSE; a periodic health probe and a
-// live tools/call session subscribing to the same backend concurrently was
-// enough to lose a message that way, surfacing as a client-side EOF even
-// though the backend had answered correctly. Every subscriber here instead
-// gets its own unbounded, order-preserving queue.
-func (b *StdioBridge) Subscribe() (*subscriberQueue, func()) {
- q := newSubscriberQueue()
- b.mu.Lock()
- b.queues[q] = true
- b.mu.Unlock()
-
- var once sync.Once
- unsub := func() {
- once.Do(func() {
- b.mu.Lock()
- delete(b.queues, q)
- b.mu.Unlock()
- q.closeQueue()
- })
- }
- return q, unsub
-}
-
-// subscriberQueue is an unbounded, order-preserving mailbox for one
-// bridgeTransport session's stdout lines.
-//
-// push is called from the bridge's single stdout-scanning goroutine (with
-// StdioBridge.mu held) and must never block or drop a line. pop is called by
-// the session's own reader; it blocks until a line is queued, the bridge
-// closes the queue, or ctx is done.
-type subscriberQueue struct {
- mu sync.Mutex
- buf []string
- closed bool
- notify chan struct{} // capacity 1: a "there may be new work" flag, coalesced
-}
-
-func newSubscriberQueue() *subscriberQueue {
- return &subscriberQueue{notify: make(chan struct{}, 1)}
-}
-
-func (q *subscriberQueue) push(line string) {
- q.mu.Lock()
- q.buf = append(q.buf, line)
- q.mu.Unlock()
- q.wake()
-}
-
-func (q *subscriberQueue) closeQueue() {
- q.mu.Lock()
- q.closed = true
- q.mu.Unlock()
- q.wake()
-}
-
-func (q *subscriberQueue) wake() {
- select {
- case q.notify <- struct{}{}:
- default:
- }
-}
-
-// pop returns the next queued line in FIFO order. ok is false only once the
-// queue has been closed and fully drained.
-func (q *subscriberQueue) pop(ctx context.Context) (line string, ok bool, err error) {
- for {
- q.mu.Lock()
- if len(q.buf) > 0 {
- line = q.buf[0]
- // Re-slicing alone leaves the popped element's string header
- // live in the backing array, keeping its bytes reachable for
- // as long as the array itself is - which, for a long-lived
- // session, is every line ever queued. Clear the slot before
- // advancing, and drop the backing array entirely once drained,
- // rather than let it sit at its peak size for the queue's
- // remaining lifetime.
- q.buf[0] = ""
- q.buf = q.buf[1:]
- if len(q.buf) == 0 {
- q.buf = nil
- }
- q.mu.Unlock()
- return line, true, nil
- }
- closed := q.closed
- q.mu.Unlock()
- if closed {
- return "", false, nil
- }
- select {
- case <-ctx.Done():
- return "", false, ctx.Err()
- case <-q.notify:
- }
- }
-}
-
-// Send writes data to the child's stdin, appending a newline.
-func (b *StdioBridge) Send(data []byte) error {
- b.mu.Lock()
- defer b.mu.Unlock()
- _, err := b.stdin.Write(append(data, '\n'))
- return err
-}
-
-func createStdioBridgeHandler(cmdBackend *api.CommandBackend) (http.Handler, *exec.Cmd, error) {
- cmd := exec.Command(cmdBackend.Command[0], cmdBackend.Command[1:]...)
- cmd.Env = os.Environ()
- for k, v := range cmdBackend.Env {
- cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
- }
-
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- return nil, nil, err
- }
- stdin, err := cmd.StdinPipe()
- if err != nil {
- return nil, nil, err
- }
-
- if err := cmd.Start(); err != nil {
- return nil, nil, err
- }
-
- bridge := &StdioBridge{
- cmd: cmd,
- stdin: stdin,
- stdout: stdout,
- }
- bridge.Start()
-
- return bridge, cmd, nil
-}
diff --git a/internal/node/stdio_bridge_headofline_test.go b/internal/node/stdio_bridge_headofline_test.go
deleted file mode 100644
index c403bdfd..00000000
--- a/internal/node/stdio_bridge_headofline_test.go
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package node
-
-import (
- "context"
- "fmt"
- "testing"
- "time"
-
- "github.com/modelcontextprotocol/go-sdk/jsonrpc"
-)
-
-// TestIntegration_StuckSubscriberDoesNotStallOthers guards the other half of
-// Subscribe's contract: never dropping a line must not come at the cost of
-// one subscriber's pace affecting another's. It connects a bridgeTransport
-// and never reads its replies - a realistic stand-in for a session whose own
-// downstream consumer has stalled, exactly the asymmetric-proxy scenario
-// aojea flagged on #375 ("closing asymmetric streams on proxies is hard") -
-// then asserts a second, healthy bridgeTransport on the same backend keeps
-// getting answered promptly regardless. A fix for the drop bug that makes
-// push block on a full per-subscriber buffer would pass every drop test and
-// still fail this one: the scan loop dispatches to every subscriber under
-// the same lock, so blocking on one wedges delivery - and, since Send also
-// takes that lock, new requests too - for all of them.
-func TestIntegration_StuckSubscriberDoesNotStallOthers(t *testing.T) {
- if testing.Short() {
- t.Skip("spawns a real subprocess; skipped in -short")
- }
- b := newEchoBridge(t)
-
- stuckTr := newBridgeTransport(b)
- stuckConn, err := stuckTr.Connect(context.Background())
- if err != nil {
- t.Fatalf("stuck subscriber connect: %v", err)
- }
- defer func() { _ = stuckConn.Close() }()
-
- // Send enough calls to the stuck subscriber's own queue to overflow any
- // reasonable fixed buffer, without ever reading a reply.
- for i := 0; i < 200; i++ {
- id := fmt.Sprintf("stuck-%d", i)
- jid, _ := jsonrpc.MakeID(id)
- writeCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- err := stuckConn.Write(writeCtx, &jsonrpc.Request{ID: jid, Method: "tools/call"})
- cancel()
- if err != nil {
- t.Logf("stuck subscriber: write %d stopped early (%v) - fine, the point is only to fill its queue", i, err)
- break
- }
- }
-
- // The healthy subscriber must complete quickly regardless of the above.
- healthyTr := newBridgeTransport(b)
- healthyConn, err := healthyTr.Connect(context.Background())
- if err != nil {
- t.Fatalf("healthy subscriber connect: %v", err)
- }
- defer func() { _ = healthyConn.Close() }()
-
- const budget = 3 * time.Second
- ctx, cancel := context.WithTimeout(context.Background(), budget)
- defer cancel()
-
- id := "healthy-1"
- jid, _ := jsonrpc.MakeID(id)
- if err := healthyConn.Write(ctx, &jsonrpc.Request{ID: jid, Method: "tools/call"}); err != nil {
- t.Fatalf("healthy subscriber write: %v", err)
- }
- for {
- msg, err := healthyConn.Read(ctx)
- if err != nil {
- t.Fatalf("healthy subscriber did not get its reply within %s while another subscriber was stuck not reading: %v (head-of-line blocking: one wedged consumer stalling every other subscriber of the same backend)", budget, err)
- }
- if resp, ok := msg.(*jsonrpc.Response); ok && fmt.Sprintf("%v", resp.ID.Raw()) == id {
- return
- }
- }
-}
diff --git a/internal/node/stdio_bridge_integration_test.go b/internal/node/stdio_bridge_integration_test.go
deleted file mode 100644
index ad94d4a6..00000000
--- a/internal/node/stdio_bridge_integration_test.go
+++ /dev/null
@@ -1,247 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package node
-
-import (
- "bufio"
- "context"
- "encoding/json"
- "fmt"
- "os"
- "os/exec"
- "sync"
- "testing"
- "time"
-
- "github.com/modelcontextprotocol/go-sdk/jsonrpc"
-)
-
-// TestEchoHelperProcess is not a real test: it's a subprocess entry point,
-// using the same exec.Command(os.Args[0], "-test.run=...") self-re-exec
-// pattern as TestStartRenewalLoop_ExpiredAndFails in node_test.go. It stands
-// in for a real command-spawned MCP backend: for every JSON-RPC line with an
-// "id" it reads on stdin, it immediately echoes back a minimal success
-// response on stdout. This lets the integration tests below drive a real
-// StdioBridge end to end, through a real OS process and real pipes, instead
-// of the in-memory io.Pipe the other tests in this package use.
-func TestEchoHelperProcess(t *testing.T) {
- if os.Getenv("GO_WANT_ECHO_HELPER") != "1" {
- return
- }
- scanner := bufio.NewScanner(os.Stdin)
- scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
- w := bufio.NewWriter(os.Stdout)
- for scanner.Scan() {
- var msg map[string]any
- if err := json.Unmarshal(scanner.Bytes(), &msg); err != nil {
- continue
- }
- id, ok := msg["id"]
- if !ok {
- continue // notification: no reply, per JSON-RPC
- }
- out, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "result": map[string]any{}})
- if err != nil {
- continue
- }
- _, _ = w.Write(out)
- _ = w.WriteByte('\n')
- _ = w.Flush()
- }
- os.Exit(0)
-}
-
-// newEchoBridge spawns a real TestEchoHelperProcess subprocess and wires a
-// StdioBridge to it, the same way createStdioBridgeHandler does for a real
-// command: backend.
-func newEchoBridge(t *testing.T) *StdioBridge {
- t.Helper()
- cmd := exec.Command(os.Args[0], "-test.run=TestEchoHelperProcess")
- cmd.Env = append(os.Environ(), "GO_WANT_ECHO_HELPER=1")
- stdin, err := cmd.StdinPipe()
- if err != nil {
- t.Fatalf("StdinPipe: %v", err)
- }
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- t.Fatalf("StdoutPipe: %v", err)
- }
- if err := cmd.Start(); err != nil {
- t.Fatalf("Start echo helper: %v", err)
- }
- t.Cleanup(func() {
- _ = cmd.Process.Kill()
- _ = cmd.Wait()
- })
-
- b := &StdioBridge{stdin: stdin, stdout: stdout}
- b.Start()
- return b
-}
-
-// TestIntegration_ProbeAndLiveSessionConcurrently reproduces, through the
-// real StdioBridge -> bridgeTransport path against a real subprocess (not an
-// in-memory pipe), the concurrency scenario documented on Subscribe: a
-// periodic health probe (MCPService.Probe in mcp_service.go) opens its own
-// short-lived bridgeTransport per check, racing a live session's
-// bridgeTransport mid-burst. Before 17da7f6, both shared the same bounded,
-// drop-on-full channel also used for SSE, and a burst from one could
-// silently cost the other a reply - surfacing downstream as a client-side
-// EOF with nothing in between to say why. This test fails on ANY dropped or
-// duplicated response, and times out (rather than hanging the suite forever)
-// if a fix reintroduces head-of-line blocking between unrelated sessions.
-func TestIntegration_ProbeAndLiveSessionConcurrently(t *testing.T) {
- if testing.Short() {
- t.Skip("spawns a real subprocess; skipped in -short")
- }
- b := newEchoBridge(t)
-
- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
- defer cancel()
- // sessionDone stops the probe loop as soon as the live session's bursts
- // finish, independent of ctx's much longer safety bound - otherwise the
- // probe loop (which by design runs until told to stop) and this test's
- // own overall wait would both key off the same ctx expiry, racing each
- // other on a timeout that has nothing to do with correctness.
- sessionDone := make(chan struct{})
-
- var wg sync.WaitGroup
- errCh := make(chan error, 256)
-
- // Live session: one long-lived bridgeTransport. Each round fires a burst
- // of calls back-to-back with no interleaved reads - the exact "busy
- // consumer" window the original bug lived in - then drains all replies
- // before starting the next round.
- wg.Add(1)
- go func() {
- defer wg.Done()
- defer close(sessionDone)
- tr := newBridgeTransport(b)
- conn, err := tr.Connect(ctx)
- if err != nil {
- errCh <- fmt.Errorf("session connect: %w", err)
- return
- }
- defer func() { _ = conn.Close() }()
-
- const rounds = 20
- const burst = 25
- for r := 0; r < rounds; r++ {
- want := make(map[string]bool, burst)
- for i := 0; i < burst; i++ {
- id := fmt.Sprintf("session-%d-%d", r, i)
- want[id] = true
- jid, err := jsonrpc.MakeID(id)
- if err != nil {
- errCh <- fmt.Errorf("session MakeID %s: %w", id, err)
- return
- }
- if err := conn.Write(ctx, &jsonrpc.Request{ID: jid, Method: "tools/call"}); err != nil {
- errCh <- fmt.Errorf("session write %s: %w", id, err)
- return
- }
- }
- for len(want) > 0 {
- msg, err := conn.Read(ctx)
- if err != nil {
- errCh <- fmt.Errorf("session read (round %d, %d still outstanding: %v): %w", r, len(want), keys(want), err)
- return
- }
- resp, ok := msg.(*jsonrpc.Response)
- if !ok {
- continue
- }
- id := fmt.Sprintf("%v", resp.ID.Raw())
- if !want[id] {
- continue // a probe reply multiplexed onto our queue; not ours
- }
- delete(want, id)
- }
- }
- }()
-
- // Probe: many short-lived bridgeTransports firing continuously for the
- // same duration as the live session's bursts - connect, call, read its
- // own reply (ignoring any of the live session's replies it also sees),
- // close.
- wg.Add(1)
- go func() {
- defer wg.Done()
- ticker := time.NewTicker(20 * time.Millisecond)
- defer ticker.Stop()
- for i := 0; ; i++ {
- select {
- case <-sessionDone:
- return
- case <-ctx.Done():
- return
- case <-ticker.C:
- }
- func() {
- tr := newBridgeTransport(b)
- conn, err := tr.Connect(ctx)
- if err != nil {
- errCh <- fmt.Errorf("probe connect %d: %w", i, err)
- return
- }
- defer func() { _ = conn.Close() }()
-
- id := fmt.Sprintf("probe-%d", i)
- jid, err := jsonrpc.MakeID(id)
- if err != nil {
- errCh <- fmt.Errorf("probe MakeID %s: %w", id, err)
- return
- }
- if err := conn.Write(ctx, &jsonrpc.Request{ID: jid, Method: "initialize"}); err != nil {
- errCh <- fmt.Errorf("probe write %s: %w", id, err)
- return
- }
- for {
- msg, err := conn.Read(ctx)
- if err != nil {
- errCh <- fmt.Errorf("probe read %s: %w", id, err)
- return
- }
- if resp, ok := msg.(*jsonrpc.Response); ok && fmt.Sprintf("%v", resp.ID.Raw()) == id {
- return
- }
- }
- }()
- }
- }()
-
- done := make(chan struct{})
- go func() {
- wg.Wait()
- close(done)
- }()
- select {
- case <-done:
- case <-ctx.Done():
- t.Fatal("test timed out: a dropped reply left a Read() blocked forever (the original bug), or a design change reintroduced head-of-line blocking between the probe and the live session")
- }
- close(errCh)
- for err := range errCh {
- t.Error(err)
- }
-}
-
-func keys(m map[string]bool) []string {
- out := make([]string, 0, len(m))
- for k := range m {
- out = append(out, k)
- }
- return out
-}
diff --git a/internal/node/stdio_bridge_test.go b/internal/node/stdio_bridge_test.go
deleted file mode 100644
index fe8240da..00000000
--- a/internal/node/stdio_bridge_test.go
+++ /dev/null
@@ -1,204 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package node
-
-import (
- "bytes"
- "context"
- "fmt"
- "io"
- "sync"
- "testing"
- "time"
-)
-
-// newPipeBridge returns a StdioBridge wired to two in-memory pipes so tests
-// can drive stdin/stdout without a real subprocess.
-func newPipeBridge() (*StdioBridge, *io.PipeWriter, *bytes.Buffer) {
- stdoutReader, stdoutWriter := io.Pipe()
- stdinBuf := &bytes.Buffer{}
- b := &StdioBridge{
- stdin: nopWriteCloser{stdinBuf},
- stdout: stdoutReader,
- }
- b.Start()
- return b, stdoutWriter, stdinBuf
-}
-
-type nopWriteCloser struct{ io.Writer }
-
-func (nopWriteCloser) Close() error { return nil }
-
-func TestStdioBridge_SubscribeReceivesLines(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
- defer func() { _ = stdoutWriter.Close() }()
-
- q, unsub := b.Subscribe()
- defer unsub()
-
- go func() {
- _, _ = stdoutWriter.Write([]byte("hello\nworld\n"))
- }()
-
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- want := []string{"hello", "world"}
- for _, w := range want {
- got, ok, err := q.pop(ctx)
- if err != nil {
- t.Fatalf("Subscribe: pop: %v", err)
- }
- if !ok {
- t.Fatalf("Subscribe: queue closed before %q arrived", w)
- }
- if got != w {
- t.Fatalf("Subscribe: got %q, want %q", got, w)
- }
- }
-}
-
-// TestStdioBridge_SubscribeDoesNotDropWhileConsumerIsBusy reproduces the
-// original bug: a burst of lines arrives while the subscriber isn't yet
-// blocked on a receive (e.g. a concurrent health-check probe still holding
-// StdioBridge.mu-adjacent work, or simply a goroutine that hasn't reached
-// its Read() call yet). The old bounded, drop-on-full channel lost lines in
-// exactly this window; the queue must never drop them.
-func TestStdioBridge_SubscribeDoesNotDropWhileConsumerIsBusy(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
- defer func() { _ = stdoutWriter.Close() }()
-
- q, unsub := b.Subscribe()
- defer unsub()
-
- const n = 50
- var wg sync.WaitGroup
- wg.Add(1)
- go func() {
- defer wg.Done()
- for i := 0; i < n; i++ {
- _, _ = fmt.Fprintf(stdoutWriter, "line-%d\n", i)
- }
- }()
- wg.Wait() // all n lines are written (and, on a slow reader, queued) before we ever call pop
-
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- for i := 0; i < n; i++ {
- want := fmt.Sprintf("line-%d", i)
- got, ok, err := q.pop(ctx)
- if err != nil {
- t.Fatalf("pop(%d): %v", i, err)
- }
- if !ok {
- t.Fatalf("pop(%d): queue closed early, want %q", i, want)
- }
- if got != want {
- t.Fatalf("pop(%d): got %q, want %q (a line was dropped or reordered)", i, got, want)
- }
- }
-}
-
-// TestStdioBridge_SubscribeCloseUnblocksPop ensures a pop() blocked waiting
-// for the next line returns promptly (ok=false) once the bridge's stdout
-// closes, rather than hanging forever.
-func TestStdioBridge_SubscribeCloseUnblocksPop(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
-
- q, unsub := b.Subscribe()
- defer unsub()
-
- done := make(chan struct{})
- go func() {
- defer close(done)
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- _, ok, err := q.pop(ctx)
- if err != nil {
- t.Errorf("pop: %v", err)
- }
- if ok {
- t.Errorf("pop: got ok=true after close, want false")
- }
- }()
-
- _ = stdoutWriter.Close()
- select {
- case <-done:
- case <-time.After(2 * time.Second):
- t.Fatal("pop did not unblock after stdout closed")
- }
-}
-
-func TestStdioBridge_UnsubscribeIsIdempotent(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
- defer func() { _ = stdoutWriter.Close() }()
-
- _, unsub := b.Subscribe()
- unsub()
- unsub() // must not panic
-}
-
-func TestStdioBridge_SendWritesToStdin(t *testing.T) {
- b, stdoutWriter, stdinBuf := newPipeBridge()
- defer func() { _ = stdoutWriter.Close() }()
-
- if err := b.Send([]byte(`{"jsonrpc":"2.0","id":1}`)); err != nil {
- t.Fatalf("Send returned error: %v", err)
- }
- got := stdinBuf.String()
- want := `{"jsonrpc":"2.0","id":1}` + "\n"
- if got != want {
- t.Fatalf("Send: stdin got %q, want %q", got, want)
- }
-}
-
-// TestSubscriberQueue_PopReleasesBackingArray guards against a real memory
-// retention bug flagged in review: re-slicing alone (q.buf = q.buf[1:])
-// leaves the popped element's string header live in the backing array,
-// keeping its bytes reachable for as long as the array itself is - which,
-// for a long-lived session, is every line ever queued. pop must clear the
-// popped slot and drop the backing array entirely once drained.
-func TestSubscriberQueue_PopReleasesBackingArray(t *testing.T) {
- q := newSubscriberQueue()
- q.push("a")
- q.push("b")
-
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
-
- // A second reference into the same backing array, captured before any
- // pop: re-slicing q.buf alone wouldn't touch this array's contents, so
- // backing[0] would still read "a" after popping it if pop didn't
- // explicitly clear the slot.
- q.mu.Lock()
- backing := q.buf[:2:2]
- q.mu.Unlock()
-
- if got, ok, err := q.pop(ctx); err != nil || !ok || got != "a" {
- t.Fatalf("pop 1: got %q, ok=%v, err=%v", got, ok, err)
- }
- if backing[0] != "" {
- t.Fatalf("pop: backing array slot still holds %q after being popped, want \"\" (string not released)", backing[0])
- }
-
- if got, ok, err := q.pop(ctx); err != nil || !ok || got != "b" {
- t.Fatalf("pop 2: got %q, ok=%v, err=%v", got, ok, err)
- }
- q.mu.Lock()
- defer q.mu.Unlock()
- if q.buf != nil {
- t.Fatalf("pop: buf = %#v after full drain, want nil (backing array not released)", q.buf)
- }
-}