Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 221 additions & 0 deletions internal/node/router_replacement_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
Comment on lines +141 to +147

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The standard library sync.WaitGroup does not have a Go method. This will cause a compilation error. Use attaching.Add(1), defer attaching.Done(), and a standard go statement instead.

Suggested change
var attaching sync.WaitGroup
for _, id := range []peer.ID{one.h.ID(), two.h.ID()} {
attaching.Go(func() {
<-ready
node.attach(id)
})
}
var attaching sync.WaitGroup
for _, id := range []peer.ID{one.h.ID(), two.h.ID()} {
attaching.Add(1)
go func(id peer.ID) {
defer attaching.Done()
<-ready
node.attach(id)
}(id)
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sync.WaitGroup.Go was added in Go 1.25: https://pkg.go.dev/sync#WaitGroup.Go. This repository requires Go 1.26.6 in go.mod, so this method is available on its supported toolchain. I also reran all three router-replacement regression tests under -race with Go 1.27.3; they compile and pass. Keeping the standard-library helper here.

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:
}
}
}
77 changes: 62 additions & 15 deletions internal/node/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -208,14 +213,20 @@ 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 {
n.mu.Lock()
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)
}
}
Expand All @@ -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()
}

Expand Down Expand Up @@ -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++
}
Expand Down Expand Up @@ -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()
}

Expand All @@ -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 {
Expand Down
7 changes: 6 additions & 1 deletion site/content/docs/concepts/networking.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading