From 0915b82dbd9a25d50f407d4b197acded67aa21bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Wed, 25 Nov 2026 01:24:55 +0200 Subject: [PATCH 1/4] sdk/js: propagate cancellation from directory requests --- sdk/js/src/discovery.test.ts | 22 ++++++++++++++++++++++ sdk/js/src/discovery.ts | 7 ++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/sdk/js/src/discovery.test.ts b/sdk/js/src/discovery.test.ts index 10bd289d9..0f418563f 100644 --- a/sdk/js/src/discovery.test.ts +++ b/sdk/js/src/discovery.test.ts @@ -68,6 +68,28 @@ function held(router: Libp2p) { const found = () => create(DirectoryResponseSchema, { providers: [create(PeerRecordSchema, { peerId: PROVIDER, addrs: [`/ip4/10.0.0.9/tcp/4001/p2p/${PROVIDER}`] })] }); const nothing = () => create(DirectoryResponseSchema, {}); +test("directory cancellation wins over an earlier empty answer", async () => { + const key = await serviceKey("mcp", "calculator"); + const find = create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit: 20 } } }); + const controller = new AbortController(); + const reason = new Error("caller stopped looking"); + const absent = { + peerId: "gone", + connection() { + controller.abort(reason); + return undefined; + }, + }; + answers.set("a", nothing); + try { + assert.equal((await request([held(routerA)], find)).providers.length, 0); + await assert.rejects(request([held(routerA), absent], find, controller.signal), reason); + await assert.rejects(request([], find, controller.signal), reason); + } finally { + answers.delete("a"); + } +}); + test("a lookup one router answers with nothing is put to the next; an announcement is not", async () => { // A router cut off from the routers closest to the key answers from what // it can reach; the member holds another that may not be. diff --git a/sdk/js/src/discovery.ts b/sdk/js/src/discovery.ts index 37dbf94a7..0651861e2 100644 --- a/sdk/js/src/discovery.ts +++ b/sdk/js/src/discovery.ts @@ -114,6 +114,7 @@ export async function request(routers: DirectoryRouter[], req: DirectoryRequest, let asked = 0; let empty: DirectoryResponse | undefined; for (const router of routers) { + signal?.throwIfAborted(); const conn = router.connection(); if (conn === undefined) { continue; @@ -122,6 +123,7 @@ export async function request(routers: DirectoryRouter[], req: DirectoryRequest, const bounded = signal === undefined ? AbortSignal.timeout(REQUEST_TIMEOUT_MS) : AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]); try { const resp = await ask(conn, req, bounded); + signal?.throwIfAborted(); if (lookup && resp.providers.length === 0 && resp.peer === undefined) { empty = resp; continue; @@ -129,11 +131,10 @@ export async function request(routers: DirectoryRouter[], req: DirectoryRequest, return resp; } catch (err) { failures.push(`${router.peerId}: ${err instanceof Error ? err.message : String(err)}`); - if (signal?.aborted === true) { - break; - } + signal?.throwIfAborted(); } } + signal?.throwIfAborted(); if (empty !== undefined) { return empty; } From 20ed380e765330ffa214762d3c11d28fc2fd004f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Wed, 25 Nov 2026 01:25:37 +0200 Subject: [PATCH 2/4] sdk/python: close directory streams when callers cancel --- sdk/python/src/agent_mesh/discovery.py | 6 +++++- sdk/python/tests/test_discovery.py | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/sdk/python/src/agent_mesh/discovery.py b/sdk/python/src/agent_mesh/discovery.py index bad98c318..048fc8c41 100644 --- a/sdk/python/src/agent_mesh/discovery.py +++ b/sdk/python/src/agent_mesh/discovery.py @@ -99,7 +99,11 @@ async def _ask(host: IHost, router: ID, req: pb.DirectoryRequest) -> pb.Director await stream.write(encode_varint_prefixed(req.SerializeToString())) resp = pb.DirectoryResponse.FromString(await read_bounded_varint_prefixed_bytes(stream, MAX_DIRECTORY_MESSAGE_BYTES)) finally: - await stream.close() + with trio.move_on_after(1, shield=True): + try: + await stream.close() + except Exception: + logger.debug("directory: failed to close stream to router %s", router, exc_info=True) if resp.error: raise DirectoryError(resp.error) return resp diff --git a/sdk/python/tests/test_discovery.py b/sdk/python/tests/test_discovery.py index 657852030..7498e3177 100644 --- a/sdk/python/tests/test_discovery.py +++ b/sdk/python/tests/test_discovery.py @@ -24,6 +24,7 @@ from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytes from agent_mesh._proto import agentmesh_pb2 as pb +from agent_mesh import discovery from agent_mesh.discovery import DIRECTORY_PROTOCOL, _REQUEST_TIMEOUT, DirectoryError, find_peer, find_providers, peer_key, provide, service_key SELF = ID.from_base58("12D3KooWJoJPhXqLrGAcVsGSzHMzWrmoHCWoTzVSSiT3JfR7RBVo") @@ -91,6 +92,31 @@ def _record(peer_id, *addrs): return pb.PeerRecord(peer_id=str(peer_id), addrs=[f"{a}/p2p/{peer_id}" for a in addrs]) +def test_directory_closes_an_opened_stream_when_cancelled(monkeypatch): + closed = [] + + async def run(): + with trio.CancelScope() as scope: + class Stream: + async def write(self, data): + scope.cancel() + await trio.lowlevel.checkpoint() + + async def close(self): + await trio.lowlevel.checkpoint() + closed.append(True) + + async def open_stream(*args): + return Stream() + + monkeypatch.setattr(discovery, "open_stream", open_stream) + await discovery.request(None, [ROUTER], pb.DirectoryRequest()) + assert scope.cancelled_caught + assert closed == [True] + + trio.run(run) + + def test_keys_are_the_sha256_multihash_of_the_name(): """The same bytes api.ServiceKey and api.PeerKey produce, so a record a Go member announced is found from Python and the other way round.""" From aaa0db12c976f3f87e3ad8295c30143fb5d9ad29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Wed, 25 Nov 2026 01:26:38 +0200 Subject: [PATCH 3/4] sdk: validate directory provider limits before querying routers --- sdk/js/src/discovery-limit.test.ts | 24 +++++++++++++++++++++ sdk/js/src/discovery.ts | 6 +++++- sdk/python/src/agent_mesh/discovery.py | 6 +++++- sdk/python/tests/test_discovery_limit.py | 27 ++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 sdk/js/src/discovery-limit.test.ts create mode 100644 sdk/python/tests/test_discovery_limit.py diff --git a/sdk/js/src/discovery-limit.test.ts b/sdk/js/src/discovery-limit.test.ts new file mode 100644 index 000000000..dcc9a9892 --- /dev/null +++ b/sdk/js/src/discovery-limit.test.ts @@ -0,0 +1,24 @@ +// 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. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { findProviders } from "./discovery.ts"; + +test("directory validates the provider limit before contacting routers", async () => { + const key = new Uint8Array(); + assert.deepEqual(await findProviders([], key, 0), []); + await assert.rejects(findProviders([], key, -1), RangeError); + await assert.rejects(findProviders([], key, 0.5), RangeError); +}); diff --git a/sdk/js/src/discovery.ts b/sdk/js/src/discovery.ts index 0651861e2..b2ceff7c9 100644 --- a/sdk/js/src/discovery.ts +++ b/sdk/js/src/discovery.ts @@ -163,7 +163,11 @@ export async function withdraw(routers: DirectoryRouter[], key: Uint8Array, sign /** Who provides key, up to limit, with their addresses; empty when nobody does. */ export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise { - const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit: Math.max(limit, 1) } } }), signal); + if (!Number.isInteger(limit) || limit < 0 || limit > 0xffffffff) { + throw new RangeError("directory provider limit must be an unsigned 32-bit integer"); + } + if (limit === 0) return []; + const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit } } }), signal); return resp.providers.slice(0, limit); } diff --git a/sdk/python/src/agent_mesh/discovery.py b/sdk/python/src/agent_mesh/discovery.py index 048fc8c41..79453f40d 100644 --- a/sdk/python/src/agent_mesh/discovery.py +++ b/sdk/python/src/agent_mesh/discovery.py @@ -153,7 +153,11 @@ async def withdraw(host: IHost, routers: Iterable[ID], key: bytes) -> None: async def find_providers(host: IHost, routers: Iterable[ID], key: bytes, limit: int = DEFAULT_LIMIT) -> list[DiscoveredProvider]: """Who provides key, up to limit, with their addresses; empty when nobody does.""" - req = pb.DirectoryRequest(find_providers=pb.DirectoryFindProviders(key=key, limit=max(limit, 1))) + if not isinstance(limit, int) or not 0 <= limit <= 0xFFFFFFFF: + raise ValueError("directory provider limit must be an unsigned 32-bit integer") + if limit == 0: + return [] + req = pb.DirectoryRequest(find_providers=pb.DirectoryFindProviders(key=key, limit=limit)) resp = await request(host, routers, req) found: dict[str, DiscoveredProvider] = {} self_id = str(host.get_id()) diff --git a/sdk/python/tests/test_discovery_limit.py b/sdk/python/tests/test_discovery_limit.py new file mode 100644 index 000000000..e692b4207 --- /dev/null +++ b/sdk/python/tests/test_discovery_limit.py @@ -0,0 +1,27 @@ +# 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. + +import pytest +import trio + +from agent_mesh.discovery import find_providers + + +def test_directory_checks_provider_limit_before_contacting_routers(): + async def run(): + assert await find_providers(None, [], b"", limit=0) == [] + with pytest.raises(ValueError, match="limit"): + await find_providers(None, [], b"", limit=-1) + + trio.run(run) From 290e63d226ffbca47ceeb4bd78db1d05150f29de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Wed, 25 Nov 2026 15:47:27 +0200 Subject: [PATCH 4/4] sdk: reject an aborted provider lookup even when it asks for nothing findProviders in the JavaScript SDK answered a zero limit with an empty list before it looked at the signal, so a caller that had already given up saw success. Check the signal first. The limit tests in both SDKs now also cover values past the unsigned 32-bit range, non-integers and NaN. --- sdk/js/src/discovery-limit.test.ts | 7 +++++++ sdk/js/src/discovery.ts | 1 + sdk/python/tests/test_discovery_limit.py | 5 +++-- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/sdk/js/src/discovery-limit.test.ts b/sdk/js/src/discovery-limit.test.ts index dcc9a9892..06b973d83 100644 --- a/sdk/js/src/discovery-limit.test.ts +++ b/sdk/js/src/discovery-limit.test.ts @@ -21,4 +21,11 @@ test("directory validates the provider limit before contacting routers", async ( assert.deepEqual(await findProviders([], key, 0), []); await assert.rejects(findProviders([], key, -1), RangeError); await assert.rejects(findProviders([], key, 0.5), RangeError); + await assert.rejects(findProviders([], key, 0xffffffff + 1), RangeError); + await assert.rejects(findProviders([], key, Number.NaN), RangeError); +}); + +test("directory rejects an already aborted provider lookup", async () => { + const reason = new Error("caller gave up"); + await assert.rejects(findProviders([], new Uint8Array(), 0, AbortSignal.abort(reason)), reason); }); diff --git a/sdk/js/src/discovery.ts b/sdk/js/src/discovery.ts index b2ceff7c9..aebf7fece 100644 --- a/sdk/js/src/discovery.ts +++ b/sdk/js/src/discovery.ts @@ -163,6 +163,7 @@ export async function withdraw(routers: DirectoryRouter[], key: Uint8Array, sign /** Who provides key, up to limit, with their addresses; empty when nobody does. */ export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise { + signal?.throwIfAborted(); if (!Number.isInteger(limit) || limit < 0 || limit > 0xffffffff) { throw new RangeError("directory provider limit must be an unsigned 32-bit integer"); } diff --git a/sdk/python/tests/test_discovery_limit.py b/sdk/python/tests/test_discovery_limit.py index e692b4207..a81024c74 100644 --- a/sdk/python/tests/test_discovery_limit.py +++ b/sdk/python/tests/test_discovery_limit.py @@ -21,7 +21,8 @@ def test_directory_checks_provider_limit_before_contacting_routers(): async def run(): assert await find_providers(None, [], b"", limit=0) == [] - with pytest.raises(ValueError, match="limit"): - await find_providers(None, [], b"", limit=-1) + for limit in (-1, 0.5, 0xFFFFFFFF + 1): + with pytest.raises(ValueError, match="limit"): + await find_providers(None, [], b"", limit=limit) trio.run(run)