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
31 changes: 31 additions & 0 deletions sdk/js/src/discovery-limit.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
Comment on lines +19 to +31

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.

medium

Section 3: Test coverage must follow the pyramid

Consider adding a test case for limits exceeding the 32-bit unsigned integer range (e.g., 0xffffffff + 1) to fully cover the validation logic and ensure parity with the implementation.

Suggested change
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);
});
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);
});
References
  1. Any new feature or codepath MUST have the corresponding testing coverage. (link)

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.

Added in 290e63d: the test now also rejects 0xffffffff + 1 and NaN.

22 changes: 22 additions & 0 deletions sdk/js/src/discovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 10 additions & 4 deletions sdk/js/src/discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -122,18 +123,18 @@ 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;
}
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;
}
Expand Down Expand Up @@ -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<PeerRecord[]> {
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);
}
Comment on lines 165 to 173

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.

medium

General Correctness & Robustness

If limit === 0, findProviders returns [] immediately without calling request. However, if the caller passed an already aborted signal, they would expect the promise to reject with the abort reason rather than succeeding with an empty array. To ensure consistent cancellation behavior, we should check signal?.throwIfAborted() at the very beginning of the function.

Suggested change
export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise<PeerRecord[]> {
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);
}
export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise<PeerRecord[]> {
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);
}

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.

Good catch, taken in 290e63d: findProviders now calls signal?.throwIfAborted() before anything else, so an already aborted lookup rejects with the abort reason even when the limit is 0. directory rejects an already aborted provider lookup covers it. (The Python find_providers takes no signal; it is cancelled through its trio scope.)


Expand Down
12 changes: 10 additions & 2 deletions sdk/python/src/agent_mesh/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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())
Expand Down
26 changes: 26 additions & 0 deletions sdk/python/tests/test_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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."""
Expand Down
28 changes: 28 additions & 0 deletions sdk/python/tests/test_discovery_limit.py
Original file line number Diff line number Diff line change
@@ -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)
Comment on lines +21 to +28

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.

medium

Section 3: Test coverage must follow the pyramid

To ensure the Python test suite is as comprehensive as the JavaScript one, consider adding test cases for non-integer limits (like 0.5) and limits exceeding the 32-bit unsigned integer range (like 0xFFFFFFFF + 1).

Suggested change
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)
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)
with pytest.raises(ValueError, match="limit"):
await find_providers(None, [], b"", limit=0.5)
with pytest.raises(ValueError, match="limit"):
await find_providers(None, [], b"", limit=0xFFFFFFFF + 1)
trio.run(run)
References
  1. Any new feature or codepath MUST have the corresponding testing coverage. (link)

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.

Added in 290e63d: the Python test now rejects -1, 0.5 and 0xFFFFFFFF + 1, the same cases as the JavaScript test.

Loading