From f73a529cbfc7146add5db1c6a4089753798b693c Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Wed, 24 Jun 2026 15:32:01 -0400 Subject: [PATCH 01/10] [RSDK-14160] Implement arm streaming apis --- src/viam/components/arm/arm.py | 180 ++++++++++++++++++++++++++++- src/viam/components/arm/client.py | 74 +++++++++++- src/viam/components/arm/service.py | 58 ++++++++++ 3 files changed, 310 insertions(+), 2 deletions(-) diff --git a/src/viam/components/arm/arm.py b/src/viam/components/arm/arm.py index b3f65595f7..1badd7880c 100644 --- a/src/viam/components/arm/arm.py +++ b/src/viam/components/arm/arm.py @@ -1,9 +1,20 @@ import abc -from typing import Any, Dict, Final, Optional +from dataclasses import dataclass +from datetime import timedelta +from typing import Any, AsyncIterator, Dict, Final, List, Optional + +from google.protobuf.duration_pb2 import Duration from viam.components import KinematicsReturn from viam.components.component_base import ComponentBase +from viam.proto.component.arm import ( + JointAccelerations, + JointVelocities, + MoveThroughJointPositionsStreamedResponse, + TrajectoryPoint as TrajectoryPointPb, +) from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT +from viam.utils import dict_to_struct, struct_to_dict from . import JointPositions, Pose @@ -29,6 +40,99 @@ class Arm(ComponentBase): API: Final = API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm") # pyright: ignore [reportIncompatibleVariableOverride] + @dataclass + class KinematicConstraints: + """ + Optional per-waypoint kinematic constraints attached to a ``TrajectoryPoint``. + + Joint velocities are required; joint accelerations are optional. The presence + of velocities is what unlocks the option to pass accelerations -- accelerations + cannot be specified without velocities. Each list is ordered spatially from the + base toward the end effector of the arm and must match the arm's DOF. + """ + + velocities: List[float] + """Target joint velocities at this waypoint. Rotational values in degrees per second, + translational values in mm per second.""" + + accelerations: Optional[List[float]] = None + """Optional target joint accelerations at this waypoint. Rotational values in + degrees per second squared, translational values in mm per second squared.""" + + @dataclass + class TrajectoryPoint: + """ + A single waypoint of a kinematized trajectory consumed by + ``move_through_joint_positions_streamed``. + + Times across a streamed trajectory must be strictly monotonically increasing. + The first point in a stream must have ``time`` equal to zero. + """ + + time: timedelta + """Time at which this waypoint should be reached, measured from the start of the motion.""" + + positions: List[float] + """Joint positions at this waypoint. Rotational values in degrees, translational values in mm.""" + + constraints: Optional["Arm.KinematicConstraints"] = None + """Optional kinematic constraints at this waypoint.""" + + def to_proto(self) -> TrajectoryPointPb: + duration = Duration() + duration.FromTimedelta(self.time) + constraints_pb = None + if self.constraints is not None: + accelerations_pb = None + if self.constraints.accelerations is not None: + accelerations_pb = JointAccelerations(values=self.constraints.accelerations) + constraints_pb = TrajectoryPointPb.KinematicConstraints( + velocities=JointVelocities(values=self.constraints.velocities), + accelerations=accelerations_pb, + ) + return TrajectoryPointPb( + time=duration, + positions=JointPositions(values=self.positions), + constraints=constraints_pb, + ) + + @classmethod + def from_proto(cls, proto: TrajectoryPointPb) -> "Arm.TrajectoryPoint": + constraints = None + if proto.HasField("constraints"): + accelerations = None + if proto.constraints.HasField("accelerations"): + accelerations = list(proto.constraints.accelerations.values) + constraints = Arm.KinematicConstraints( + velocities=list(proto.constraints.velocities.values), + accelerations=accelerations, + ) + return cls( + time=proto.time.ToTimedelta(), + positions=list(proto.positions.values), + constraints=constraints, + ) + + @dataclass + class Response: + """ + Per-message response from ``move_through_joint_positions_streamed``. + + For the proof-of-concept the response payload is empty; the type exists so that + callers can iterate the response stream today and pick up future per-batch + status fields without an API reshape. + """ + + extra: Optional[Dict[str, Any]] = None + """Arm-side reply data.""" + + def to_proto(self) -> MoveThroughJointPositionsStreamedResponse: + return MoveThroughJointPositionsStreamedResponse(extra=dict_to_struct(self.extra)) + + @classmethod + def from_proto(cls, proto: MoveThroughJointPositionsStreamedResponse) -> "Arm.Response": + return cls(extra=struct_to_dict(proto.extra) if proto.HasField("extra") else None) + @abc.abstractmethod async def get_end_position( self, @@ -122,6 +226,80 @@ async def move_to_joint_positions( """ ... + @abc.abstractmethod + async def move_through_joint_positions( + self, + positions: List[JointPositions], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ): + """ + Move each joint on the arm to through the corresponding angles specified in each entry of ``positions``. + + :: + + my_arm = Arm.from_robot(robot=machine, name="my_arm") + + # Declare a list of values with your desired rotational value for each joint on + # the arm. This example is for a 5dof arm. + degrees1 = [0.0, 45.0, 0.0, 0.0, 0.0] + degrees2 = [0.0, 45.0, 45.0, 0.0, 0.0] + + # Declare a new JointPositions with these values. + positions = [JointPositions(values=degrees1), JointPositions(values=degrees2)] + + # Move each joint of the arm to the position these values specify. + await my_arm.move_through_joint_positions(positions=positions) + + Args: + positions (JointPositions): A list of destination ``JointPositions`` for the arm. + + For more information, see `Arm component `_. + """ + ... + + @abc.abstractmethod + async def move_through_joint_positions_streamed( + self, + points: AsyncIterator["Arm.TrajectoryPoint"], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> AsyncIterator["Arm.Response"]: + """ + Move the arm through a time-parameterized stream of joint waypoints. + + The caller supplies an asynchronous iterator of ``TrajectoryPoint`` values; the + arm executes them in order as they arrive. Per-message responses are yielded back + to the caller as they are produced by the arm. Arm-side errors raised during + execution surface as a gRPC status on the response iteration -- the + ``async for`` raises rather than returning. + + :: + + my_arm = Arm.from_robot(robot=machine, name="my_arm") + + async def points(): + yield Arm.TrajectoryPoint(time=timedelta(seconds=0.0), positions=[0.0, 0.0, 0.0, 0.0, 0.0]) + yield Arm.TrajectoryPoint(time=timedelta(seconds=1.0), positions=[10.0, 0.0, 0.0, 0.0, 0.0]) + + async for resp in my_arm.move_through_joint_positions_streamed(points()): + # Observe arm-side acknowledgements; errors raise out of this iteration. + pass + + Args: + points: an asynchronous iterator of ``TrajectoryPoint`` values. Point times + must be strictly monotonically increasing across the stream, and the first + point's time must be zero. + + Returns: + AsyncIterator[Arm.Response]: a live stream of per-message responses. + """ + ... + @abc.abstractmethod async def get_joint_positions( self, diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index 7113fa269e..844485edfa 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -1,4 +1,5 @@ -from typing import Any, Dict, List, Mapping, Optional +import asyncio +from typing import Any, AsyncIterator, Dict, List, Mapping, Optional from grpclib.client import Channel @@ -22,6 +23,8 @@ IsMovingResponse, JointPositions, MoveToJointPositionsRequest, + MoveThroughJointPositionsRequest, + MoveThroughJointPositionsStreamedRequest, MoveToPositionRequest, StopRequest, ) @@ -91,6 +94,75 @@ async def move_to_joint_positions( request = MoveToJointPositionsRequest(name=self.name, positions=positions, extra=dict_to_struct(extra)) await self.client.MoveToJointPositions(request, timeout=timeout, metadata=md) + async def move_through_joint_positions( + self, + positions: List[JointPositions], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ): + md = kwargs.get("metadata", self.Metadata()).proto + request = MoveThroughJointPositionsRequest(name=self.name, positions=positions, extra=dict_to_struct(extra)) + await self.client.MoveThroughJointPositions(request, timeout=timeout, metadata=md) + + async def move_through_joint_positions_streamed( # type: ignore + self, + points: AsyncIterator[Arm.TrajectoryPoint], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> AsyncIterator[Arm.Response]: + md = kwargs.get("metadata", self.Metadata()).proto + async with self.client.MoveThroughJointPositionsStreamed.open(timeout=timeout, metadata=md) as stream: + await stream.send_message( + MoveThroughJointPositionsStreamedRequest( + init=MoveThroughJointPositionsStreamedRequest.Init( + name=self.name, + extra=dict_to_struct(extra), + ), + ) + ) + + # Drive the caller-supplied point iterator on a background task so that send + # and receive proceed independently -- arm-side acknowledgements and errors + # may surface at any time, including while the caller is still producing points. + async def send_loop() -> None: + try: + async for point in points: + await stream.send_message( + MoveThroughJointPositionsStreamedRequest( + batch=MoveThroughJointPositionsStreamedRequest.TrajectoryBatch( + points=[point.to_proto()], + ), + ) + ) + finally: + await stream.end() + + send_task = asyncio.create_task(send_loop()) + try: + async for response in stream: + yield Arm.Response.from_proto(response) + except BaseException: + # Recv side raised (a gRPC status from the server, the generator being + # closed by the consumer, or cancellation). Tear down the send side + # and suppress whatever it produces -- the recv-side cause is what + # the caller needs to see, not a downstream send-side cleanup error. + send_task.cancel() + try: + await send_task + except BaseException: + pass + raise + else: + # Recv side completed normally. Surface any send-side failure -- + # most importantly, an exception from the caller's points iterator, + # which would otherwise be silently swallowed and defeat the whole + # point of the bidi shape. + await send_task + async def stop( self, *, diff --git a/src/viam/components/arm/service.py b/src/viam/components/arm/service.py index f7bba88dde..9130147491 100644 --- a/src/viam/components/arm/service.py +++ b/src/viam/components/arm/service.py @@ -1,3 +1,5 @@ +from typing import AsyncIterator + from grpclib.server import Stream from viam.proto.common import ( @@ -17,6 +19,10 @@ GetJointPositionsResponse, IsMovingRequest, IsMovingResponse, + MoveThroughJointPositionsRequest, + MoveThroughJointPositionsResponse, + MoveThroughJointPositionsStreamedRequest, + MoveThroughJointPositionsStreamedResponse, MoveToJointPositionsRequest, MoveToJointPositionsResponse, MoveToPositionRequest, @@ -78,6 +84,58 @@ async def MoveToJointPositions(self, stream: Stream[MoveToJointPositionsRequest, response = MoveToJointPositionsResponse() await stream.send_message(response) + async def MoveThroughJointPositions( + self, + stream: Stream[MoveThroughJointPositionsRequest, MoveThroughJointPositionsResponse], + ) -> None: + request = await stream.recv_message() + assert request is not None + name = request.name + arm = self.get_resource(name) + timeout = stream.deadline.time_remaining() if stream.deadline else None + await arm.move_through_joint_positions( + list(request.positions), + extra=struct_to_dict(request.extra), + timeout=timeout, + metadata=stream.metadata, + ) + response = MoveThroughJointPositionsResponse() + await stream.send_message(response) + + async def MoveThroughJointPositionsStreamed( + self, + stream: Stream[MoveThroughJointPositionsStreamedRequest, MoveThroughJointPositionsStreamedResponse], + ) -> None: + # The first message on the request stream is the Init. + first_request = await stream.recv_message() + assert first_request is not None + assert first_request.HasField("init"), "First message must contain init" + + init = first_request.init + name = init.name + arm = self.get_resource(name) + extra = struct_to_dict(init.extra) + timeout = stream.deadline.time_remaining() if stream.deadline else None + + # Surface subsequent TrajectoryBatch messages as a flat async iterator of + # TrajectoryPoint values, which is what driver code consumes. + async def point_iterator() -> AsyncIterator[Arm.TrajectoryPoint]: + while True: + request = await stream.recv_message() + if request is None: + break + if request.HasField("batch"): + for point_proto in request.batch.points: + yield Arm.TrajectoryPoint.from_proto(point_proto) + + async for response in arm.move_through_joint_positions_streamed( # pyright: ignore [reportGeneralTypeIssues] + point_iterator(), + extra=extra, + timeout=timeout, + metadata=stream.metadata, + ): + await stream.send_message(response.to_proto()) + async def Stop(self, stream: Stream[StopRequest, StopResponse]) -> None: request = await stream.recv_message() assert request is not None From 029888884592548a011f923ee719a6d051716001 Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Tue, 30 Jun 2026 11:40:29 -0400 Subject: [PATCH 02/10] [RSDK-14160] The name field is now top-level --- src/viam/components/arm/client.py | 2 +- src/viam/components/arm/service.py | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index 844485edfa..3830bbd004 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -118,8 +118,8 @@ async def move_through_joint_positions_streamed( # type: ignore async with self.client.MoveThroughJointPositionsStreamed.open(timeout=timeout, metadata=md) as stream: await stream.send_message( MoveThroughJointPositionsStreamedRequest( + name=self.name, init=MoveThroughJointPositionsStreamedRequest.Init( - name=self.name, extra=dict_to_struct(extra), ), ) diff --git a/src/viam/components/arm/service.py b/src/viam/components/arm/service.py index 9130147491..a3c804461f 100644 --- a/src/viam/components/arm/service.py +++ b/src/viam/components/arm/service.py @@ -111,10 +111,9 @@ async def MoveThroughJointPositionsStreamed( assert first_request is not None assert first_request.HasField("init"), "First message must contain init" - init = first_request.init - name = init.name + name = first_request.name arm = self.get_resource(name) - extra = struct_to_dict(init.extra) + extra = struct_to_dict(first_request.init.extra) timeout = stream.deadline.time_remaining() if stream.deadline else None # Surface subsequent TrajectoryBatch messages as a flat async iterator of From 69db36c9fac40f07de153ff4157e3fd04b751f8a Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Wed, 24 Jun 2026 18:17:37 -0400 Subject: [PATCH 03/10] [RSDK-14160] Streaming should be in batches not point by point --- src/viam/components/arm/arm.py | 32 +++++++++++++++++++----------- src/viam/components/arm/client.py | 11 +++++----- src/viam/components/arm/service.py | 17 ++++++++-------- 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/src/viam/components/arm/arm.py b/src/viam/components/arm/arm.py index 1badd7880c..a969d4f07e 100644 --- a/src/viam/components/arm/arm.py +++ b/src/viam/components/arm/arm.py @@ -263,7 +263,7 @@ async def move_through_joint_positions( @abc.abstractmethod async def move_through_joint_positions_streamed( self, - points: AsyncIterator["Arm.TrajectoryPoint"], + batches: AsyncIterator[List["Arm.TrajectoryPoint"]], *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, @@ -272,28 +272,36 @@ async def move_through_joint_positions_streamed( """ Move the arm through a time-parameterized stream of joint waypoints. - The caller supplies an asynchronous iterator of ``TrajectoryPoint`` values; the - arm executes them in order as they arrive. Per-message responses are yielded back - to the caller as they are produced by the arm. Arm-side errors raised during - execution surface as a gRPC status on the response iteration -- the + The caller supplies an asynchronous iterator of batches, where each batch is a + ``list`` of ``TrajectoryPoint`` values. Each list yielded by the caller is sent + as one wire ``TrajectoryBatch``; the caller therefore controls the wire cadence + directly, and can pack enough points into the first send to ride out network + jitter on tight-cadence trajectories. A caller that genuinely wants per-point + granularity yields ``[point]`` for each point. Per-message responses are yielded + back to the caller as they are produced by the arm. Arm-side errors raised + during execution surface as a gRPC status on the response iteration -- the ``async for`` raises rather than returning. :: my_arm = Arm.from_robot(robot=machine, name="my_arm") - async def points(): - yield Arm.TrajectoryPoint(time=timedelta(seconds=0.0), positions=[0.0, 0.0, 0.0, 0.0, 0.0]) - yield Arm.TrajectoryPoint(time=timedelta(seconds=1.0), positions=[10.0, 0.0, 0.0, 0.0, 0.0]) + async def batches(): + yield [ + Arm.TrajectoryPoint(time=timedelta(seconds=0.0), positions=[0.0, 0.0, 0.0, 0.0, 0.0]), + Arm.TrajectoryPoint(time=timedelta(seconds=1.0), positions=[10.0, 0.0, 0.0, 0.0, 0.0]), + ] - async for resp in my_arm.move_through_joint_positions_streamed(points()): + async for resp in my_arm.move_through_joint_positions_streamed(batches()): # Observe arm-side acknowledgements; errors raise out of this iteration. pass Args: - points: an asynchronous iterator of ``TrajectoryPoint`` values. Point times - must be strictly monotonically increasing across the stream, and the first - point's time must be zero. + batches: an asynchronous iterator of lists of ``TrajectoryPoint`` values. + Each list maps to one wire ``TrajectoryBatch``. Point times must be + strictly monotonically increasing across the entire stream (not just + within each batch), and the first point of the very first batch must + have time zero. Returns: AsyncIterator[Arm.Response]: a live stream of per-message responses. diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index 3830bbd004..364c818381 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -108,7 +108,7 @@ async def move_through_joint_positions( async def move_through_joint_positions_streamed( # type: ignore self, - points: AsyncIterator[Arm.TrajectoryPoint], + batches: AsyncIterator[List[Arm.TrajectoryPoint]], *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, @@ -125,16 +125,17 @@ async def move_through_joint_positions_streamed( # type: ignore ) ) - # Drive the caller-supplied point iterator on a background task so that send + # Drive the caller-supplied batch iterator on a background task so that send # and receive proceed independently -- arm-side acknowledgements and errors - # may surface at any time, including while the caller is still producing points. + # may surface at any time, including while the caller is still producing + # batches. Each list yielded by the caller maps 1:1 to one wire TrajectoryBatch. async def send_loop() -> None: try: - async for point in points: + async for batch in batches: await stream.send_message( MoveThroughJointPositionsStreamedRequest( batch=MoveThroughJointPositionsStreamedRequest.TrajectoryBatch( - points=[point.to_proto()], + points=[point.to_proto() for point in batch], ), ) ) diff --git a/src/viam/components/arm/service.py b/src/viam/components/arm/service.py index a3c804461f..4998f7de16 100644 --- a/src/viam/components/arm/service.py +++ b/src/viam/components/arm/service.py @@ -1,4 +1,4 @@ -from typing import AsyncIterator +from typing import AsyncIterator, List from grpclib.server import Stream @@ -116,19 +116,20 @@ async def MoveThroughJointPositionsStreamed( extra = struct_to_dict(first_request.init.extra) timeout = stream.deadline.time_remaining() if stream.deadline else None - # Surface subsequent TrajectoryBatch messages as a flat async iterator of - # TrajectoryPoint values, which is what driver code consumes. - async def point_iterator() -> AsyncIterator[Arm.TrajectoryPoint]: + # Surface subsequent TrajectoryBatch messages as an async iterator of lists of + # TrajectoryPoint values -- one yielded list per wire TrajectoryBatch -- which + # is what driver code consumes. Empty batches and non-Batch messages are + # filtered out by the dispatcher and never surface to the driver. + async def batch_iterator() -> AsyncIterator[List[Arm.TrajectoryPoint]]: while True: request = await stream.recv_message() if request is None: break - if request.HasField("batch"): - for point_proto in request.batch.points: - yield Arm.TrajectoryPoint.from_proto(point_proto) + if request.HasField("batch") and request.batch.points: + yield [Arm.TrajectoryPoint.from_proto(point_proto) for point_proto in request.batch.points] async for response in arm.move_through_joint_positions_streamed( # pyright: ignore [reportGeneralTypeIssues] - point_iterator(), + batch_iterator(), extra=extra, timeout=timeout, metadata=stream.metadata, From c07eeb2dc599ab548f77aa1ec93ddfdc81d7b657 Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Thu, 16 Jul 2026 15:07:09 -0400 Subject: [PATCH 04/10] [RSDK-14160] Get closer to production quality --- docs/examples/my_cool_arm.py | 29 ++++- examples/complex_module/src/arm/my_arm.py | 29 ++++- examples/server/v1/components.py | 22 ++++ src/viam/components/arm/arm.py | 66 ++++++------ src/viam/components/arm/client.py | 76 +++++++++---- src/viam/components/arm/service.py | 90 +++++++++++++--- tests/mocks/components.py | 32 ++++++ tests/test_arm.py | 123 +++++++++++++++++++++- tests/test_robot.py | 21 +++- 9 files changed, 417 insertions(+), 71 deletions(-) diff --git a/docs/examples/my_cool_arm.py b/docs/examples/my_cool_arm.py index 889b3cb667..aefd1d1764 100644 --- a/docs/examples/my_cool_arm.py +++ b/docs/examples/my_cool_arm.py @@ -2,7 +2,7 @@ import asyncio import json -from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing import Any, AsyncIterator, Dict, List, Mapping, Optional, Tuple, Union from viam.components.arm import Arm, JointPositions, KinematicsFileFormat, Pose from viam.operations import run_with_operation @@ -91,6 +91,33 @@ async def move_to_joint_positions(self, positions: JointPositions, extra: Option self.is_stopped = True + async def move_through_joint_positions( + self, positions: List[JointPositions], *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs + ): + # Move through the waypoints in order. A real arm would plan a smooth path across them. + self.is_stopped = False + for jp in positions: + self.joint_positions = jp + self.is_stopped = True + + async def move_through_joint_positions_streamed( # type: ignore + self, + batches: AsyncIterator[List[Arm.TrajectoryPoint]], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> AsyncIterator[Arm.TrajectoryUpdate]: + # Each list the framework hands us is one wire batch. Walk it point by point to drive the + # arm, then send one update back per batch so the caller can watch progress and so a fault + # reaches it while the trajectory is still running. + self.is_stopped = False + async for batch in batches: + for point in batch: + self.joint_positions = JointPositions(values=point.positions) + yield Arm.TrajectoryUpdate() + self.is_stopped = True + async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs): self.is_stopped = True diff --git a/examples/complex_module/src/arm/my_arm.py b/examples/complex_module/src/arm/my_arm.py index 00b3000df4..24c07a18ed 100644 --- a/examples/complex_module/src/arm/my_arm.py +++ b/examples/complex_module/src/arm/my_arm.py @@ -1,6 +1,6 @@ import asyncio import os -from typing import Any, ClassVar, Dict, List, Mapping, Optional, Tuple +from typing import Any, AsyncIterator, ClassVar, Dict, List, Mapping, Optional, Tuple from typing_extensions import Self @@ -93,6 +93,33 @@ async def move_to_joint_positions(self, positions: JointPositions, extra: Option self.joint_positions = positions self.is_stopped = True + async def move_through_joint_positions( + self, positions: List[JointPositions], *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs + ): + # Move through the waypoints in order. A real arm would plan a smooth path across them. + self.is_stopped = False + for jp in positions: + self.joint_positions = jp + self.is_stopped = True + + async def move_through_joint_positions_streamed( # type: ignore + self, + batches: AsyncIterator[List[Arm.TrajectoryPoint]], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> AsyncIterator[Arm.TrajectoryUpdate]: + # Each list the framework hands us is one wire batch. Walk it point by point to drive the + # arm, then send one update back per batch so the caller can watch progress and so a fault + # reaches it while the trajectory is still running. + self.is_stopped = False + async for batch in batches: + for point in batch: + self.joint_positions = JointPositions(values=point.positions) + yield Arm.TrajectoryUpdate() + self.is_stopped = True + async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs): self.is_stopped = True diff --git a/examples/server/v1/components.py b/examples/server/v1/components.py index ad9035806b..6320c48467 100644 --- a/examples/server/v1/components.py +++ b/examples/server/v1/components.py @@ -95,6 +95,28 @@ async def move_to_joint_positions(self, positions: JointPositions, extra: Option self.is_stopped = False self.joint_positions = positions + async def move_through_joint_positions( + self, positions: List[JointPositions], *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs + ): + self.is_stopped = False + if positions: + self.joint_positions = positions[-1] + + async def move_through_joint_positions_streamed( # type: ignore + self, + batches: AsyncIterator[List[Arm.TrajectoryPoint]], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> AsyncIterator[Arm.TrajectoryUpdate]: + self.is_stopped = False + async for batch in batches: + for point in batch: + self.joint_positions = JointPositions(values=point.positions) + yield Arm.TrajectoryUpdate() + self.is_stopped = True + async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs): self.is_stopped = True diff --git a/src/viam/components/arm/arm.py b/src/viam/components/arm/arm.py index a969d4f07e..98411cc207 100644 --- a/src/viam/components/arm/arm.py +++ b/src/viam/components/arm/arm.py @@ -45,10 +45,9 @@ class KinematicConstraints: """ Optional per-waypoint kinematic constraints attached to a ``TrajectoryPoint``. - Joint velocities are required; joint accelerations are optional. The presence - of velocities is what unlocks the option to pass accelerations -- accelerations - cannot be specified without velocities. Each list is ordered spatially from the - base toward the end effector of the arm and must match the arm's DOF. + Velocities are required whenever constraints are present; accelerations are optional and + may only be given alongside velocities. Each list runs from the base joint out to the end + effector and must match the arm's degrees of freedom. """ velocities: List[float] @@ -62,11 +61,11 @@ class KinematicConstraints: @dataclass class TrajectoryPoint: """ - A single waypoint of a kinematized trajectory consumed by + A single waypoint of a kinematized trajectory, as consumed by ``move_through_joint_positions_streamed``. - Times across a streamed trajectory must be strictly monotonically increasing. - The first point in a stream must have ``time`` equal to zero. + Point times must strictly increase across a stream, and the first point must have a + ``time`` of zero. """ time: timedelta @@ -114,13 +113,12 @@ def from_proto(cls, proto: TrajectoryPointPb) -> "Arm.TrajectoryPoint": ) @dataclass - class Response: + class TrajectoryUpdate: """ - Per-message response from ``move_through_joint_positions_streamed``. + An update reported by the arm as it executes a ``move_through_joint_positions_streamed`` trajectory. - For the proof-of-concept the response payload is empty; the type exists so that - callers can iterate the response stream today and pick up future per-batch - status fields without an API reshape. + Today it carries only ``extra``. The type exists as its own message so that + per-batch execution status can be added later without reshaping the streaming API. """ extra: Optional[Dict[str, Any]] = None @@ -130,7 +128,7 @@ def to_proto(self) -> MoveThroughJointPositionsStreamedResponse: return MoveThroughJointPositionsStreamedResponse(extra=dict_to_struct(self.extra)) @classmethod - def from_proto(cls, proto: MoveThroughJointPositionsStreamedResponse) -> "Arm.Response": + def from_proto(cls, proto: MoveThroughJointPositionsStreamedResponse) -> "Arm.TrajectoryUpdate": return cls(extra=struct_to_dict(proto.extra) if proto.HasField("extra") else None) @abc.abstractmethod @@ -268,19 +266,28 @@ async def move_through_joint_positions_streamed( extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs, - ) -> AsyncIterator["Arm.Response"]: + ) -> AsyncIterator["Arm.TrajectoryUpdate"]: """ Move the arm through a time-parameterized stream of joint waypoints. - The caller supplies an asynchronous iterator of batches, where each batch is a - ``list`` of ``TrajectoryPoint`` values. Each list yielded by the caller is sent - as one wire ``TrajectoryBatch``; the caller therefore controls the wire cadence - directly, and can pack enough points into the first send to ride out network - jitter on tight-cadence trajectories. A caller that genuinely wants per-point - granularity yields ``[point]`` for each point. Per-message responses are yielded - back to the caller as they are produced by the arm. Arm-side errors raised - during execution surface as a gRPC status on the response iteration -- the - ``async for`` raises rather than returning. + The caller supplies an asynchronous iterator of batches, each batch a ``list`` of + ``TrajectoryPoint``. Each list the caller yields is sent as one wire ``TrajectoryBatch``, + so the caller sets the wire cadence by choosing how many points go in each list; a caller + that wants to send one point at a time yields a single-element list. The arm's updates are + yielded back as they arrive, so iterating the return value observes execution in real time. + If the arm faults mid-trajectory, that fault arrives as a gRPC error on the iteration, so the + ``async for`` raises instead of ending normally. Delivering faults mid-execution, not only at + the end, is the point of streaming this call. + + The first point of the stream must have time zero, and if it carries velocity constraints + those velocities must all be zero, since the trajectory starts from rest. Point times must + strictly increase across the whole stream, not merely within a batch. A ``timeout``, if + given, bounds the entire stream, not a single message, so an open-ended trajectory should + normally leave it unset. + + An implementation must yield at least one ``TrajectoryUpdate`` before returning. Besides + reporting progress, this is what makes the implementation an asynchronous generator; a + coroutine that never yields cannot be iterated as a stream and fails at runtime. :: @@ -292,19 +299,16 @@ async def batches(): Arm.TrajectoryPoint(time=timedelta(seconds=1.0), positions=[10.0, 0.0, 0.0, 0.0, 0.0]), ] - async for resp in my_arm.move_through_joint_positions_streamed(batches()): - # Observe arm-side acknowledgements; errors raise out of this iteration. + async for update in my_arm.move_through_joint_positions_streamed(batches()): + # Observe the arm's updates; a fault raises out of this iteration. pass Args: - batches: an asynchronous iterator of lists of ``TrajectoryPoint`` values. - Each list maps to one wire ``TrajectoryBatch``. Point times must be - strictly monotonically increasing across the entire stream (not just - within each batch), and the first point of the very first batch must - have time zero. + batches: an asynchronous iterator of lists of ``TrajectoryPoint``. Each list becomes + one wire ``TrajectoryBatch``. Returns: - AsyncIterator[Arm.Response]: a live stream of per-message responses. + AsyncIterator[Arm.TrajectoryUpdate]: the arm's updates, yielded as they arrive. """ ... diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index 364c818381..c0f6c2401e 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -113,8 +113,11 @@ async def move_through_joint_positions_streamed( # type: ignore extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs, - ) -> AsyncIterator[Arm.Response]: + ) -> AsyncIterator[Arm.TrajectoryUpdate]: md = kwargs.get("metadata", self.Metadata()).proto + # A timeout, if the caller supplies one, bounds the whole stream rather than a single + # message, so it defaults to none; binding a deadline here would cancel a long but + # healthy trajectory partway through. async with self.client.MoveThroughJointPositionsStreamed.open(timeout=timeout, metadata=md) as stream: await stream.send_message( MoveThroughJointPositionsStreamedRequest( @@ -125,43 +128,72 @@ async def move_through_joint_positions_streamed( # type: ignore ) ) - # Drive the caller-supplied batch iterator on a background task so that send - # and receive proceed independently -- arm-side acknowledgements and errors - # may surface at any time, including while the caller is still producing - # batches. Each list yielded by the caller maps 1:1 to one wire TrajectoryBatch. - async def send_loop() -> None: + # Sending and receiving have to proceed at the same time. The arm can report an update + # or a fault at any point, including while the caller is still producing batches, so we + # run the sends on a background task and drain the arm's updates here. Each list the + # caller yields becomes one wire TrajectoryBatch. + # + # We hold onto a failure of the caller's own iterator separately. If the caller's batch + # production raises, that is the caller's bug and the fault they need to see, so it wins + # over whatever the receive side reports once we tear the stream down (which is usually + # just a consequence of that same failure). + producer_exception: Optional[BaseException] = None + + async def send_batches() -> None: + nonlocal producer_exception try: - async for batch in batches: - await stream.send_message( - MoveThroughJointPositionsStreamedRequest( + iterator = batches.__aiter__() + while True: + try: + batch = await iterator.__anext__() + message = MoveThroughJointPositionsStreamedRequest( batch=MoveThroughJointPositionsStreamedRequest.TrajectoryBatch( points=[point.to_proto() for point in batch], - ), + ) ) - ) + except StopAsyncIteration: + break + except asyncio.CancelledError: + # Our own teardown, not the caller's failure; do not claim it as one. + raise + except BaseException as exc: + producer_exception = exc + raise + await stream.send_message(message) finally: + # TODO: half-closing is right when the caller's batches are exhausted, but it + # also runs when the caller's batch production raised, and there it is wrong. A + # half-close tells the arm the trajectory completed normally, when a producer + # failure has actually left it truncated, so the arm may be brought to rest at a + # point that was never meant to be its last. The C++ SDK cancels the RPC in this + # case so the arm sees an abort. Matching that here is not a one-line change: + # awaiting stream.cancel() from this task deadlocks against the concurrent + # receive loop. A correct fix restructures the teardown to await the receive and + # the send together, cancel the pending receive when the producer fails, and let + # the producer exception propagate out of the `async with` so grpclib resets the + # stream. Deferred to a focused follow-up. await stream.end() - send_task = asyncio.create_task(send_loop()) + send_task = asyncio.create_task(send_batches()) try: - async for response in stream: - yield Arm.Response.from_proto(response) + async for update in stream: + yield Arm.TrajectoryUpdate.from_proto(update) except BaseException: - # Recv side raised (a gRPC status from the server, the generator being - # closed by the consumer, or cancellation). Tear down the send side - # and suppress whatever it produces -- the recv-side cause is what - # the caller needs to see, not a downstream send-side cleanup error. + # The receive side ended abnormally: the arm faulted, the caller closed this + # generator, or the call was cancelled. Cancel the send task, discard whatever it + # unwinds with, and re-raise, preferring a producer failure over the receive-side + # error. send_task.cancel() try: await send_task except BaseException: pass + if producer_exception is not None: + raise producer_exception raise else: - # Recv side completed normally. Surface any send-side failure -- - # most importantly, an exception from the caller's points iterator, - # which would otherwise be silently swallowed and defeat the whole - # point of the bidi shape. + # The receive side finished cleanly. Wait on the send task so that a failure in the + # caller's batch production still surfaces rather than being swallowed. await send_task async def stop( diff --git a/src/viam/components/arm/service.py b/src/viam/components/arm/service.py index 4998f7de16..f09454351a 100644 --- a/src/viam/components/arm/service.py +++ b/src/viam/components/arm/service.py @@ -1,5 +1,7 @@ +from datetime import timedelta from typing import AsyncIterator, List +from grpclib import GRPCError, Status from grpclib.server import Stream from viam.proto.common import ( @@ -37,6 +39,51 @@ from .arm import Arm +class _TrajectoryStreamValidator: + """ + Enforces the trajectory contract across a single streamed request, one point at a time. + + The checks match what the other SDKs apply on the server side (see the C++ SDK's + TrajectoryStreamValidator): the trajectory begins at time zero and from rest, point times + strictly increase, and any constraints are dimensionally consistent with the positions. + State carries across batches, so a single validator must see every point of the stream in + order. + """ + + def __init__(self) -> None: + self._seen_first = False + self._last_time = timedelta() + + def check(self, point: Arm.TrajectoryPoint) -> None: + if not self._seen_first: + if point.time != timedelta(): + raise GRPCError(Status.INVALID_ARGUMENT, "first trajectory point must have time zero") + elif point.time <= self._last_time: + raise GRPCError(Status.INVALID_ARGUMENT, "trajectory point times must strictly increase") + + if not point.positions: + raise GRPCError(Status.INVALID_ARGUMENT, "trajectory point must carry at least one position") + + constraints = point.constraints + if constraints is not None: + if len(constraints.velocities) != len(point.positions): + raise GRPCError( + Status.INVALID_ARGUMENT, + "trajectory point must carry one velocity per position when constraints are present", + ) + # The arm has to start from a standstill, so the first point may not ask for motion. + if not self._seen_first and any(velocity != 0.0 for velocity in constraints.velocities): + raise GRPCError(Status.INVALID_ARGUMENT, "first trajectory point must start from rest (all velocities zero)") + if constraints.accelerations is not None and len(constraints.accelerations) != len(constraints.velocities): + raise GRPCError( + Status.INVALID_ARGUMENT, + "trajectory point must carry one acceleration per velocity when accelerations are present", + ) + + self._seen_first = True + self._last_time = point.time + + class ArmRPCService(UnimplementedArmServiceBase, ResourceRPCServiceBase[Arm]): """ gRPC Service for an Arm @@ -106,35 +153,50 @@ async def MoveThroughJointPositionsStreamed( self, stream: Stream[MoveThroughJointPositionsStreamedRequest, MoveThroughJointPositionsStreamedResponse], ) -> None: - # The first message on the request stream is the Init. + # The stream opens with exactly one Init, which names the arm and carries the sticky extra + # arguments. The name sits at the top level of the request rather than inside Init because + # that is where the RDK server reads it. first_request = await stream.recv_message() - assert first_request is not None - assert first_request.HasField("init"), "First message must contain init" + if first_request is None: + raise GRPCError(Status.INVALID_ARGUMENT, "stream closed before init message") + if not first_request.HasField("init"): + raise GRPCError(Status.INVALID_ARGUMENT, "first message must be init") name = first_request.name arm = self.get_resource(name) extra = struct_to_dict(first_request.init.extra) timeout = stream.deadline.time_remaining() if stream.deadline else None - # Surface subsequent TrajectoryBatch messages as an async iterator of lists of - # TrajectoryPoint values -- one yielded list per wire TrajectoryBatch -- which - # is what driver code consumes. Empty batches and non-Batch messages are - # filtered out by the dispatcher and never surface to the driver. - async def batch_iterator() -> AsyncIterator[List[Arm.TrajectoryPoint]]: + # Turn the rest of the request stream into the async iterator of point-lists the driver + # consumes, validating each point as it arrives. Validation lives here on the server so + # that every arm implementation gets the same contract enforcement without having to + # repeat it. An empty batch is a wire no-op and is skipped; a second Init, or any message + # that is not a batch, is a protocol violation that ends the stream with an error. + validator = _TrajectoryStreamValidator() + + async def batches() -> AsyncIterator[List[Arm.TrajectoryPoint]]: while True: request = await stream.recv_message() if request is None: - break - if request.HasField("batch") and request.batch.points: - yield [Arm.TrajectoryPoint.from_proto(point_proto) for point_proto in request.batch.points] + return + message = request.WhichOneof("message") + if message == "init": + raise GRPCError(Status.INVALID_ARGUMENT, "init may only appear as the first message") + if message != "batch": + raise GRPCError(Status.INVALID_ARGUMENT, "expected a trajectory batch") + points = [Arm.TrajectoryPoint.from_proto(point_proto) for point_proto in request.batch.points] + for point in points: + validator.check(point) + if points: + yield points - async for response in arm.move_through_joint_positions_streamed( # pyright: ignore [reportGeneralTypeIssues] - batch_iterator(), + async for update in arm.move_through_joint_positions_streamed( # pyright: ignore [reportGeneralTypeIssues] + batches(), extra=extra, timeout=timeout, metadata=stream.metadata, ): - await stream.send_message(response.to_proto()) + await stream.send_message(update.to_proto()) async def Stop(self, stream: Stream[StopRequest, StopResponse]) -> None: request = await stream.recv_message() diff --git a/tests/mocks/components.py b/tests/mocks/components.py index 192c0de055..eb143da719 100644 --- a/tests/mocks/components.py +++ b/tests/mocks/components.py @@ -67,6 +67,8 @@ def __init__(self, name: str): self.geometries = GEOMETRIES self.extra = None self.timeout: Optional[float] = None + self.move_through_positions: Optional[List[JointPositions]] = None + self.streamed_points: List[Arm.TrajectoryPoint] = [] super().__init__(name) async def get_end_position(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Pose: @@ -102,6 +104,36 @@ async def move_to_joint_positions( self.extra = extra self.timeout = timeout + async def move_through_joint_positions( + self, positions: List[JointPositions], *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs + ): + self.move_through_positions = positions + if positions: + self.joint_positions = positions[-1] + self.is_stopped = False + self.extra = extra + self.timeout = timeout + + async def move_through_joint_positions_streamed( # type: ignore + self, + batches: AsyncIterator[List[Arm.TrajectoryPoint]], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> AsyncIterator[Arm.TrajectoryUpdate]: + self.is_stopped = False + self.extra = extra + self.timeout = timeout + self.streamed_points = [] + async for batch in batches: + for point in batch: + self.streamed_points.append(point) + self.joint_positions = JointPositions(values=point.positions) + # Acknowledge each batch with one update, as a real driver would. + yield Arm.TrajectoryUpdate() + self.is_stopped = True + async def stop(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs): self.is_stopped = True self.extra = extra diff --git a/tests/test_arm.py b/tests/test_arm.py index 1100f7d4f3..caa264982f 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -1,6 +1,11 @@ +from datetime import timedelta +from typing import AsyncIterator, List + +import pytest +from grpclib import GRPCError, Status from grpclib.testing import ChannelFor -from viam.components.arm import ArmClient, KinematicsFileFormat +from viam.components.arm import Arm, ArmClient, KinematicsFileFormat from viam.components.arm.service import ArmRPCService from viam.proto.common import ( DoCommandRequest, @@ -268,3 +273,119 @@ async def test_extra(self): client = ArmClient(self.name, channel) await client.get_end_position(extra={"foo": "bar"}) assert self.arm.extra == {"foo": "bar"} + + +async def _batches(batch_lists: List[List[Arm.TrajectoryPoint]]) -> AsyncIterator[List[Arm.TrajectoryPoint]]: + for batch in batch_lists: + yield batch + + +class TestArmStreamed: + @classmethod + def setup_class(cls): + cls.name = "arm" + cls.arm = MockArm(name=cls.name) + cls.manager = ResourceManager([cls.arm]) + cls.service = ArmRPCService(cls.manager) + + async def test_move_through_joint_positions(self): + async with ChannelFor([self.service]) as channel: + client = ArmClient(self.name, channel) + positions = [JointPositions(values=[1, 2, 3]), JointPositions(values=[4, 5, 6])] + await client.move_through_joint_positions(positions) + assert self.arm.move_through_positions == positions + + async def test_streamed_round_trip(self): + async with ChannelFor([self.service]) as channel: + client = ArmClient(self.name, channel) + first = [ + Arm.TrajectoryPoint(time=timedelta(0), positions=[0.0, 0.0, 0.0]), + Arm.TrajectoryPoint(time=timedelta(seconds=1), positions=[1.0, 2.0, 3.0]), + ] + second = [Arm.TrajectoryPoint(time=timedelta(seconds=2), positions=[4.0, 5.0, 6.0])] + updates = [update async for update in client.move_through_joint_positions_streamed(_batches([first, second]))] + assert len(updates) == 2 + assert len(self.arm.streamed_points) == 3 + assert self.arm.streamed_points[-1].positions == [4.0, 5.0, 6.0] + + async def test_streamed_rejects_nonzero_first_time(self): + async with ChannelFor([self.service]) as channel: + client = ArmClient(self.name, channel) + bad = [Arm.TrajectoryPoint(time=timedelta(seconds=1), positions=[0.0])] + with pytest.raises(GRPCError) as excinfo: + async for _ in client.move_through_joint_positions_streamed(_batches([bad])): + pass + assert excinfo.value.status == Status.INVALID_ARGUMENT + + async def test_streamed_rejects_nonmonotonic_time(self): + async with ChannelFor([self.service]) as channel: + client = ArmClient(self.name, channel) + bad = [ + Arm.TrajectoryPoint(time=timedelta(0), positions=[0.0]), + Arm.TrajectoryPoint(time=timedelta(0), positions=[0.0]), + ] + with pytest.raises(GRPCError) as excinfo: + async for _ in client.move_through_joint_positions_streamed(_batches([bad])): + pass + assert excinfo.value.status == Status.INVALID_ARGUMENT + + async def test_streamed_rejects_first_point_in_motion(self): + async with ChannelFor([self.service]) as channel: + client = ArmClient(self.name, channel) + bad = [ + Arm.TrajectoryPoint( + time=timedelta(0), positions=[0.0], constraints=Arm.KinematicConstraints(velocities=[1.0]) + ) + ] + with pytest.raises(GRPCError) as excinfo: + async for _ in client.move_through_joint_positions_streamed(_batches([bad])): + pass + assert excinfo.value.status == Status.INVALID_ARGUMENT + + async def test_streamed_producer_error_surfaces(self): + async with ChannelFor([self.service]) as channel: + client = ArmClient(self.name, channel) + + class ProducerError(Exception): + pass + + async def failing_batches() -> AsyncIterator[List[Arm.TrajectoryPoint]]: + yield [Arm.TrajectoryPoint(time=timedelta(0), positions=[0.0])] + raise ProducerError() + + with pytest.raises(ProducerError): + async for _ in client.move_through_joint_positions_streamed(failing_batches()): + pass + + +class TestTrajectoryConversions: + def test_trajectory_point_round_trip_with_accelerations(self): + point = Arm.TrajectoryPoint( + time=timedelta(seconds=1, milliseconds=500), + positions=[1.0, 2.0, 3.0], + constraints=Arm.KinematicConstraints(velocities=[0.5, 0.5, 0.5], accelerations=[0.25, 0.25, 0.25]), + ) + restored = Arm.TrajectoryPoint.from_proto(point.to_proto()) + assert restored.time == point.time + assert restored.positions == point.positions + assert restored.constraints is not None + assert restored.constraints.velocities == [0.5, 0.5, 0.5] + assert restored.constraints.accelerations == [0.25, 0.25, 0.25] + + def test_trajectory_point_round_trip_without_constraints(self): + point = Arm.TrajectoryPoint(time=timedelta(0), positions=[0.0, 0.0]) + restored = Arm.TrajectoryPoint.from_proto(point.to_proto()) + assert restored.time == timedelta(0) + assert restored.positions == [0.0, 0.0] + assert restored.constraints is None + + def test_kinematic_constraints_without_accelerations(self): + point = Arm.TrajectoryPoint(time=timedelta(seconds=2), positions=[1.0], constraints=Arm.KinematicConstraints(velocities=[0.0])) + restored = Arm.TrajectoryPoint.from_proto(point.to_proto()) + assert restored.constraints is not None + assert restored.constraints.velocities == [0.0] + assert restored.constraints.accelerations is None + + def test_trajectory_update_round_trip(self): + restored = Arm.TrajectoryUpdate.from_proto(Arm.TrajectoryUpdate(extra={"foo": "bar"}).to_proto()) + assert restored.extra == {"foo": "bar"} diff --git a/tests/test_robot.py b/tests/test_robot.py index a09aeeff79..17705db54c 100644 --- a/tests/test_robot.py +++ b/tests/test_robot.py @@ -1,5 +1,5 @@ import asyncio -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, AsyncIterator, Dict, List, Optional, Tuple from unittest import mock import pytest @@ -497,6 +497,25 @@ async def move_to_joint_positions( ): return await self.actual_client.move_to_joint_positions(positions, extra=extra, timeout=timeout) + async def move_through_joint_positions( + self, + positions: List[JointPositions], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + ): + return await self.actual_client.move_through_joint_positions(positions, extra=extra, timeout=timeout) + + async def move_through_joint_positions_streamed( + self, + batches: AsyncIterator[List[Arm.TrajectoryPoint]], + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + ) -> AsyncIterator[Arm.TrajectoryUpdate]: + async for update in self.actual_client.move_through_joint_positions_streamed(batches, extra=extra, timeout=timeout): + yield update + async def get_joint_positions( self, *, From 930d8f45dc8651d8d6656116bdb9bd28afe83c76 Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Thu, 16 Jul 2026 16:05:12 -0400 Subject: [PATCH 05/10] [RSDK-14160] Working cancel on batch failure but really ugly --- src/viam/components/arm/client.py | 120 +++++++++++++++++------------- 1 file changed, 68 insertions(+), 52 deletions(-) diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index c0f6c2401e..251be6c1a8 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -128,72 +128,88 @@ async def move_through_joint_positions_streamed( # type: ignore ) ) - # Sending and receiving have to proceed at the same time. The arm can report an update - # or a fault at any point, including while the caller is still producing batches, so we - # run the sends on a background task and drain the arm's updates here. Each list the - # caller yields becomes one wire TrajectoryBatch. + # Sending and receiving proceed at the same time: the arm can report an update or a + # fault at any point, including while the caller is still producing batches. The sends + # run on their own task and the receives on another; this loop watches both and yields + # each update to the caller as it arrives. Each list the caller yields becomes one wire + # TrajectoryBatch. # - # We hold onto a failure of the caller's own iterator separately. If the caller's batch - # production raises, that is the caller's bug and the fault they need to see, so it wins - # over whatever the receive side reports once we tear the stream down (which is usually - # just a consequence of that same failure). + # A failure of the caller's own batch iterator is held separately. It is the caller's + # bug and the fault they need to see, so it wins over whatever the receive side reports + # while the stream is torn down. producer_exception: Optional[BaseException] = None async def send_batches() -> None: nonlocal producer_exception - try: - iterator = batches.__aiter__() - while True: - try: - batch = await iterator.__anext__() - message = MoveThroughJointPositionsStreamedRequest( - batch=MoveThroughJointPositionsStreamedRequest.TrajectoryBatch( - points=[point.to_proto() for point in batch], - ) + iterator = batches.__aiter__() + while True: + try: + batch = await iterator.__anext__() + message = MoveThroughJointPositionsStreamedRequest( + batch=MoveThroughJointPositionsStreamedRequest.TrajectoryBatch( + points=[point.to_proto() for point in batch], ) - except StopAsyncIteration: - break - except asyncio.CancelledError: - # Our own teardown, not the caller's failure; do not claim it as one. - raise - except BaseException as exc: - producer_exception = exc - raise - await stream.send_message(message) - finally: - # TODO: half-closing is right when the caller's batches are exhausted, but it - # also runs when the caller's batch production raised, and there it is wrong. A - # half-close tells the arm the trajectory completed normally, when a producer - # failure has actually left it truncated, so the arm may be brought to rest at a - # point that was never meant to be its last. The C++ SDK cancels the RPC in this - # case so the arm sees an abort. Matching that here is not a one-line change: - # awaiting stream.cancel() from this task deadlocks against the concurrent - # receive loop. A correct fix restructures the teardown to await the receive and - # the send together, cancel the pending receive when the producer fails, and let - # the producer exception propagate out of the `async with` so grpclib resets the - # stream. Deferred to a focused follow-up. - await stream.end() + ) + except StopAsyncIteration: + break + except asyncio.CancelledError: + raise + except BaseException as exc: + # Record the caller's producer failure and stop. The main loop surfaces it + # and aborts the stream. We deliberately do not tear the stream down here: + # calling stream.cancel() from this task deadlocks against the concurrent + # receive (confirmed end to end against a real server, not just in tests). + producer_exception = exc + raise + await stream.send_message(message) + # Batches exhausted cleanly; half-close so the arm knows the trajectory completed. + await stream.end() send_task = asyncio.create_task(send_batches()) + recv_task = asyncio.ensure_future(stream.recv_message()) + watch_send = True try: - async for update in stream: - yield Arm.TrajectoryUpdate.from_proto(update) + while True: + wait_set = {recv_task, send_task} if watch_send else {recv_task} + await asyncio.wait(wait_set, return_when=asyncio.FIRST_COMPLETED) + + # Handle the send task finishing before consuming any ready update. A clean + # finish (batches exhausted and half-closed) just means we stop watching it and + # keep receiving until the server closes. A failure means the caller's producer + # broke, so we abort by raising into the handler below. The handler tears down + # the still-pending receive before the `async with` resets the stream, so nothing + # is parked in a read when the reset happens; that is precisely what a direct + # stream.cancel() from the send task cannot manage without deadlocking. + if watch_send and send_task.done(): + watch_send = False + send_error = send_task.exception() + if send_error is not None: + raise send_error + + if recv_task.done(): + update = recv_task.result() + if update is None: + # The server closed the response stream: the trajectory is complete. + break + yield Arm.TrajectoryUpdate.from_proto(update) + recv_task = asyncio.ensure_future(stream.recv_message()) except BaseException: - # The receive side ended abnormally: the arm faulted, the caller closed this - # generator, or the call was cancelled. Cancel the send task, discard whatever it - # unwinds with, and re-raise, preferring a producer failure over the receive-side - # error. - send_task.cancel() - try: - await send_task - except BaseException: - pass + # The receive side raised (a server fault or cancellation), the producer failed, or + # the caller closed this generator. Cancel both tasks and wait them out so neither is + # left parked in a read or write when the `async with` resets the stream. Prefer the + # caller's producer failure when there is one. + for task in (send_task, recv_task): + task.cancel() + try: + await task + except BaseException: + pass if producer_exception is not None: raise producer_exception raise else: - # The receive side finished cleanly. Wait on the send task so that a failure in the - # caller's batch production still surfaces rather than being swallowed. + # Clean completion: the server closed the response stream after we half-closed. Wait + # on the send task so a producer failure that raced in right at the end still surfaces. await send_task async def stop( From a058679afa338121fcbe64db5e98b44424177be0 Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Thu, 16 Jul 2026 16:52:24 -0400 Subject: [PATCH 06/10] [RSDK-14160] Maybe less awful batch error handling --- src/viam/components/arm/client.py | 146 ++++++++++++++++-------------- 1 file changed, 76 insertions(+), 70 deletions(-) diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index 251be6c1a8..fc89fa188b 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -128,89 +128,95 @@ async def move_through_joint_positions_streamed( # type: ignore ) ) - # Sending and receiving proceed at the same time: the arm can report an update or a - # fault at any point, including while the caller is still producing batches. The sends - # run on their own task and the receives on another; this loop watches both and yields - # each update to the caller as it arrives. Each list the caller yields becomes one wire + # Sending and receiving run concurrently as tasks: the arm can report an update or a + # fault at any point, including while the caller is still producing batches. An async + # generator cannot yield a value produced inside a task, so the receive task feeds a + # queue that this generator drains and yields from; a sentinel marks the point past + # which no more updates will arrive. Each list the caller yields becomes one wire # TrajectoryBatch. # - # A failure of the caller's own batch iterator is held separately. It is the caller's - # bug and the fault they need to see, so it wins over whatever the receive side reports - # while the stream is torn down. + # A failure of the caller's own batch iterator is recorded separately. It is the + # caller's bug and the fault they need to see, so it wins over whatever the receive side + # reports while the stream is torn down. producer_exception: Optional[BaseException] = None + updates: asyncio.Queue = asyncio.Queue() + end_of_updates = object() async def send_batches() -> None: nonlocal producer_exception - iterator = batches.__aiter__() - while True: - try: - batch = await iterator.__anext__() - message = MoveThroughJointPositionsStreamedRequest( - batch=MoveThroughJointPositionsStreamedRequest.TrajectoryBatch( - points=[point.to_proto() for point in batch], + try: + async for batch in batches: + await stream.send_message( + MoveThroughJointPositionsStreamedRequest( + batch=MoveThroughJointPositionsStreamedRequest.TrajectoryBatch( + points=[point.to_proto() for point in batch], + ) ) ) - except StopAsyncIteration: - break - except asyncio.CancelledError: - raise - except BaseException as exc: - # Record the caller's producer failure and stop. The main loop surfaces it - # and aborts the stream. We deliberately do not tear the stream down here: - # calling stream.cancel() from this task deadlocks against the concurrent - # receive (confirmed end to end against a real server, not just in tests). - producer_exception = exc - raise - await stream.send_message(message) - # Batches exhausted cleanly; half-close so the arm knows the trajectory completed. - await stream.end() + # Batches exhausted cleanly; half-close so the arm knows the trajectory completed. + await stream.end() + except asyncio.CancelledError: + # Our own teardown cancelling this task, not the caller's failure. + raise + except BaseException as exc: + producer_exception = exc + raise + + async def receive_updates() -> None: + try: + while True: + update = await stream.recv_message() + if update is None: + break + updates.put_nowait(update) + finally: + updates.put_nowait(end_of_updates) send_task = asyncio.create_task(send_batches()) - recv_task = asyncio.ensure_future(stream.recv_message()) - watch_send = True + receive_task = asyncio.create_task(receive_updates()) + + # If the producer fails, stop receiving so the queue terminates and the fault can be + # surfaced. A clean producer finish leaves the receive alone: the arm still has updates + # to send until it closes the response stream itself. + def stop_receiving_if_producer_failed(task: asyncio.Task) -> None: + if not task.cancelled() and task.exception() is not None: + receive_task.cancel() + + send_task.add_done_callback(stop_receiving_if_producer_failed) + try: while True: - wait_set = {recv_task, send_task} if watch_send else {recv_task} - await asyncio.wait(wait_set, return_when=asyncio.FIRST_COMPLETED) - - # Handle the send task finishing before consuming any ready update. A clean - # finish (batches exhausted and half-closed) just means we stop watching it and - # keep receiving until the server closes. A failure means the caller's producer - # broke, so we abort by raising into the handler below. The handler tears down - # the still-pending receive before the `async with` resets the stream, so nothing - # is parked in a read when the reset happens; that is precisely what a direct - # stream.cancel() from the send task cannot manage without deadlocking. - if watch_send and send_task.done(): - watch_send = False - send_error = send_task.exception() - if send_error is not None: - raise send_error + update = await updates.get() + if update is end_of_updates: + break + yield Arm.TrajectoryUpdate.from_proto(update) + finally: + # Before the `async with` resets the stream, make sure both tasks have finished and + # their outcomes have been retrieved, so neither is parked in a read or write during + # the reset. A parked read is exactly what deadlocks a direct stream.cancel(); the + # reset that aborts the arm comes from leaving the `async with` instead. A finished + # task's result is retrieved with `.exception()` rather than by awaiting it, which + # keeps a recorded producer failure's traceback pointed at the caller's code. + for task in (send_task, receive_task): + if task.done(): + if not task.cancelled(): + task.exception() + else: + task.cancel() + try: + await task + except BaseException: + pass - if recv_task.done(): - update = recv_task.result() - if update is None: - # The server closed the response stream: the trajectory is complete. - break - yield Arm.TrajectoryUpdate.from_proto(update) - recv_task = asyncio.ensure_future(stream.recv_message()) - except BaseException: - # The receive side raised (a server fault or cancellation), the producer failed, or - # the caller closed this generator. Cancel both tasks and wait them out so neither is - # left parked in a read or write when the `async with` resets the stream. Prefer the - # caller's producer failure when there is one. - for task in (send_task, recv_task): - task.cancel() - try: - await task - except BaseException: - pass - if producer_exception is not None: - raise producer_exception - raise - else: - # Clean completion: the server closed the response stream after we half-closed. Wait - # on the send task so a producer failure that raced in right at the end still surfaces. - await send_task + # Surface the terminal cause: the caller's producer failure first, then a fault from the + # receive side, otherwise the stream completed cleanly. Raising leaves the `async with`, + # which resets the stream so the arm sees an abort rather than a clean end. + if producer_exception is not None: + raise producer_exception + if not receive_task.cancelled(): + receive_error = receive_task.exception() + if receive_error is not None: + raise receive_error async def stop( self, From 05207bc01e089a059ac3c5dc036cf6d749521aac Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Fri, 17 Jul 2026 12:43:07 -0400 Subject: [PATCH 07/10] [RSDK-14160] Trajectory streaming responses are empty --- src/viam/components/arm/arm.py | 17 +++++++++-------- tests/test_arm.py | 4 ++-- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/viam/components/arm/arm.py b/src/viam/components/arm/arm.py index 98411cc207..a4763ab35f 100644 --- a/src/viam/components/arm/arm.py +++ b/src/viam/components/arm/arm.py @@ -14,7 +14,6 @@ TrajectoryPoint as TrajectoryPointPb, ) from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT -from viam.utils import dict_to_struct, struct_to_dict from . import JointPositions, Pose @@ -117,19 +116,21 @@ class TrajectoryUpdate: """ An update reported by the arm as it executes a ``move_through_joint_positions_streamed`` trajectory. - Today it carries only ``extra``. The type exists as its own message so that - per-batch execution status can be added later without reshaping the streaming API. + The type is intentionally empty. The response is a ``oneof`` whose only branch today is an empty + ``BatchAck``, so receiving a response is itself the acknowledgment. The ``oneof`` exists so the arm's + replies can grow new branches without breaking existing clients on the wire; when a branch carries + data worth surfacing (``BatchAck``'s ``extra``, or a new branch entirely), this type grows to match. """ - extra: Optional[Dict[str, Any]] = None - """Arm-side reply data.""" - def to_proto(self) -> MoveThroughJointPositionsStreamedResponse: - return MoveThroughJointPositionsStreamedResponse(extra=dict_to_struct(self.extra)) + # A received response is itself the acknowledgment, so send the default message and leave the + # oneof unset: the only branch is empty, nothing reads it today, and RDK and the C++ SDK send + # it unset as well. If a future branch carries data, set it here. + return MoveThroughJointPositionsStreamedResponse() @classmethod def from_proto(cls, proto: MoveThroughJointPositionsStreamedResponse) -> "Arm.TrajectoryUpdate": - return cls(extra=struct_to_dict(proto.extra) if proto.HasField("extra") else None) + return cls() @abc.abstractmethod async def get_end_position( diff --git a/tests/test_arm.py b/tests/test_arm.py index caa264982f..96fc43ec92 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -387,5 +387,5 @@ def test_kinematic_constraints_without_accelerations(self): assert restored.constraints.accelerations is None def test_trajectory_update_round_trip(self): - restored = Arm.TrajectoryUpdate.from_proto(Arm.TrajectoryUpdate(extra={"foo": "bar"}).to_proto()) - assert restored.extra == {"foo": "bar"} + restored = Arm.TrajectoryUpdate.from_proto(Arm.TrajectoryUpdate().to_proto()) + assert isinstance(restored, Arm.TrajectoryUpdate) From 950554d8161005f5c381145085921e343e09f7b2 Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Wed, 2 Sep 2026 12:44:22 -0400 Subject: [PATCH 08/10] fix bad merge --- src/viam/components/arm/client.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index 46aafc0f93..b77b80cb80 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -28,7 +28,6 @@ MoveOptions, MoveThroughJointPositionsRequest, MoveToJointPositionsRequest, - MoveThroughJointPositionsRequest, MoveThroughJointPositionsStreamedRequest, MoveToPositionRequest, StopRequest, From 8620a4b130cb5645cb17e6c9fa4f285f07491462 Mon Sep 17 00:00:00 2001 From: Andrew Morrow Date: Wed, 2 Sep 2026 12:50:34 -0400 Subject: [PATCH 09/10] remove test for outdated mtjp impl --- tests/test_arm.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/tests/test_arm.py b/tests/test_arm.py index 6cd334ff38..b95f0c34bf 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -388,13 +388,6 @@ def setup_class(cls): cls.manager = ResourceManager([cls.arm]) cls.service = ArmRPCService(cls.manager) - async def test_move_through_joint_positions(self): - async with ChannelFor([self.service]) as channel: - client = ArmClient(self.name, channel) - positions = [JointPositions(values=[1, 2, 3]), JointPositions(values=[4, 5, 6])] - await client.move_through_joint_positions(positions) - assert self.arm.move_through_positions == positions - async def test_streamed_round_trip(self): async with ChannelFor([self.service]) as channel: client = ArmClient(self.name, channel) From 357fea6ab5bf3f208efdc278c23bb0a98ea53412 Mon Sep 17 00:00:00 2001 From: Naveed Jooma Date: Tue, 15 Sep 2026 14:51:32 -0400 Subject: [PATCH 10/10] Missed a conflict --- tests/test_arm.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/test_arm.py b/tests/test_arm.py index 0bfa8b0a1b..09b3c90284 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -2,11 +2,7 @@ from typing import AsyncIterator, List import pytest -<<<<<<< HEAD from grpclib import GRPCError, Status -======= -from grpclib import GRPCError ->>>>>>> 82b5bcd9a9dce368e46056ee8b9eca335266091f from grpclib.testing import ChannelFor from viam.components.arm import Arm, ArmClient, KinematicsFileFormat