Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk/python: renew the relay reservation before the router drops it
Antonio Ojea7b82456484af
diff --git a/sdk/README.md b/sdk/README.mdindex 8125c136..1ae27069 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -81,6 +81,15 @@ pinned by a test:`<relay>/p2p-circuit`, and a router refuses that before the authhandshake. The JS SDK starts the listener after the handshake, through thetransport manager, which is not on the public `Libp2p` interface.+- go-libp2p's relay grants a reservation for one hour and drops it when+ that passes; a member that still advertises the relayed address is then+ unreachable (`NO_RESERVATION`). js-libp2p's listener renews on its own.+ The Python SDK renews two minutes before the expiry the router returned,+ and runs the auth handshake again first when the router has closed the+ connection in between, since the router forgets the admission with it.+ py-libp2p 0.7 cannot take this over: its relay client has the framing+ problem above, and its `RelayDiscovery` reserves again only after the+ expiry has passed, when the router has already dropped the slot.- py-libp2p's Kademlia client takes a protocol prefix but its providerlookups still speak `/ipfs/kad/1.0.0`, so it cannot reach the mesh DHT.The Python SDK does a bounded GET_PROVIDERS walk itself ondiff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.pyindex e066f3ff..a810e326 100644--- a/sdk/python/src/agent_mesh/mesh.py+++ b/sdk/python/src/agent_mesh/mesh.py@@ -243,7 +243,7 @@ class AgentMesh:def join(self, **options): # type: ignore[no-untyped-def]"""Joins the mesh: connects to the routers in the credential, passes theauth handshake with them, reserves a relay slot and keeps the credential- fresh. An async context manager to use under trio:+ and the reservation fresh. An async context manager to use under trio:async with mesh.join() as session: ..."""diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.pyindex cfd51264..b6a8037f 100644--- a/sdk/python/src/agent_mesh/session.py+++ b/sdk/python/src/agent_mesh/session.py@@ -18,7 +18,7 @@ import loggingimport randomimport timefrom contextlib import asynccontextmanager-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom datetime import datetimefrom typing import TYPE_CHECKING, Any, AsyncIterator, Mapping, Optional, Sequence, Union@@ -66,6 +66,9 @@ logger = logging.getLogger("agent_mesh")DEFAULT_REFRESH_LEAD = 60 * 60.0DEFAULT_REFRESH_RETRY = 30.0MIN_REFRESH_DELAY = 2.0+# go-libp2p's relay grants a reservation for an hour and drops it on expiry;+# its own clients renew two minutes before that.+RESERVATION_RENEW_LEAD = 2 * 60.0# sam-node's --control-plane-sync-interval default.DEFAULT_POLICY_SYNC = 15 * 60.0# How often provider records are refreshed; go-libp2p-kad-dht expires them after 48h.@@ -154,6 +157,8 @@ class MeshSession:provide_interval: float = DEFAULT_PROVIDE_INTERVALcontrol_plane_sync_interval: float = DEFAULT_CONTROL_PLANE_SYNCcontrol_plane_sync_jitter: float = DEFAULT_CONTROL_PLANE_SYNC_JITTER+ reservation_lead: float = RESERVATION_RENEW_LEAD+ reservation_retry: float = DEFAULT_REFRESH_RETRY_nursery: Optional[trio.Nursery] = field(default=None, repr=False)_policy_rules: Optional[list[str]] = field(default=None, repr=False)_serving: bool = field(default=False, repr=False)@@ -356,6 +361,31 @@ class MeshSession:if self.control_plane_sync_interval > 0:delay = self.control_plane_sync_interval * random.uniform(1.0, 1.1) # noqa: S311+ async def _reservation_loop(self) -> None:+ """Renews the relay reservation on each admitted router before the+ relay lets it expire. A member whose reservation lapsed still+ advertises the relayed address, and every dial to it fails with+ NO_RESERVATION. A router that dropped the connection forgets the+ admission with it, so that one is dialed and authenticated again+ before the reservation is asked for."""+ while True:+ reserved = [r for r in self.routers if r.reservation is not None]+ if not reserved:+ return+ due = min(r.reservation.expire for r in reserved) - self.reservation_lead - time.time() # type: ignore[union-attr]+ await trio.sleep(max(MIN_REFRESH_DELAY, due))+ failed = False+ for i, r in enumerate(self.routers):+ if r.reservation is None or r.reservation.expire - time.time() > self.reservation_lead + MIN_REFRESH_DELAY:+ continue+ try:+ self.routers[i] = await _reserve_again(self.host, self.mesh, r)+ except Exception as err: # noqa: BLE001 - retried; the relay keeps the old reservation until it expires+ failed = True+ logger.warning("relay reservation on router %s not renewed, retrying in %.0fs: %s", r.peer_id, self.reservation_retry, err)+ if failed:+ await trio.sleep(self.reservation_retry)+async def _events_loop(self, pubsub: Pubsub) -> None:"""The control plane's gossip events, relayed by the routers. The topicvalidator drops anything not signed by a trusted control plane key, so@@ -495,6 +525,7 @@ async def join_mesh(reserve: bool = True,refresh_lead: float = DEFAULT_REFRESH_LEAD,refresh_retry: float = DEFAULT_REFRESH_RETRY,+ reservation_lead: float = RESERVATION_RENEW_LEAD,policy_sync_interval: float = DEFAULT_POLICY_SYNC,provide_interval: float = DEFAULT_PROVIDE_INTERVAL,control_plane_sync_interval: float = DEFAULT_CONTROL_PLANE_SYNC,@@ -540,10 +571,13 @@ async def join_mesh(provide_interval=provide_interval,control_plane_sync_interval=control_plane_sync_interval,control_plane_sync_jitter=control_plane_sync_jitter,+ reservation_lead=reservation_lead,+ reservation_retry=refresh_retry,_nursery=nursery,)nursery.start_soon(session._events_loop, pubsub) # noqa: SLF001nursery.start_soon(session._sync_loop) # noqa: SLF001+ nursery.start_soon(session._reservation_loop) # noqa: SLF001try:yield sessionfinally:@@ -562,10 +596,7 @@ async def _admit(host: IHost, mesh: "AgentMesh", router_addrs: list[multiaddr.Mutry:info = await peer_info(addr)await dial(host, info)- credential = await authenticate_with_peer(host, info.peer_id, mesh.auth_frame(), mesh.credential.control_plane_keys)- # Enforced under the key that verified the token; a relay that- # is not a router must not become our way onto the mesh.- require_role(credential, ROLE_ROUTER)+ credential = await _authenticate_router(host, mesh, info.peer_id)reservation = await reserve_relay(host, info.peer_id) if reserve else Noneadmitted.append(AdmittedRouter(peer_id=str(info.peer_id), addr=addr, credential=credential, reservation=reservation))if reserve:@@ -575,3 +606,21 @@ async def _admit(host: IHost, mesh: "AgentMesh", router_addrs: list[multiaddr.Muif not admitted:raise RuntimeError("no router admitted this member:\n " + "\n ".join(failures))return admitted+++async def _authenticate_router(host: IHost, mesh: "AgentMesh", peer_id: ID) -> VerifiedBiscuit:+ credential = await authenticate_with_peer(host, peer_id, mesh.auth_frame(), mesh.credential.control_plane_keys)+ # Enforced under the key that verified the token; a relay that+ # is not a router must not become our way onto the mesh.+ require_role(credential, ROLE_ROUTER)+ return credential+++async def _reserve_again(host: IHost, mesh: "AgentMesh", router: AdmittedRouter) -> AdmittedRouter:+ peer_id = ID.from_base58(router.peer_id)+ credential = router.credential+ if peer_id not in host.get_connected_peers():+ await dial(host, await peer_info(router.addr))+ credential = await _authenticate_router(host, mesh, peer_id)+ reservation = await reserve_relay(host, peer_id)+ return replace(router, credential=credential, reservation=reservation)diff --git a/sdk/python/tests/test_session.py b/sdk/python/tests/test_session.pyindex a334164c..aaae8749 100644--- a/sdk/python/tests/test_session.py+++ b/sdk/python/tests/test_session.py@@ -97,17 +97,19 @@ def libp2p_host(identity: Identity):)-def hop_handler(relay_addr: str, grants: bool):+def hop_handler(relay_addr: str, grants: bool, ttl: int = 3600, events=None):"""Answers RESERVE like a go-libp2p relay whose ACL either admits or refuses us."""async def handle(stream):req = circuit.HopMessage.FromString(await read_varint_prefixed_bytes(stream))assert req.type == circuit.HopMessage.RESERVE+ if events is not None:+ events.append(("reserve", str(stream.muxed_conn.peer_id)))if grants:resp = circuit.HopMessage(type=circuit.HopMessage.STATUS,status=circuit.OK,- reservation=circuit.Reservation(expire=int(time.time()) + 3600, addrs=[multiaddr.Multiaddr(relay_addr).to_bytes()]),+ reservation=circuit.Reservation(expire=int(time.time()) + ttl, addrs=[multiaddr.Multiaddr(relay_addr).to_bytes()]),)else:resp = circuit.HopMessage(type=circuit.HopMessage.STATUS, status=circuit.PERMISSION_DENIED)@@ -117,18 +119,24 @@ def hop_handler(relay_addr: str, grants: bool):return handle-async def start_router(nursery, role=ROLE_ROUTER, trusted=(CP_KEY,), grants=True):+async def start_router(nursery, role=ROLE_ROUTER, trusted=(CP_KEY,), grants=True, ttl=3600, events=None):+ """events, when given, records ("auth", peer) per handshake and ("reserve", peer) per RESERVE."""identity = Identity.generate()router = libp2p_host(identity)router_biscuit = mint(identity.peer_id, role)- router.set_stream_handler(AUTH_PROTOCOL, auth_stream_handler(lambda: router_biscuit, lambda: list(trusted)))++ def on_authenticated(peer, _verified):+ if events is not None:+ events.append(("auth", peer))++ router.set_stream_handler(AUTH_PROTOCOL, auth_stream_handler(lambda: router_biscuit, lambda: list(trusted), on_authenticated=on_authenticated))started = trio.Event()addr_box = []async def run():async with router.run(listen_addrs=[multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")]):addr = f"{router.get_addrs()[0]}"- router.set_stream_handler(RELAY_HOP_PROTOCOL, hop_handler(addr, grants))+ router.set_stream_handler(RELAY_HOP_PROTOCOL, hop_handler(addr, grants, ttl, events))addr_box.append(addr)started.set()await trio.sleep_forever()@@ -221,3 +229,42 @@ def test_join_fails_when_the_relay_refuses_the_reservation():nursery.cancel_scope.cancel()trio.run(with_timeout, 30, main)+++def test_join_renews_the_reservation_and_reauthenticates_after_a_disconnect():+ """go-libp2p's relay drops a reservation when its TTL passes and grants one+ only to a peer authenticated on the current connection. The member renews+ ahead of the TTL; once the router has closed the connection, the renewal+ runs the handshake again first."""++ async def wait_for(predicate):+ while not predicate():+ await trio.sleep(0.1)++ async def main():+ async with trio.open_nursery() as nursery:+ events = []+ router, addr = await start_router(nursery, ttl=4, events=events)+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([addr]))+ async with mesh.join(refresh_lead=0, reservation_lead=1) as session:+ member = session.host.get_id()+ assert events == [("auth", mesh.peer_id), ("reserve", mesh.peer_id)]+ first = session.routers[0].reservation.expire++ # Renewed before the TTL, on the same admission.+ await wait_for(lambda: events.count(("reserve", mesh.peer_id)) >= 2)+ assert events.count(("auth", mesh.peer_id)) == 1+ assert session.routers[0].reservation.expire >= first+ assert session.relay_addresses == [f"{addr}/p2p-circuit/p2p/{mesh.peer_id}"]++ # The router drops the connection and with it the admission.+ await router.disconnect(member)+ await wait_for(lambda: member not in router.get_connected_peers())+ reserves = events.count(("reserve", mesh.peer_id))+ await wait_for(lambda: events.count(("reserve", mesh.peer_id)) > reserves)+ assert events.count(("auth", mesh.peer_id)) == 2+ assert events.index(("auth", mesh.peer_id), 2) < len(events) - 1+ assert member in router.get_connected_peers()+ nursery.cancel_scope.cancel()++ trio.run(with_timeout, 60, main)