diff --git a/sdk/js/src/discovery-limit.test.ts b/sdk/js/src/discovery-limit.test.ts new file mode 100644 index 000000000..06b973d83 --- /dev/null +++ b/sdk/js/src/discovery-limit.test.ts @@ -0,0 +1,31 @@ +// 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); + 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.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..aebf7fece 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; } @@ -162,7 +163,12 @@ 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); + signal?.throwIfAborted(); + 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 bad98c318..79453f40d 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 @@ -149,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.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.""" diff --git a/sdk/python/tests/test_discovery_limit.py b/sdk/python/tests/test_discovery_limit.py new file mode 100644 index 000000000..a81024c74 --- /dev/null +++ b/sdk/python/tests/test_discovery_limit.py @@ -0,0 +1,28 @@ +# 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) == [] + for limit in (-1, 0.5, 0xFFFFFFFF + 1): + with pytest.raises(ValueError, match="limit"): + await find_providers(None, [], b"", limit=limit) + + trio.run(run)