From a7e9885fcd463debce4e79038df75d7820f54155 Mon Sep 17 00:00:00 2001 From: "Jaehyup (Jay) Shin" Date: Wed, 28 Oct 2026 23:28:24 -0700 Subject: [PATCH] node: keep router replacements within attachment target Signed-off-by: Jaehyup (Jay) Shin --- internal/node/router_replacement_test.go | 221 +++++++++++++++++++++++ internal/node/routers.go | 77 ++++++-- site/content/docs/concepts/networking.md | 7 +- 3 files changed, 289 insertions(+), 16 deletions(-) create mode 100644 internal/node/router_replacement_test.go diff --git a/internal/node/router_replacement_test.go b/internal/node/router_replacement_test.go new file mode 100644 index 000000000..4a36e8856 --- /dev/null +++ b/internal/node/router_replacement_test.go @@ -0,0 +1,221 @@ +// 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" + "slices" + "sync" + "testing" + "time" + + "github.com/google/agentmesh/api" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" +) + +// The replacement authenticates while the old router's redial is in flight. +// Letting that redial finish must not leave the node holding K+1 routers. +func TestRouterReplacementDuringRedial(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + old := newFakeRouter(t, "/ip4/127.0.0.1/tcp/0") + kept := newFakeRouterWithKey(t, old.cpPub, old.cpPriv, "/ip4/127.0.0.1/tcp/0") + spare := newFakeRouterWithKey(t, old.cpPub, old.cpPriv, "/ip4/127.0.0.1/tcp/0") + node := old.startNode(t, ctx, append(slices.Clone(old.routerAddrs), kept.routerAddrs...), func(o *Options) { + o.Routers = 2 + o.RouterRedialDelay = time.Millisecond + o.MonitorBootstrap = time.Hour + }) + node.setRouterCatalog(candidatesFromAddrs(ctx, append(append(slices.Clone(old.routerAddrs), kept.routerAddrs...), spare.routerAddrs...))) + waitForRouterState(t, ctx, "both initial attachments", func() bool { return node.AttachedRouters() == 2 }) + + started, resume := make(chan struct{}), make(chan struct{}) + var startedOnce, resumeOnce sync.Once + defer resumeOnce.Do(func() { close(resume) }) + old.h.SetStreamHandler(api.AuthProtocolID, func(s network.Stream) { + startedOnce.Do(func() { close(started) }) + select { + case <-resume: + old.admit(s) + case <-ctx.Done(): + _ = s.Reset() + } + }) + dropFromRouter(t, old.h, node) + select { + case <-started: + case <-ctx.Done(): + t.Fatal("old router's redial never reached its handshake") + } + if got := node.topUpRouters(ctx); got != 2 { + t.Fatalf("top-up holds %d routers, want 2", got) + } + if node.isAttached(old.h.ID()) { + t.Error("replaced router is still held while its redial is pending") + } + resumeOnce.Do(func() { close(resume) }) + waitForRouterState(t, ctx, "old router's redial to finish", func() bool { + node.mu.Lock() + defer node.mu.Unlock() + return !node.redialing[old.h.ID()] + }) + got := node.attachedRouters() + if len(got) != 2 || !slices.Contains(got, kept.h.ID()) || !slices.Contains(got, spare.h.ID()) { + t.Errorf("routers after redial = %v, want kept %s and spare %s", got, kept.h.ID(), spare.h.ID()) + } + if node.connMgr.IsProtected(old.h.ID(), routerTag) { + t.Error("replaced router is still protected by the attachment tag") + } + node.mu.Lock() + relays := slices.Clone(node.currentRelays) + node.mu.Unlock() + if len(relays) != 2 { + t.Errorf("AutoRelay candidates = %v, want the two remaining attachments", relays) + } + for _, relay := range relays { + if relay.ID == old.h.ID() { + t.Error("replaced router is still offered to AutoRelay") + } + } +} + +// A delayed top-up and concurrent top-ups can finish after another path has +// already filled the target. Admission must check the live count atomically. +func TestFinishDialAndAttachKeepsRouterLimit(t *testing.T) { + for _, lost := range []bool{false, true} { + name := "already full" + if lost { + name = "concurrent replacements" + } + t.Run(name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + kept := newFakeRouter(t, "/ip4/127.0.0.1/tcp/0") + one := newFakeRouterWithKey(t, kept.cpPub, kept.cpPriv, "/ip4/127.0.0.1/tcp/0") + two := newFakeRouterWithKey(t, kept.cpPub, kept.cpPriv, "/ip4/127.0.0.1/tcp/0") + node := kept.startNode(t, ctx, kept.routerAddrs, func(o *Options) { + o.Routers = 1 + o.RouterRedialDelay = -1 + o.MonitorBootstrap = time.Hour + }) + node.setRouterCatalog(candidatesFromAddrs(ctx, append(append(slices.Clone(kept.routerAddrs), one.routerAddrs...), two.routerAddrs...))) + if lost { + dropFromRouter(t, kept.h, node) + waitForRouterState(t, ctx, "old session to clear", func() bool { + node.mu.Lock() + defer node.mu.Unlock() + return !node.authenticatedRouters[kept.h.ID()] + }) + } + identity, err := node.loadIdentityForAuth() + if err != nil { + t.Fatal(err) + } + for _, router := range []*fakeRouter{one, two} { + if err := node.authRouter(ctx, peer.AddrInfo{ID: router.h.ID(), Addrs: router.h.Addrs()}, identity); err != nil { + t.Fatal(err) + } + } + node.mu.Lock() + if node.dialing == nil { + node.dialing = make(map[peer.ID]bool) + } + node.dialing[one.h.ID()] = true + node.dialing[two.h.ID()] = true + node.mu.Unlock() + + ready := make(chan struct{}) + var attaching sync.WaitGroup + for _, id := range []peer.ID{one.h.ID(), two.h.ID()} { + attaching.Go(func() { + <-ready + node.finishDialAndAttach(id) + }) + } + close(ready) + attaching.Wait() + got := node.attachedRouters() + if len(got) != 1 { + t.Fatalf("routers = %v, want exactly one", got) + } + if !lost && got[0] != kept.h.ID() { + t.Errorf("router = %s, want existing live router %s", got[0], kept.h.ID()) + } + if lost && got[0] == kept.h.ID() { + t.Errorf("router = %s, want one of the replacements", got[0]) + } + node.mu.Lock() + pending := len(node.dialing) + node.mu.Unlock() + if pending != 0 { + t.Errorf("pending router dials = %d, want 0", pending) + } + for _, id := range []peer.ID{kept.h.ID(), one.h.ID(), two.h.ID()} { + want := id == got[0] + if node.isAttached(id) != want || node.connMgr.IsProtected(id, routerTag) != want { + t.Errorf("router %s attachment/protection must be %v", id, want) + } + } + }) + } +} + +func TestFinishDialAndAttachRetainsRedialUntilTargetIsFull(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + old := newFakeRouter(t, "/ip4/127.0.0.1/tcp/0") + one := newFakeRouterWithKey(t, old.cpPub, old.cpPriv, "/ip4/127.0.0.1/tcp/0") + two := newFakeRouterWithKey(t, old.cpPub, old.cpPriv, "/ip4/127.0.0.1/tcp/0") + node := old.startNode(t, ctx, old.routerAddrs, func(o *Options) { + o.Routers = 2 + o.RouterRedialDelay = -1 + o.MonitorBootstrap = time.Hour + }) + all := append(append(slices.Clone(old.routerAddrs), one.routerAddrs...), two.routerAddrs...) + node.setRouterCatalog(candidatesFromAddrs(ctx, all)) + dropFromRouter(t, old.h, node) + waitForRouterState(t, ctx, "old router's session to clear", func() bool { + node.mu.Lock() + defer node.mu.Unlock() + return !node.authenticatedRouters[old.h.ID()] + }) + identity, err := node.loadIdentityForAuth() + if err != nil { + t.Fatal(err) + } + for i, router := range []*fakeRouter{one, two} { + if err := node.authRouter(ctx, peer.AddrInfo{ID: router.h.ID(), Addrs: router.h.Addrs()}, identity); err != nil { + t.Fatal(err) + } + node.finishDialAndAttach(router.h.ID()) + if got := node.isAttached(old.h.ID()); got != (i == 0) { + t.Errorf("old router held = %v after replacement %d, want %v", got, i+1, i == 0) + } + } +} + +func waitForRouterState(t *testing.T, ctx context.Context, description string, ready func() bool) { + t.Helper() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for !ready() { + select { + case <-ctx.Done(): + t.Fatalf("waiting for %s: %v", description, ctx.Err()) + case <-tick.C: + } + } +} diff --git a/internal/node/routers.go b/internal/node/routers.go index fe2bd74f4..7e087f09f 100644 --- a/internal/node/routers.go +++ b/internal/node/routers.go @@ -199,6 +199,11 @@ func (n *AgentMeshNode) refreshRouterCatalog(ctx context.Context) error { func (n *AgentMeshNode) wantRouters() int { n.mu.Lock() defer n.mu.Unlock() + return n.wantRoutersLocked() +} + +// wantRoutersLocked requires n.mu. +func (n *AgentMeshNode) wantRoutersLocked() int { matched := 0 for _, c := range n.routerCatalog { if len(n.config.RouterSelector) == 0 || api.LabelsSatisfy(n.config.RouterSelector, c.Labels) { @@ -208,6 +213,12 @@ func (n *AgentMeshNode) wantRouters() int { return min(n.config.Routers, matched) } +// routerLiveLocked reports whether an authenticated router still has a connection. +// The caller holds n.mu. +func (n *AgentMeshNode) routerLiveLocked(router peer.ID) bool { + return n.authenticatedRouters[router] && (n.Host == nil || n.Host.Network().Connectedness(router) == network.Connected) +} + // attachedRouters lists the routers the node keeps and holds a live // authenticated session with. func (n *AgentMeshNode) attachedRouters() []peer.ID { @@ -215,7 +226,7 @@ func (n *AgentMeshNode) attachedRouters() []peer.ID { defer n.mu.Unlock() var out []peer.ID for pid := range n.attached { - if n.authenticatedRouters[pid] && n.Host.Network().Connectedness(pid) == network.Connected { + if n.routerLiveLocked(pid) { out = append(out, pid) } } @@ -240,10 +251,10 @@ func (n *AgentMeshNode) RefreshRouters(ctx context.Context) error { return n.ref func (n *AgentMeshNode) detach(router peer.ID) { n.mu.Lock() delete(n.attached, router) - n.mu.Unlock() if n.connMgr != nil { n.connMgr.Unprotect(router, routerTag) } + n.mu.Unlock() n.refreshRelays() } @@ -307,17 +318,11 @@ func (n *AgentMeshNode) selectAndWarnRouters(cands []routerCandidate, k int, exc // admitByRouters) never overshoot Options.Routers or dial the same router twice. func (n *AgentMeshNode) reserveRoutersToAttach() []peer.AddrInfo { n.mu.Lock() - matched := 0 - for _, c := range n.routerCatalog { - if len(n.config.RouterSelector) == 0 || api.LabelsSatisfy(n.config.RouterSelector, c.Labels) { - matched++ - } - } - want := min(n.config.Routers, matched) + want := n.wantRoutersLocked() inUse := 0 counted := make(map[peer.ID]bool, len(n.attached)+len(n.dialing)) for pid := range n.attached { - if n.authenticatedRouters[pid] && (n.Host == nil || n.Host.Network().Connectedness(pid) == network.Connected) { + if n.routerLiveLocked(pid) { counted[pid] = true inUse++ } @@ -360,16 +365,58 @@ func (n *AgentMeshNode) shun(router peer.ID, d time.Duration) { func (n *AgentMeshNode) finishDialAndAttach(router peer.ID) { n.mu.Lock() + delete(n.dialing, router) + want := n.wantRoutersLocked() + live := 0 + var dropped []peer.ID + for pid := range n.attached { + if n.routerLiveLocked(pid) { + live++ + } else { + dropped = append(dropped, pid) + } + } + // A redial or another top-up may have filled the target while this + // handshake was in flight. Check and record the attachment under one lock. + if !n.attached[router] && live >= want { + n.mu.Unlock() + logger.Infof("[AuthN] Not attaching admitted router %s: holding %d live routers, target %d", router, live, want) + return + } if n.attached == nil { n.attached = map[peer.ID]bool{} } + if !n.attached[router] && n.routerLiveLocked(router) { + live++ + } n.attached[router] = true - delete(n.dialing, router) - n.mu.Unlock() + // Protection changes share the attachment lock, so a concurrent detach + // cannot leave a router protected after its attachment has been removed. if n.connMgr != nil { n.connMgr.Protect(router, routerTag) } + if live >= want { + // Keep trying a dropped router while still short. Once replacements + // fill the target, retire it even if its redial is already in flight: + // redial never attaches on success, so it cannot restore a K+1th hold. + // Use the same snapshot as the count: a live router that drops + // during this decision must keep its own redial intent. + for _, pid := range dropped { + delete(n.attached, pid) + if n.connMgr != nil { + n.connMgr.Unprotect(pid, routerTag) + } + } + } else { + dropped = nil + } + n.mu.Unlock() + for _, pid := range dropped { + logger.Infof("[AuthN] Releasing dropped router %s: %d live routers fill the target %d", pid, live, want) + } n.refreshRelays() + // A router to announce to: services registered before this one was + // held, as the egress assignments are at start, go to the directory now. n.triggerReprovide() } @@ -382,9 +429,9 @@ func (n *AgentMeshNode) clearDialing(routers []peer.AddrInfo) { } // dialAndAttach runs authRouter against each router at once and attaches -// the ones that admit the node, delivering one outcome per router on the -// returned channel in completion order. A caller may stop reading early: -// the dials still in flight attach on their own as they land. +// the ones that admit the node while there is room, delivering one outcome +// per router on the returned channel in completion order. A caller may stop +// reading early: the dials still in flight finish on their own. func (n *AgentMeshNode) dialAndAttach(ctx context.Context, routers []peer.AddrInfo, biscuitBytes []byte) <-chan error { n.mu.Lock() if n.dialing == nil && len(routers) > 0 { diff --git a/site/content/docs/concepts/networking.md b/site/content/docs/concepts/networking.md index c317ea280..42c38c9c3 100644 --- a/site/content/docs/concepts/networking.md +++ b/site/content/docs/concepts/networking.md @@ -97,7 +97,12 @@ out what each connection carries and what a NAT or firewall sees. Routers are the fixed points. A node learns their addresses, labels and load from the control plane's `/info` at enrollment and again on a schedule, holds two of them with a relay reservation on each, and replaces -one that drops or that sends it away. A router that holds a member answers +one that drops or that sends it away. While short of its target, the node +redials dropped routers. Once replacements fill the target, it stops holding +the disconnected routers; a late redial or top-up cannot add an extra +attachment. Existing live attachments are kept. This limits held routers, +not every router connection: a call can still need a transit router. +A router that holds a member answers a lookup for it from what it sees of the member; any other router answers from the record the member announced under its own peer ID, so a lookup for the member learns where it is reached through any router. An SDK