Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
fix: advertise a service as soon as its backend answers
Antonio Ojeade12fb963116
diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.goindex ead111a9..32b11c26 100644--- a/internal/node/mcp_service.go+++ b/internal/node/mcp_service.go@@ -34,10 +34,6 @@ type MCPService struct {toolsMu sync.MutexcachedTools []stringtoolsExpires time.Time-- probeMu sync.Mutex- probeErr error- probeExpires time.Time}// Probe reports whether the backend actually speaks MCP, by completing an@@ -47,28 +43,12 @@ type MCPService struct {// has no tools and is still a working MCP server, so an empty tool list is no// reason to withhold it. Failing to initialize is — that is a backend which is// down, or was never an MCP server to begin with.+//+// The result is deliberately not cached. Callers are the registry's advertise+// path, which asks once per service per reprovide, so the cost is negligible;+// caching would make a backend that has just come up wait out the TTL, which+// is the delay this gating exists to avoid.func (m *MCPService) Probe(ctx context.Context) error {- if err := ctx.Err(); err != nil {- return err- }- m.probeMu.Lock()- defer m.probeMu.Unlock()- if time.Now().Before(m.probeExpires) {- return m.probeErr- }- err := m.dialBackend(ctx)- // A cancelled or expired context is a fact about the caller, not the- // backend. Caching it would withhold a merely slow service for the whole- // TTL -- the failure this gating is meant to avoid.- if ctxErr := ctx.Err(); ctxErr != nil {- return ctxErr- }- m.probeErr = err- m.probeExpires = time.Now().Add(backendProbeTTL)- return m.probeErr-}--func (m *MCPService) dialBackend(ctx context.Context) error {transport, err := m.backendTransport()if err != nil {return errdiff --git a/internal/node/mcp_service_test.go b/internal/node/mcp_service_test.goindex 2c7ff83e..bc773b99 100644--- a/internal/node/mcp_service_test.go+++ b/internal/node/mcp_service_test.go@@ -18,8 +18,8 @@ import ("context""net/http""net/http/httptest"+ "sync/atomic""testing"- "time""github.com/google/sam/api""github.com/modelcontextprotocol/go-sdk/mcp"@@ -61,14 +61,37 @@ func TestMCPService_ProbeRejectsNonMCPBackend(t *testing.T) {if err := svc.Probe(context.Background()); err == nil {t.Fatal("Probe accepted a backend that is not an MCP server")}- if svc.probeExpires.IsZero() {- t.Error("a real negative result should be cached")+}++// Backends routinely start after the node does, so a failed probe must not be+// sticky: the next one has to see the backend as it is now, not as it was.+func TestMCPService_ProbeRecoversWhenBackendComesUp(t *testing.T) {+ var up atomic.Bool+ real := mcp.NewServer(&mcp.Implementation{Name: "late", Version: "0.0.1"}, nil)+ handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return real }, nil)++ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !up.Load() {+ http.Error(w, "still starting", http.StatusServiceUnavailable)+ return+ }+ handler.ServeHTTP(w, r)+ }))+ t.Cleanup(ts.Close)++ svc := newProbeService(ts.URL)+ if err := svc.Probe(context.Background()); err == nil {+ t.Fatal("Probe accepted a backend that was not serving yet")+ }++ up.Store(true)+ if err := svc.Probe(context.Background()); err != nil {+ t.Errorf("Probe still failing after the backend came up: %v", err)}}-// A cancelled context is a fact about the caller, not the backend. Caching it-// would withhold a healthy service for the whole TTL.-func TestMCPService_ProbeDoesNotCacheContextErrors(t *testing.T) {+// A cancelled context is a fact about the caller, not the backend.+func TestMCPService_ProbeFailsOnCancelledContext(t *testing.T) {svc := newProbeService(newProbeBackend(t).URL)cancelled, cancel := context.WithCancel(context.Background())@@ -76,33 +99,8 @@ func TestMCPService_ProbeDoesNotCacheContextErrors(t *testing.T) {if err := svc.Probe(cancelled); err == nil {t.Fatal("Probe returned nil for a cancelled context")}- if !svc.probeExpires.IsZero() {- t.Fatal("a context error was cached")- }if err := svc.Probe(context.Background()); err != nil {t.Errorf("Probe after a cancelled one: %v", err)}}--// The same, for a context that is alive on entry and expires mid-dial: this is-// the slow backend the gating is explicitly meant not to punish.-func TestMCPService_ProbeDoesNotCacheTimeouts(t *testing.T) {- // Answers, but never within the probe's deadline.- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- time.Sleep(150 * time.Millisecond)- http.Error(w, "too slow", http.StatusServiceUnavailable)- }))- t.Cleanup(ts.Close)-- svc := newProbeService(ts.URL)- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)- defer cancel()-- if err := svc.Probe(ctx); err == nil {- t.Fatal("Probe returned nil against a backend slower than the deadline")- }- if !svc.probeExpires.IsZero() {- t.Error("a timeout was cached: a slow backend would stay withheld for the whole TTL")- }-}diff --git a/internal/node/node.go b/internal/node/node.goindex c4b0bc72..c079da7a 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -430,6 +430,7 @@ func (n *SamNode) Start(ctx context.Context) error {n.DHT = kdhtn.services = NewServiceRegistry(n.DHT)+ n.services.reprovideNow = n.triggerReprovidevar authenticated boolvar fatalAuthErr error@@ -498,10 +499,7 @@ func (n *SamNode) Start(ctx context.Context) error {// Debounce and trigger unified reprovide loopgo func() {time.Sleep(2 * time.Second) // Small debounce- select {- case n.reprovideTrigger <- struct{}{}:- default:- }+ n.triggerReprovide()}()}}@@ -546,6 +544,15 @@ func (n *SamNode) Start(ctx context.Context) error {return nil}+// triggerReprovide asks the reprovide loop to run a cycle now, dropping the+// request when one is already pending.+func (n *SamNode) triggerReprovide() {+ select {+ case n.reprovideTrigger <- struct{}{}:+ default:+ }+}+func (n *SamNode) startReprovideLoop(ctx context.Context, interval time.Duration) {go func() {// Initial delay lets DHT bootstrap stabilize.diff --git a/internal/node/service_registry.go b/internal/node/service_registry.goindex 79ffca7f..ffcc2724 100644--- a/internal/node/service_registry.go+++ b/internal/node/service_registry.go@@ -64,6 +64,11 @@ type ServiceRegistry struct {mu sync.RWMutexservices map[string]Servicedht dhtProvider++ // reprovideNow asks the node to run a reprovide cycle now, so a service+ // registered after the loop last ran does not wait a whole interval to be+ // advertised. Optional; nil outside a running node.+ reprovideNow func()}func NewServiceRegistry(d dhtProvider) *ServiceRegistry {@@ -122,6 +127,8 @@ func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {if probeErr == nil {logger.Infof("[ServiceRegistry] Registered %s/%s (name CID: %s, type CID: %s)", info.Type, info.Name, srvNameCID, srvTypeCID)+ } else if r.reprovideNow != nil {+ r.reprovideNow()}return nil}diff --git a/internal/node/service_registry_test.go b/internal/node/service_registry_test.goindex 32e0ee39..5b60b6f2 100644--- a/internal/node/service_registry_test.go+++ b/internal/node/service_registry_test.go@@ -210,6 +210,28 @@ func TestServiceRegistry_UnreachableBackendIsRegisteredButNotAdvertised(t *testi}}+// A service registered after the reprovide loop's last cycle would otherwise+// wait a whole interval to be advertised, which is minutes.+func TestServiceRegistry_WithheldRegistrationAsksForAReprovide(t *testing.T) {+ r := newServiceRegistryForTest(&fakeDHT{})+ var asked int+ r.reprovideNow = func() { asked++ }++ if err := r.Register(context.Background(), newProbingSvc("late", errors.New("not up yet"))); err != nil {+ t.Fatalf("Register: %v", err)+ }+ if asked != 1 {+ t.Errorf("reprovide requested %d times for a withheld service, want 1", asked)+ }++ if err := r.Register(context.Background(), newProbingSvc("healthy", nil)); err != nil {+ t.Fatalf("Register: %v", err)+ }+ if asked != 1 {+ t.Errorf("reprovide requested %d times, want 1: an advertised service needs no retry", asked)+ }+}+func TestServiceRegistry_ReprovideWithholdsUnreachableBackend(t *testing.T) {dht := &fakeDHT{}r := newServiceRegistryForTest(dht)diff --git a/mobile/mobile_e2e.sh b/mobile/mobile_e2e.shindex 27c49c2e..e60d8255 100755--- a/mobile/mobile_e2e.sh+++ b/mobile/mobile_e2e.sh@@ -228,6 +228,15 @@ class S(BaseHTTPRequestHandler):HTTPServer(("0.0.0.0", 9091), S).serve_forever()'+# The node probes a backend before advertising it, so the mock has to be+# listening before the service below is registered.+for _ in $(seq 1 30); do+ curl -sf -o /dev/null -X POST -H "Content-Type: application/json" \+ -d '{"jsonrpc":"2.0","id":1,"method":"initialize"}' \+ http://127.0.0.1:9091 && break+ sleep 1+done+# Register a dummy MCP service on the host node pointing to the local mock server container (using container name)curl -s -X POST \-H "Content-Type: application/json" \diff --git a/tests/e2e/services.bats b/tests/e2e/services.batsindex 80890277..0a0b022a 100644--- a/tests/e2e/services.bats+++ b/tests/e2e/services.bats@@ -20,6 +20,7 @@ start_calc_mcp() {--network-alias calc-mcp \"${CALC_MCP_IMAGE}" >/dev/nullMESH_CONTAINERS+=("${name}")+ mesh_wait_for_log "${name}" "Uvicorn running on" 20}setup() {