Skip to content

Agent Mesh

close latent leak in redeclare path

Ibrahim12d0b2487bab
diff --git a/internal/node/service_registry.go b/internal/node/service_registry.go
index 04ea0a27..04b0077d 100644
--- a/internal/node/service_registry.go
+++ b/internal/node/service_registry.go
@@ -106,6 +106,8 @@ func NewServiceRegistry(d dhtProvider, backendProbeTimeout time.Duration) *Servi
// A backend that does not answer is registered but not advertised, rather than
// rejected: backends routinely start after the node does, and the reprovide
// loop picks them up once they answer.
+//
+// registering a name again replaces the instance and tears the old one down
func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {
info := svc.Info()
if info.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {
@@ -164,9 +166,16 @@ func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {
}
r.mu.Lock()
+ replaced := r.services[info.Name]
r.services[info.Name] = svc
r.mu.Unlock()
+ if replaced != nil && replaced != svc {
+ if err := replaced.Teardown(); err != nil {
+ logger.Errorf("[ServiceRegistry] Teardown replaced %s: %v", info.Name, err)
+ }
+ }
+
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 {
diff --git a/internal/node/service_registry_test.go b/internal/node/service_registry_test.go
index f2a6a8ee..020de989 100644
--- a/internal/node/service_registry_test.go
+++ b/internal/node/service_registry_test.go
@@ -395,3 +395,31 @@ func TestServiceRegistry_BackendProbeTimeoutIsConfigurable(t *testing.T) {
}
})
}
+
+// registering the name again replaces the entry, so the displaced instance is
+// only reachable if this call tears it down
+func TestServiceRegistry_ReplacingServiceTearsDownPrevious(t *testing.T) {
+ r := newServiceRegistryForTest(&fakeDHT{})
+ ctx := context.Background()
+
+ first := newFakeSvc("demo", api.ServiceType_SERVICE_TYPE_MCP)
+ if err := r.Register(ctx, first); err != nil {
+ t.Fatalf("first Register: %v", err)
+ }
+
+ second := newFakeSvc("demo", api.ServiceType_SERVICE_TYPE_MCP)
+ if err := r.Register(ctx, second); err != nil {
+ t.Fatalf("second Register: %v", err)
+ }
+
+ if first.teardownCalls != 1 {
+ t.Errorf("replaced service Teardown called %d times, want 1: "+
+ "the replaced instance is no longer reachable from the map, so nothing else can ever tear it down", first.teardownCalls)
+ }
+ if second.teardownCalls != 0 {
+ t.Errorf("replacement service Teardown called %d times, want 0", second.teardownCalls)
+ }
+ if got, ok := r.Get("demo"); !ok || got != Service(second) {
+ t.Error("registry should hold the replacement instance")
+ }
+}