From 9c3d0918e528716afc01a4f4279a943c22b76476 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:24:12 +0800 Subject: [PATCH 01/27] fix(materials): turn non-str keys into JSON keys where PLR data enters materials PyLabRobot 1.0 serializes a Well's height_volume_data as {float: float} (and legacy liquid handler channel state is keyed by int). Those keys reached the registry template sync through config_info, where normalize_json (orjson without OPT_NON_STR_KEYS) stopped the Host at startup with "Dict key must be str"; the local registry snapshot report failed the same way, so authoring reported registry_not_reported. The strict canonical encoder rejects such keys as well. material_serialization, the boundary where a PLR serialize() result becomes material config/data, now turns dict keys into JSON keys ("0.45"). That is the form they already have after any JSON round trip, and PyLabRobot restores them on deserialization (Container does float(h), channels are read back with int()). normalize_json also gets OPT_NON_STR_KEYS, matching its own stdlib json fallback, because registry entries reach it without passing that boundary: config_info cached by an earlier build is reused while the resource module's source hash is unchanged, and registry YAML may use numeric mapping keys. The strict encoder is left unchanged. --- .../registry/test_registry_report_metadata.py | 37 ++++++++++++ .../resources/test_materials_serialization.py | 30 ++++++++++ .../test_registry_material_adapter.py | 59 +++++++++++++++++++ unilabos/resources/plr_identity.py | 27 ++++++++- unilabos/utils/serialization.py | 8 ++- 5 files changed, 158 insertions(+), 3 deletions(-) diff --git a/tests/registry/test_registry_report_metadata.py b/tests/registry/test_registry_report_metadata.py index 76b3bc1f1b..9a74a4ebe2 100644 --- a/tests/registry/test_registry_report_metadata.py +++ b/tests/registry/test_registry_report_metadata.py @@ -143,6 +143,43 @@ def test_device_projection_keeps_available_sites(self, tmp_path) -> None: assert devices[0]["available_sites"] == [{"id": "slot", "name": "slot"}] assert "file_path" not in devices[0] + def test_local_report_accepts_plr_float_keys(self, tmp_path) -> None: + """PyLabRobot 1.0 孔的 ``height_volume_data`` 是 ``{float: float}``:本机注册表上报照常完成。 + + 上报失败只记一条警告(fail-open),但结果是注册表没有上报、工作流作者编译报 + ``registry_not_reported``;键按 JSON 规则转成字符串。 + """ + + from pylabrobot.resources import cor_96_wellplate_360uL_Fb + + from unilabos.client.host.legacy_adaptor.sync.templates import report_registry_snapshot_local + from unilabos.resources.resource_tracker import ResourceTreeSet + + nodes = ResourceTreeSet.from_plr_resources( + [cor_96_wellplate_360uL_Fb(name="corning_plate")], known_random_uuid=True, old_size=True + ).dump_templates()[0] + # 上一版写下的 config_info 缓存(按资源模块源码哈希复用):键还是 PLR 原样的 float + for node in nodes: + volumes = node["config"].get("height_volume_data") + if volumes: + node["config"]["height_volume_data"] = {float(key): value for key, value in volumes.items()} + registry = _Registry({"arm": _device("arm", str(tmp_path / "arm.py"))}) + registry.obtain_registry_resource_info = lambda: [{ + "id": "corning_plate", + "class": {"module": "pylabrobot.resources:cor_96_wellplate_360uL_Fb", "type": "pylabrobot"}, + "config_info": nodes, + }] + service = RegistryService(tmp_path / "runtime.db", machine_id=AUTHORITY_MACHINE) + try: + report = report_registry_snapshot_local(registry, service) + assert report is not None + assert report.resource_count == 1 + payload = service.entry_detail("corning_plate")["active_payload"] + finally: + service.close() + volumes = payload["config_info"][1]["config"]["height_volume_data"] + assert volumes and all(isinstance(key, str) for key in volumes) + def test_package_upgrade_on_a_remote_host_is_accepted_and_an_edit_is_not(self, stack, tmp_path, monkeypatch) -> None: """规则 A 端到端:另一台机器上的 Host 升级驱动包 → 自动接受;同版本里改动 → 挂起。""" diff --git a/tests/resources/test_materials_serialization.py b/tests/resources/test_materials_serialization.py index 8358ab3634..d692df5f82 100644 --- a/tests/resources/test_materials_serialization.py +++ b/tests/resources/test_materials_serialization.py @@ -117,3 +117,33 @@ def test_parse_resource_slot_rejects_invalid(): materials.parse_resource_slot({"foo": "bar"}) with pytest.raises(TypeError): materials.parse_resource_slot(123) + + +def test_plr_float_keys_become_json_keys_at_the_material_boundary(): + """PyLabRobot 1.0 孔的 ``height_volume_data`` 是 ``{float: float}``(PLR 库里的 Corning 96 孔板)。 + + PLR 序列化进入物料 config / data 时键按 JSON 规则转成字符串:两套 JSON 编码器(``normalize_json`` + 的 orjson、拒绝非字符串键的严格编码器 ``encode_json``)都能编码;读回 PLR 后孔的键还原成 float,值不变。 + """ + + from pylabrobot.resources import Cor_96_wellplate_360ul_Fb + + from unilabos.protocol.utils.json_codec import decode_json_bytes, encode_json + from unilabos.utils.serialization import normalize_json + + plate = Cor_96_wellplate_360ul_Fb(name="corning_plate") + original = plate.children[0].height_volume_data + assert original and all(isinstance(key, float) for key in original) + + dumped = ResourceTreeSet.from_plr_resources([plate], known_random_uuid=True).dump() + well = next(node for node in dumped[0] if node["config"].get("height_volume_data")) + assert all(isinstance(key, str) for key in well["config"]["height_volume_data"]) + + via_orjson = normalize_json({"trees": dumped})["trees"] + via_strict = decode_json_bytes(encode_json(dumped, sort_keys=True)) + for payload in (via_orjson, via_strict): + restored = ResourceTreeSet.load(payload).to_plr_resources()[0] + volumes = restored.children[0].height_volume_data + assert all(isinstance(key, float) for key in volumes) + assert volumes == original + assert restored.children[0].compute_volume_from_height(3.3) == plate.children[0].compute_volume_from_height(3.3) diff --git a/tests/resources/test_registry_material_adapter.py b/tests/resources/test_registry_material_adapter.py index e779749776..184c8e754d 100644 --- a/tests/resources/test_registry_material_adapter.py +++ b/tests/resources/test_registry_material_adapter.py @@ -1,10 +1,69 @@ """Registry 生成定义与微后端模板模型的映射测试。""" +from uuid import uuid4 + from unilabos.resources.adapters.registry_materials import register_resource_definitions +from unilabos.resources.resource_tracker import ResourceTreeSet from unilabos.client.materials import LocalMaterialsClient from unilabos.server.services.materials import MaterialsService +def test_plr_definition_with_float_keys_is_registered_and_reads_back(tmp_path) -> None: + """PyLabRobot 1.0 的孔把 ``height_volume_data`` 序列化成 ``{float: float}``(PLR 库里的 Corning 96 孔板)。 + + 物料边界已把键转成字符串,但注册表条目不一定经过那里:上一版写下的 config_info 缓存(按资源模块 + 源码哈希复用)、注册表 YAML 里的数字键。模板同步把定义规范成 JSON 时同样按 JSON 规则转成字符串, + 不能报 "Dict key must be str" 让 Host 起不来;读回的模板交给 PLR 反序列化,孔的 + ``height_volume_data`` 还原成 float 键,按液面高度算出的体积不变。 + """ + + from pylabrobot.resources import cor_96_wellplate_360uL_Fb + + nodes = ResourceTreeSet.from_plr_resources( + [cor_96_wellplate_360uL_Fb(name="corning_plate")], known_random_uuid=True, old_size=True + ).dump_templates()[0] + # 旧缓存里的 config_info:键还是 PLR 原样的 float + for node in nodes: + volumes = node["config"].get("height_volume_data") + if volumes: + node["config"]["height_volume_data"] = {float(key): value for key, value in volumes.items()} + assert all(isinstance(key, float) for key in nodes[1]["config"]["height_volume_data"]) + definition = { + "id": "corning_plate", + "display_name": "Corning 96", + "class": {"module": "pylabrobot.resources:cor_96_wellplate_360uL_Fb", "type": "pylabrobot"}, + "category": ["plate"], + "config_info": nodes, + "handles": [], + } + service = MaterialsService(tmp_path / "materials.db") + client = LocalMaterialsClient(service) + try: + report = register_resource_definitions([definition], client) + stored = client.get_template(report.template_uuids["corning_plate"]).definition["config_info"] + # 再同步一次:同一份定义的哈希稳定,不因键的形态变化而反复更新 + assert register_resource_definitions([definition], client) == report + finally: + service.close() + + assert all(isinstance(key, str) for key in stored[1]["config"]["height_volume_data"]) + uuids = {node["id"]: str(uuid4()) for node in stored} + flat = [ + { + **{key: value for key, value in node.items() if key != "parent_id"}, + "uuid": uuids[node["id"]], + "parent_uuid": uuids[node["parent_id"]] if node["parent_id"] else None, + } + for node in stored + ] + plate = ResourceTreeSet.load([flat]).to_plr_resources()[0] + original = cor_96_wellplate_360uL_Fb(name="reference").children[0] + well = plate.children[0] + assert well.height_volume_data == original.height_volume_data + assert all(isinstance(key, float) for key in well.height_volume_data) + assert well.compute_volume_from_height(3.3) == original.compute_volume_from_height(3.3) + + def test_registry_definition_is_registered_once_with_promoted_fields(tmp_path) -> None: service = MaterialsService(tmp_path / "materials.db") client = LocalMaterialsClient(service) diff --git a/unilabos/resources/plr_identity.py b/unilabos/resources/plr_identity.py index 104d53586d..4298ecb611 100644 --- a/unilabos/resources/plr_identity.py +++ b/unilabos/resources/plr_identity.py @@ -4,6 +4,7 @@ import copy import inspect +import json from typing import Any TIP_CHILDREN = "unilabos_tip_children" @@ -165,12 +166,36 @@ def visit(node): return data try: - return visit(resource), states + return json_object_keys(visit(resource)), json_object_keys(states) finally: for node, counter in counters.values(): node._tip_counter = counter +def json_object_keys(value: Any) -> Any: + """字典键按 JSON 规则转成字符串:PLR 序列化进入物料 config / data 的边界。 + + PyLabRobot 1.0 孔的 ``height_volume_data`` 是 ``{float: float}``,旧式液体处理器的通道状态以 int + 为键。物料 config / data 要能经任何 JSON 编码器(含拒绝非字符串键的严格编码器)编码,入库读回 + 后键本来就是字符串;读回时 PLR 自己还原(``Container`` 构造时 ``float(h)``,通道按 ``int(channel)``)。 + """ + + if isinstance(value, dict): + return { + key if isinstance(key, str) else _json_key(key): json_object_keys(item) + for key, item in value.items() + } + if isinstance(value, list): + return [json_object_keys(item) for item in value] + return value + + +def _json_key(key: Any) -> str: + if key is None or isinstance(key, (bool, int, float)): + return json.dumps(key) + return str(key) + + def restore_tip_counters(resource: Any, states: dict) -> None: """状态恢复可能重建枪头,最后恢复发号计数,防止再次生成已存在名称。""" state = states.get(resource.name, {}) diff --git a/unilabos/utils/serialization.py b/unilabos/utils/serialization.py index 58c6f69533..ab31bb42b8 100644 --- a/unilabos/utils/serialization.py +++ b/unilabos/utils/serialization.py @@ -30,8 +30,12 @@ def default(self, obj): import orjson def normalize_json(info: dict) -> dict: - """经 JSON 序列化/反序列化一轮来清理非标准类型。""" - return orjson.loads(orjson.dumps(info, default=json_default)) + """经 JSON 序列化/反序列化一轮来清理非标准类型。 + + 非字符串键(PyLabRobot 1.0 孔的 ``height_volume_data`` 是 ``{float: float}``)按 JSON 规则 + 转成字符串,与下面标准库 json 的回退实现一致;PLR 反序列化时自己把键还原成 float。 + """ + return orjson.loads(orjson.dumps(info, default=json_default, option=orjson.OPT_NON_STR_KEYS)) except ImportError: From c7788fbf1e5a8601ac152d4c0eb17a994c08493e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:28:52 +0800 Subject: [PATCH 02/27] fix(host): hand drivers a device reference when a ResourceSlot names a device A transfer whose owner is the device itself (an arm whose gripper site hangs on the device) resolved the slot by fetching the device tree from the authority and indexing to_plr_resources()[0]. Devices are not PLR materials and to_plr_resources() skips device trees, so the action failed with IndexError before the driver was called. A slot whose tree root is a device now gives the driver {uuid, id, name, type: "device"}, the same shape as a {uuid} reference, on HostLink and on ROS 2 (reference, flattened tree and batch sync paths). A tree that still yields no PLR material raises a clear error naming the reference instead of IndexError. --- docs/developer_guide/action_standard.md | 2 + .../host/hostlink/test_local_runtime.py | 91 +++++++++++++++++++ .../host/ros2/test_device_node_contract.py | 58 ++++++++++++ .../client/host/runtime/test_resource_slot.py | 37 ++++++++ .../client/host/hostlink/local_runtime.py | 22 ++++- unilabos/client/host/ros2/base_device_node.py | 29 +++++- unilabos/client/host/runtime/resource_slot.py | 40 ++++++++ unilabos/registry/placeholder_type.py | 3 +- 8 files changed, 274 insertions(+), 8 deletions(-) diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 72b0193bc4..7fcce4a3f7 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -31,6 +31,8 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) `{"name": ...}`(派发前由调度器向物料权威解析出 uuid)、上游端口传来的扁平资源树(列表)、uuid 字符串; 能否解析出权威 uuid 由派发前的物料锁检查保证。不可空的物料参数给空值(`{}` / `""` / `[]`)报 「物料参数 … 没有给物料」;可空的物料参数留空等于没给。 +- 物料参数指向设备本身时(例如搬运动作的所属物料是机械臂,夹爪库位挂在设备上),驱动拿到的不是 PLR 实例, + 而是设备引用 `{"uuid", "id", "name", "type": "device"}`:设备子树里只放 PLR 物料,设备本身不是 PLR 物料。 - 物料参数还可以**按库位绑定**:`{"site_uuid": "<库位 uuid>"}`(`list[ResourceSlot]` 的每一项也可以),表示「此刻占着这个 库位的物料」。工作流入口参数、节点静态参数、单点动作参数都可以这样写。建任务与运行预检走同一条解析路径 (`server/services/runtime/workflow/material_sites.py`,物料权威只读事实 `POST /api/v1/inventory/site-admission`): diff --git a/tests/client/host/hostlink/test_local_runtime.py b/tests/client/host/hostlink/test_local_runtime.py index 40bdf1eef3..065b0d4ce7 100644 --- a/tests/client/host/hostlink/test_local_runtime.py +++ b/tests/client/host/hostlink/test_local_runtime.py @@ -604,6 +604,97 @@ def test_hostlink_runtime_resolves_resource_slot_before_driver_call() -> None: runtime.stop() +class TransferDriver: + def __init__(self, device_id=None, config=None): + self.device_id = device_id + + def pick_material(self, material: ResourceSlot, target_owner: ResourceSlot) -> dict: + return {"material": material.name, "target_owner": target_owner} + + +class _AuthorityTrees: + """物料权威的最小替身:按 uuid 返回整棵子树(with_children)。""" + + def __init__(self, tree_set) -> None: + self.trees = {node.res_content.uuid: node for node in tree_set.all_nodes} + + def get_resources_sync(self, uuids, with_children=True): + from unilabos.resources.resource_tracker import ResourceTreeInstance, ResourceTreeSet + + return ResourceTreeSet([ResourceTreeInstance(self.trees[uuid]) for uuid in uuids if uuid in self.trees]) + + def get_resource_by_id_sync(self, resource_id, with_children=True): + raise KeyError(resource_id) + + +ROBOT_UUID = "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f60" +WORKDECK_DEVICE_UUID = "0b9e8d7c-6a5f-4e3d-8c2b-1a0f9e8d7c6b" + + +def _transfer_runtime(): + from unilabos.resources.resource_tracker import ResourceTreeSet + from unilabos.server.services.materials.graph import graph_resource_tree + from tests.plr_fixtures import plate + + def device(device_id: str, uuid: str) -> dict: + return {"id": device_id, "uuid": uuid, "type": "device", "class": "test_device", + "template_name": "test_device", "parent": None, "config": {}} + + deck_nodes = ResourceTreeSet.from_plr_resources([plate("deck_plate")], known_random_uuid=True).dump()[0] + deck_nodes[0]["parent_uuid"] = WORKDECK_DEVICE_UUID + graph = graph_resource_tree([device("robot", ROBOT_UUID), device("workdeck", WORKDECK_DEVICE_UUID), *deck_nodes]) + + runtime = HostLinkLocalRuntime() + runtime.add_driver(HostLinkDriverSpec("robot", TransferDriver, {}, action_names=("pick_material",))) + runtime.start() + node = runtime.devices["robot"] + node.__dict__["_device_resource_service"] = _AuthorityTrees(graph) + from pylabrobot.resources import Resource + + held = Resource("held_plate", size_x=1, size_y=1, size_z=1) + held.unilabos_uuid = "held-plate-uuid" + node.resource_tracker.add_resource(held) + return runtime, graph + + +@pytest.mark.parametrize("owner_uuid, owner_id", [(ROBOT_UUID, "robot"), (WORKDECK_DEVICE_UUID, "workdeck")]) +def test_resource_slot_pointing_at_a_device_gets_a_device_reference(owner_uuid, owner_id) -> None: + """搬运动作的所属物料是设备本身(机械臂夹爪库位挂在设备上;台面设备下挂着 PLR 物料)。 + + 设备不是 PLR 物料,本地快照里没有它,权威取回的是设备树:不能当 PLR 树转换(以前 + ``to_plr_resources()[0]`` 越界,动作在调用驱动前失败),驱动拿到设备引用。 + """ + + runtime, _graph = _transfer_runtime() + try: + result = runtime.call_action( + "robot", "pick_material", material={"uuid": "held-plate-uuid"}, target_owner={"uuid": owner_uuid} + ) + finally: + runtime.stop() + + assert result["material"] == "held_plate" + owner = result["target_owner"] + assert owner["uuid"] == owner_uuid and owner["id"] == owner_id and owner["type"] == "device" + assert isinstance(owner["name"], str) and owner["name"] + + +def test_resource_slot_tree_rooted_at_a_device_gets_a_device_reference() -> None: + """上游端口传来的扁平树以设备为根时同样不走 PLR 转换。""" + + runtime, graph = _transfer_runtime() + robot_tree = next(tree for tree in graph.dump() if tree[0]["uuid"] == ROBOT_UUID) + try: + result = runtime.call_action( + "robot", "pick_material", material={"uuid": "held-plate-uuid"}, target_owner=robot_tree + ) + finally: + runtime.stop() + + assert result["target_owner"]["uuid"] == ROBOT_UUID + assert result["target_owner"]["type"] == "device" + + def test_hostlink_runtime_honors_topic_config_period_and_name() -> None: runtime = _decorated_runtime() received: list[int] = [] diff --git a/tests/client/host/ros2/test_device_node_contract.py b/tests/client/host/ros2/test_device_node_contract.py index 172de44667..f45f4de911 100644 --- a/tests/client/host/ros2/test_device_node_contract.py +++ b/tests/client/host/ros2/test_device_node_contract.py @@ -248,3 +248,61 @@ def create_timer(self, *_args, **_kwargs): "/devices/source/absolute", "/devices/source/split", } + + +def test_ros2_resource_slot_pointing_at_a_device_gets_a_device_reference() -> None: + """与 HostLink 同一规则:设备不是 PLR 物料,ResourceSlot 指向设备时驱动拿到设备引用。""" + + import logging + + from unilabos.resources.resource_tracker import ( + DeviceNodeResourceTracker, + ResourceTreeInstance, + ResourceTreeSet, + ) + from unilabos.server.services.materials.graph import graph_resource_tree + from tests.plr_fixtures import plate + + robot_uuid = "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f64" + plate_nodes = ResourceTreeSet.from_plr_resources([plate("loose_plate")], known_random_uuid=True).dump()[0] + graph = graph_resource_tree([ + {"id": "robot", "uuid": robot_uuid, "type": "device", "class": "test_device", + "template_name": "test_device", "parent": None, "config": {}}, + *plate_nodes, + ]) + nodes = {node.res_content.uuid: node for node in graph.all_nodes} + + class Service: + def get_resources_sync(self, uuids, with_children=True): + return ResourceTreeSet([ResourceTreeInstance(nodes[uuid]) for uuid in uuids]) + + class Node: + _convert_resources_sync = BaseROS2DeviceNode._convert_resources_sync + _assemble_single_resource = BaseROS2DeviceNode._assemble_single_resource + _convert_resource_async = BaseROS2DeviceNode._convert_resource_async + _resolve_slot_value_sync = BaseROS2DeviceNode._resolve_slot_value_sync + resource_tracker = DeviceNodeResourceTracker() + + def _require_resource_service(self): + return Service() + + async def get_resource(self, uuids, with_children=True): + return Service().get_resources_sync(uuids, with_children) + + def lab_logger(self): + return logging.getLogger(__name__) + + node = Node() + expected = {"uuid": robot_uuid, "id": "robot", "type": "device"} + + def subset(value): + return {key: value[key] for key in expected} + + assert subset(node._resolve_slot_value_sync({"uuid": robot_uuid})) == expected + assert subset(asyncio.run(node._convert_resource_async({"uuid": robot_uuid}))) == expected + robot_tree = next(tree for tree in graph.dump() if tree[0]["uuid"] == robot_uuid) + assert subset(node._assemble_single_resource(ResourceTreeSet.load([robot_tree]))) == expected + # 设备与 PLR 物料一起查:顺序与输入一致,PLR 物料照常装配 + device, loose = node._convert_resources_sync(robot_uuid, plate_nodes[0]["uuid"]) + assert subset(device) == expected + assert loose.name == "loose_plate" diff --git a/tests/client/host/runtime/test_resource_slot.py b/tests/client/host/runtime/test_resource_slot.py index e6f0d582f3..0018e717d8 100644 --- a/tests/client/host/runtime/test_resource_slot.py +++ b/tests/client/host/runtime/test_resource_slot.py @@ -93,3 +93,40 @@ def test_hostlink_hands_an_unset_optional_slot_to_the_driver_as_none(empty): assert runtime.call_action("heater", "heat", temp=40.0, vessel=empty) == {"vessel": None, "temp": 40.0} finally: runtime.stop() + + +def _device_node(device_id: str, uuid: str) -> dict: + return {"id": device_id, "uuid": uuid, "type": "device", "class": "test_device", + "template_name": "test_device", "parent": None, "config": {}} + + +def test_device_slot_reference_only_for_a_device_root(): + from unilabos.resources.resource_tracker import ResourceTreeSet + from unilabos.server.services.materials.graph import graph_resource_tree + from unilabos.client.host.runtime.resource_slot import device_slot_reference + from tests.plr_fixtures import plate + + robot = graph_resource_tree([_device_node("robot", "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f61")]) + assert device_slot_reference(robot) == { + "uuid": "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f61", + "id": "robot", + "name": robot.trees[0].root_node.res_content.name, + "type": "device", + } + plates = ResourceTreeSet.from_plr_resources([plate("p")], known_random_uuid=True) + assert device_slot_reference(plates) is None + + +def test_a_slot_tree_without_plr_materials_fails_with_a_clear_error(): + """``to_plr_resources`` 跳过设备树:一个 PLR 物料都转不出时说清是哪个引用,不再 IndexError。""" + + from unilabos.server.services.materials.graph import graph_resource_tree + from unilabos.client.host.runtime.resource_slot import first_plr_resource + + devices = graph_resource_tree([ + _device_node("left", "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f62"), + _device_node("right", "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f63"), + ]) + with pytest.raises(ValueError, match="没有 PLR 物料") as caught: + first_plr_resource(devices, "slot-ref") + assert "slot-ref" in str(caught.value) and "left" in str(caught.value) diff --git a/unilabos/client/host/hostlink/local_runtime.py b/unilabos/client/host/hostlink/local_runtime.py index 49bd831602..e04f117d72 100644 --- a/unilabos/client/host/hostlink/local_runtime.py +++ b/unilabos/client/host/hostlink/local_runtime.py @@ -33,7 +33,11 @@ ) from unilabos.client.host.runtime.node import BackendCapabilityError, DeviceNode from unilabos.client.host.runtime.resource import ResourceService -from unilabos.client.host.runtime.resource_slot import is_unset_resource_slot +from unilabos.client.host.runtime.resource_slot import ( + device_slot_reference, + first_plr_resource, + is_unset_resource_slot, +) from unilabos.client.host.runtime.resource_slot import resource_slot_shape as _resource_slot_shape from unilabos.client.host.hostlink.service import ( DeviceService, @@ -866,7 +870,10 @@ def _map_action_arguments( return mapped def _resolve_resource_slot(self, value: Any) -> Any: - """Resolve one ResourceSlot from this device's authoritative snapshot.""" + """Resolve one ResourceSlot from this device's authoritative snapshot. + + 指向设备本身(设备不是 PLR 物料)时交给驱动设备引用,见 ``device_slot_reference``。 + """ kind, payload = parse_resource_slot(value) @@ -880,7 +887,10 @@ def _resolve_resource_slot(self, value: Any) -> Any: "单个 ResourceSlot 必须恰好包含一棵资源树," f"实际为 {len(tree_set.trees)} 棵" ) - resource = tree_set.to_plr_resources()[0] + device = device_slot_reference(tree_set) + if device is not None: + return device + resource = first_plr_resource(tree_set, tree_set.trees[0].root_node.res_content.uuid) matches = self.resource_tracker.figure_resource(resource, try_mode=True) if len(matches) > 1: raise ValueError(f"ResourceSlot 匹配到多个本地资源:{matches}") @@ -895,7 +905,11 @@ def _resolve_resource_slot(self, value: Any) -> Any: identity = payload.get("uuid") or payload.get("id") or payload.get("name") tree_set = self._fetch_reference_from_authority(payload) if tree_set is not None and len(tree_set.trees): - resource = tree_set.to_plr_resources()[0] + # 设备节点不在本地 PLR 快照里,权威取回的是设备树:设备本身不转 PLR + device = device_slot_reference(tree_set) + if device is not None: + return device + resource = first_plr_resource(tree_set, identity) refigured = self.resource_tracker.figure_resource(resource, try_mode=True) if len(refigured) == 1: return refigured[0] diff --git a/unilabos/client/host/ros2/base_device_node.py b/unilabos/client/host/ros2/base_device_node.py index 3f9fcb6aa7..5e88a998d6 100644 --- a/unilabos/client/host/ros2/base_device_node.py +++ b/unilabos/client/host/ros2/base_device_node.py @@ -32,7 +32,12 @@ from unilabos_msgs.action import StrSingleInput from unilabos.client.host.runtime.node import DeviceNode from unilabos.client.host.runtime.action import bind_action_context -from unilabos.client.host.runtime.resource_slot import is_unset_resource_slot, resource_slot_shapes +from unilabos.client.host.runtime.resource_slot import ( + device_slot_reference, + first_plr_resource, + is_unset_resource_slot, + resource_slot_shapes, +) from unilabos.client.host.runtime.async_utils import schedule_async_func from unilabos.registry.decorators import get_topic_config from unilabos.registry.action_policy import ( @@ -1607,11 +1612,20 @@ def _convert_resources_sync(self, *uuids: str) -> List["ResourcePLR"]: tree_set = self._require_resource_service().get_resources_sync(uuids_list, with_children=True) if not len(tree_set.trees): raise Exception(f"资源查询返回空树: {uuids_list}") + # 设备本身不是 PLR 物料(to_plr_resources 跳过设备树):按 uuid 交给驱动设备引用 + devices: Dict[str, Dict[str, str]] = {} + plr_trees = [] + for tree in tree_set.trees: + reference = device_slot_reference(ResourceTreeSet([tree])) + if reference is None: + plr_trees.append(tree) + else: + devices[reference["uuid"]] = reference plr_resources = tree_set.to_plr_resources() # 通过资源跟踪器获取本地实例 figured_resources: List[ResourcePLR] = [] - for plr_resource, tree in zip(plr_resources, tree_set.trees): + for plr_resource, tree in zip(plr_resources, plr_trees): res = self.resource_tracker.figure_resource(plr_resource, try_mode=True) if len(res) == 0: self.lab_logger().warning(f"资源转换未能索引到实例: {tree.root_node.res_content},返回新建实例") @@ -1623,6 +1637,9 @@ def _convert_resources_sync(self, *uuids: str) -> List["ResourcePLR"]: mapped_plr_resources = [] for uuid in uuids_list: + if uuid in devices: + mapped_plr_resources.append(devices[uuid]) + continue found = None for plr_resource in figured_resources: r = find_resource_by_uuid(plr_resource, uuid) @@ -1645,7 +1662,10 @@ def _assemble_single_resource(self, tree_set: "ResourceTreeSet") -> "ResourcePLR if len(tree_set.trees) != 1: names = [t.root_node.res_content.name for t in tree_set.trees] raise ValueError(f"单物料输入要求恰好一个根物料,实际得到 {len(tree_set.trees)} 个根:{names}") - plr = tree_set.to_plr_resources()[0] + device = device_slot_reference(tree_set) + if device is not None: + return device + plr = first_plr_resource(tree_set, tree_set.trees[0].root_node.res_content.uuid) res = self.resource_tracker.figure_resource(plr, try_mode=True) if len(res) == 1: return res[0] @@ -1779,6 +1799,9 @@ async def _convert_resource_async(self, resource_data: "ResourceDictType"): if unilabos_uuid: resource_tree = await self.get_resource([unilabos_uuid], with_children=True) + device = device_slot_reference(resource_tree) + if device is not None: + return device plr_resources = resource_tree.to_plr_resources() if plr_resources: plr_resource = plr_resources[0] diff --git a/unilabos/client/host/runtime/resource_slot.py b/unilabos/client/host/runtime/resource_slot.py index 3548730760..8f011c8cde 100644 --- a/unilabos/client/host/runtime/resource_slot.py +++ b/unilabos/client/host/runtime/resource_slot.py @@ -67,6 +67,46 @@ def is_unset_resource_slot(value: Any) -> bool: return False +def device_slot_reference(tree_set: Any) -> Optional[dict[str, str]]: + """ResourceSlot 解析到的是设备本身时,返回交给驱动的设备引用;否则返回 ``None``。 + + 设备不是 PLR 物料:设备子树里只放 PLR 物料,设备节点本身不反序列化(``to_plr_resources`` + 跳过设备树),没有 PLR 实例可给。搬运动作把设备当所属物料时(例如机械臂的夹爪库位挂在设备上), + 驱动拿到 ``{"uuid", "id", "name", "type": "device"}``,与 ``{"uuid": ...}`` 引用同形。 + ``tree_set`` 是权威取回或上游传来的单棵 ``ResourceTreeSet``。 + """ + + trees = getattr(tree_set, "trees", None) or [] + if len(trees) != 1: + return None + root = trees[0].root_node.res_content + if str(getattr(root, "type", "") or "") != "device": + return None + return { + "uuid": str(root.uuid or ""), + "id": str(root.id or ""), + "name": str(root.name or root.id or ""), + "type": "device", + } + + +def first_plr_resource(tree_set: Any, identity: Any) -> Any: + """单个 ResourceSlot 的资源树转成 PLR 后的根实例;一个 PLR 物料都转不出时明确报错(而不是越界)。 + + 调用方先用 :func:`device_slot_reference` 处理设备本身;``to_plr_resources`` 只会在树里全是设备时 + 返回空列表,这里兜底说清是哪个引用。 + """ + + resources = tree_set.to_plr_resources() + if not resources: + roots = [ + f"{tree.root_node.res_content.id}(type={tree.root_node.res_content.type})" + for tree in getattr(tree_set, "trees", None) or [] + ] + raise ValueError(f"ResourceSlot {identity!r} 的资源树里没有 PLR 物料:{', '.join(roots) or '空树'}") + return resources[0] + + def resource_slot_shapes(function: Any) -> dict[str, str]: """函数各参数中 ResourceSlot 的形态:``{参数名: "single" | "list"}``。""" diff --git a/unilabos/registry/placeholder_type.py b/unilabos/registry/placeholder_type.py index 6d758dfc23..d97f40c6e0 100644 --- a/unilabos/registry/placeholder_type.py +++ b/unilabos/registry/placeholder_type.py @@ -8,7 +8,8 @@ class ResourceSlot(Resource): 1. 作为 @action 函数参数类型(**暴露给外部调用的契约**):表示「**一个完整的物料**」。 框架已在 send_goal 把原始入参解析为单个 PLR ``Resource`` 实例,函数体内拿到的就是它, - 直接当普通 Resource 用即可,无需关心 list/dict。 + 直接当普通 Resource 用即可,无需关心 list/dict。例外:指向设备本身时(设备不是 PLR 物料), + 拿到的是设备引用 ``{"uuid", "id", "name", "type": "device"}``。 2. 作为原始入参(**仅框架内部解析阶段**):见 ``ResourceSlotRawInput``,可能是 list(一棵树的扁平节点组,handle ``@flatten`` 运行期形态)或 dict(资源引用,前端 schema 填写形态)。 From c88861292b4269c1590158c1d205045c5b6d444a Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:37:00 +0800 Subject: [PATCH 03/27] fix(host): put a device whose startup fails inside the Host into maintenance mode Only a device whose held materials could not be built went into maintenance mode. Any other failure while bringing up a device that runs inside the Host process - its authority state not fitting the registry (e.g. a site missing from available_sites), its driver module failing to import, its constructor raising, or post_init / setup / initialize raising on HostLink - escaped populate_runtime / HostLinkLocalRuntime.start or HostNode.__init__ and stopped the whole Host. DeviceStartupError (stage definition / construct / initialize) now shares the maintenance base and record with DeviceMaterialError: the device and its sub-devices stay down (sub-devices already started are stopped), the reason reaches /api/v1/devices and /api/v1/health, and the Host and the other devices keep running. The ROS 2 HostNode handles definition and construction failures of its local devices the same way. The isolation applies only to the Host process (HostLinkLocalRuntime(isolate_device_failures=True) for the HostLink Host; HostNode.initialize_device for ROS 2). A Slave, including a managed one under --root_devices_as_slaves, still fails and exits so the restart policy of its managed process applies. Graph configuration errors (missing registry entry, invalid template name) still fail the HostLink startup. --- docs/developer_guide/api_v1_migration.md | 2 +- docs/developer_guide/networking_overview.md | 14 +- .../test_device_startup_maintenance.py | 168 ++++++++++++++++++ .../ros2/test_host_node_device_maintenance.py | 104 +++++++++++ .../client/host/hostlink/local_runtime.py | 94 ++++++++-- .../client/host/hostlink/main_hostlink_run.py | 98 +++++++--- .../client/host/ros2/initialize_device.py | 10 +- .../client/host/ros2/presets/host_node.py | 61 +++++-- unilabos/client/host/runtime/exception.py | 46 ++++- 9 files changed, 532 insertions(+), 65 deletions(-) create mode 100644 tests/client/host/hostlink/test_device_startup_maintenance.py create mode 100644 tests/client/host/ros2/test_host_node_device_maintenance.py diff --git a/docs/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index 727533a60a..6cb9a69a94 100644 --- a/docs/developer_guide/api_v1_migration.md +++ b/docs/developer_guide/api_v1_migration.md @@ -57,7 +57,7 @@ `starting`。health 的 `scheduler` 按 V1 为 `ready` / `disabled`,dev 的本机 / 远端归属改名 `scheduler_mode`, `execution` 保留;dev 扩展 `unavailable_devices` 列出设备图里有、但没有启动的设备:当前 backend 跑不了的 (`device_id` / `registry_name` / `backend` / `reason` / `supported_backends`),以及持有的物料建不成 PLR 实例而 - 进入维护模式的(另有 `maintenance: true` / `material_uuid` / `material_type`),分进程时经控制面读 Host。 + 进入维护模式的(另有 `maintenance: true` / `material_uuid` / `material_type`),以及装配 / 构造 / 初始化失败而进入维护模式的(另有 `maintenance: true` / `stage` / `error_type`),分进程时经控制面读 Host。 - V1 进程管理的四个路由(原 V1 Workspace Host 路由:`/v1/snapshot`、`/v1/operations`、`/v1/operations/{id}`、 `/v1/logs/{component}`)路径按 V1 不带 `/api` 前缀,响应是信封:成功 `data` 为快照 / 操作文档 / 日志尾部(提交操作 HTTP 202),失败 HTTP 200 + 业务码,V1 的符号码(`operation_not_found`、`operation_conflict`、`revision_conflict`、 diff --git a/docs/developer_guide/networking_overview.md b/docs/developer_guide/networking_overview.md index d74a20510d..c63eff7dc3 100644 --- a/docs/developer_guide/networking_overview.md +++ b/docs/developer_guide/networking_overview.md @@ -205,9 +205,17 @@ ActionClient、规划场景、RViz、依赖 ROS graph/TF 的功能,以及 ROS2 (`runtime/driver_creator.py:build_device_materials`),建不成就抛 `DeviceMaterialError`,这台设备(连同子设备) 不启动,Host 与其余设备照常运行;记录多出 `maintenance: true`、`material_uuid`、`material_type`,`reason` 写明设备、物料 uuid 与 `config.type`,客户端从 `/api/v1/devices` 的 `unavailable` 字段与 `/api/v1/health` 看到。 -改正物料(或移走它)后重启 Host 即恢复。权威只核对 `config.type` 的格式,类是否存在只有 Host 知道。工作站和 -普通 sub-device 本身不属于这个例外,应通过通用节点接口在 HostLink 与 ROS2 下使用 -相同的设备初始化路径。 +改正物料(或移走它)后重启 Host 即恢复。权威只核对 `config.type` 的格式,类是否存在只有 Host 知道。 + +设备装配、构造或初始化失败同样进入维护模式(`runtime/exception.py:DeviceStartupError`):权威里的设备状态装配不起来 +(例如设备 Site 不在注册表 `available_sites` 里)、驱动模块导入失败、驱动构造器抛错,以及 HostLink 上 +`post_init` / `setup` / `initialize` 抛错。这台设备连同子设备不启动(已经启动的子设备随之停下),Host 与其余设备照常 +运行;记录多出 `maintenance: true`、`stage`(`definition` / `construct` / `initialize`)与 `error_type`,`reason` 写明 +设备与原始错误。ROS 2 Host 对装配与构造失败同样处理;ROS 2 驱动的 `post_init` 抛错仍只记日志、设备照常注册。 +这条只管直接跑在 Host 进程里的设备:Slave 进程(含 `--root_devices_as_slaves` 的受管 Slave)里设备起不来仍让 +Slave 退出,由受管进程的重启策略处理。 +注册表缺失、模板名非法等图配置错误不在此列,仍让 HostLink 启动失败。工作站和普通 sub-device 本身不属于这个例外, +应通过通用节点接口在 HostLink 与 ROS2 下使用相同的设备初始化路径。 HostLink 构造驱动与 ROS2 同一套构造器(`client/host/runtime/driver_creator.py`): diff --git a/tests/client/host/hostlink/test_device_startup_maintenance.py b/tests/client/host/hostlink/test_device_startup_maintenance.py new file mode 100644 index 0000000000..d628e7a5bd --- /dev/null +++ b/tests/client/host/hostlink/test_device_startup_maintenance.py @@ -0,0 +1,168 @@ +"""一台设备装配、构造或初始化失败时只让它进入维护模式:Host 与其余设备照常运行。 + +以前只有「持有的物料建不成 PLR 实例」走维护模式;权威里的设备状态与注册表对不上(例如设备 Site +不在注册表 ``available_sites`` 里)、驱动构造器抛错、``post_init`` / ``setup`` / ``initialize`` 抛错 +都会从 ``populate_runtime`` / ``HostLinkLocalRuntime.start`` 抛出去,整个 Host 以 CRITICAL 退出。 +现在它们与物料建不成同一份不可用记录(``maintenance`` / ``stage`` / ``reason``);子设备没有宿主,一并不启动。 +图配置错误(注册表里没有这个设备)仍让启动失败,见 ``test_backend_unsupported_devices``。 +隔离只在 Host 进程(``isolate_device_failures=True``);Slave 进程失败即退出,交给受管进程的重启策略 +(``--root_devices_as_slaves``,见 ``tests/e2e/test_root_device_slaves.py``)。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +import pytest + +from unilabos.client.host.hostlink.local_runtime import HostLinkLocalRuntime +from unilabos.client.host.hostlink.main_hostlink_run import populate_runtime +from unilabos.client.host.runtime import definition as definition_module +from unilabos.registry.registry import lab_registry +from unilabos.server.services.materials.graph import graph_resource_tree + +MODULE = __name__ + + +class PlainDriver: + def __init__(self, device_id: str = "", **_kwargs) -> None: + self.device_id = device_id + self.cleaned = False + + def cleanup(self) -> None: + self.cleaned = True + + +class BrokenConstructorDriver: + def __init__(self, device_id: str = "", **_kwargs) -> None: + raise RuntimeError("串口打不开") + + +class BrokenInitializeDriver(PlainDriver): + def initialize(self) -> bool: + raise ConnectionError("仪器没有应答") + + +@pytest.fixture +def registry(monkeypatch): + for name, driver in ( + ("test_plain", "PlainDriver"), + ("test_broken_constructor", "BrokenConstructorDriver"), + ("test_broken_initialize", "BrokenInitializeDriver"), + ): + monkeypatch.setitem(lab_registry.device_type_registry, name, { + "class": {"module": f"{MODULE}:{driver}", "type": "python"}}) + # 不接物料权威:只核验本地快照 + monkeypatch.setattr(definition_module, "apply_device_authority_state", lambda *args, **kwargs: None) + + +def _host_runtime() -> HostLinkLocalRuntime: + return HostLinkLocalRuntime(isolate_device_failures=True) + + +def _device(device_id: str, template: str, parent: str | None = None) -> dict: + return {"id": device_id, "uuid": str(uuid4()), "type": "device", "class": template, + "template_name": template, "parent": parent, "config": {}} + + +def test_a_driver_whose_constructor_fails_enters_maintenance(registry) -> None: + devices = graph_resource_tree([ + _device("pump", "test_broken_constructor"), + _device("pump_valve", "test_plain", parent="pump"), + _device("balance", "test_plain"), + ]) + + runtime = populate_runtime(_host_runtime(), devices) + runtime.start() + try: + assert set(runtime.devices) == {"balance"} + record = runtime.unavailable_devices["pump"] + assert record["maintenance"] is True and record["stage"] == "construct" + assert record["error_type"] == "RuntimeError" and "串口打不开" in record["reason"] + assert record["registry_name"] == "test_broken_constructor" and record["backend"] == "hostlink" + assert runtime.unavailable_devices["pump_valve"]["parent_device_id"] == "pump" + finally: + runtime.stop() + + +def test_a_driver_whose_initialize_fails_enters_maintenance(registry) -> None: + devices = graph_resource_tree([ + _device("reader", "test_broken_initialize"), + _device("reader_door", "test_plain", parent="reader"), + _device("balance", "test_plain"), + ]) + runtime = populate_runtime(_host_runtime(), devices) + door = runtime.devices["reader_door"] + + runtime.start() + try: + assert set(runtime.devices) == {"balance"} + assert runtime.devices["balance"]._ready + record = runtime.unavailable_devices["reader"] + assert record["maintenance"] is True and record["stage"] == "initialize" + assert record["error_type"] == "ConnectionError" and "仪器没有应答" in record["reason"] + # 子设备先于父设备启动;父设备起不来,它也停下并登记原因 + assert runtime.unavailable_devices["reader_door"]["parent_device_id"] == "reader" + assert door.driver.cleaned is True and not door._ready + finally: + runtime.stop() + + +def test_authority_state_that_does_not_fit_the_registry_enters_maintenance(registry, monkeypatch) -> None: + """权威里机械臂的 Site 不在注册表 ``available_sites`` 里:只有这台设备起不来。""" + + def apply(device_config, registry_entry, registry_name): + if device_config.res_content.id == "arm": + raise ValueError("物料权威中设备 arm 存在注册表 available_sites 未声明的 Site: ['held_material']") + + monkeypatch.setattr(definition_module, "apply_device_authority_state", apply) + devices = graph_resource_tree([_device("arm", "test_plain"), _device("balance", "test_plain")]) + + runtime = populate_runtime(_host_runtime(), devices) + runtime.start() + try: + assert set(runtime.devices) == {"balance"} + record = runtime.unavailable_devices["arm"] + assert record["maintenance"] is True and record["stage"] == "definition" + assert "held_material" in record["reason"] and record["registry_name"] == "test_plain" + finally: + runtime.stop() + + +def test_the_startup_failure_reaches_the_health_route(registry, monkeypatch) -> None: + from types import SimpleNamespace + + from fastapi.testclient import TestClient + + from unilabos.client.host.hostlink import main_hostlink_run + from unilabos.server.api import edge_proxy + from unilabos.server.api.runtime.diagnostics import create_backend_app + + runtime = populate_runtime(_host_runtime(), graph_resource_tree([ + _device("reader", "test_broken_initialize"), _device("balance", "test_plain")])) + runtime.start() + try: + monkeypatch.setattr(main_hostlink_run, "_runtime", SimpleNamespace(local=runtime)) + edge_proxy.configure_edge_proxy(False) + client = TestClient(create_backend_app(get_scheduler=lambda: object())) + + [record] = client.get("/api/v1/health").json()["data"]["unavailable_devices"] + assert record["device_id"] == "reader" and record["maintenance"] is True + assert record["stage"] == "initialize" + finally: + runtime.stop() + + +def test_a_slave_process_still_fails_so_its_restart_policy_applies(registry) -> None: + """Slave 进程保持失败即退出:构造失败从 populate 抛出,初始化失败从 start 抛出(已启动的设备收尾)。""" + + with pytest.raises(RuntimeError, match="串口打不开"): + populate_runtime(HostLinkLocalRuntime(), graph_resource_tree([_device("pump", "test_broken_constructor")])) + + runtime = populate_runtime(HostLinkLocalRuntime(), graph_resource_tree([ + _device("reader", "test_broken_initialize"), _device("reader_door", "test_plain", parent="reader")])) + door = runtime.devices["reader_door"] + with pytest.raises(ConnectionError, match="仪器没有应答"): + runtime.start() + assert door.driver.cleaned is True + assert runtime.unavailable_devices == {} diff --git a/tests/client/host/ros2/test_host_node_device_maintenance.py b/tests/client/host/ros2/test_host_node_device_maintenance.py new file mode 100644 index 0000000000..b4a94b11ef --- /dev/null +++ b/tests/client/host/ros2/test_host_node_device_maintenance.py @@ -0,0 +1,104 @@ +"""ROS 2 Host:Host 进程里的一台设备装配或构造失败只让它进入维护模式,与 HostLink 同一份不可用记录。 + +以前只有 ``DeviceClassInvalid`` 被接住;驱动构造器抛错、权威里的设备状态装配不起来都会从 +``HostNode.__init__`` 抛出去,Host 退出。自己有 Slave 的设备(``--root_devices_as_slaves``)不经 +``HostNode.initialize_device``,Slave 里的 ``initialize_device_from_dict`` 照旧把异常抛出去,由 Slave +退出与受管进程的重启策略处理。 +""" + +from __future__ import annotations + +import logging +from types import SimpleNamespace + +import pytest + +from unilabos.client.host.ros2 import initialize_device as initialize_module +from unilabos.client.host.ros2.presets.host_node import HostNode +from unilabos.client.host.runtime.exception import DeviceClassInvalid + + +class _Host: + initialize_device = HostNode.initialize_device + + def __init__(self) -> None: + self.registered: list[str] = [] + + def lab_logger(self): + return logging.getLogger(__name__) + + def _register_local_device(self, device_id, _node) -> None: + self.registered.append(device_id) + + +def _config(device_id: str): + return SimpleNamespace(res_content=SimpleNamespace(id=device_id, template_name=f"{device_id}_driver")) + + +def _broken(device_id: str, failure): + def step(*args, **kwargs): + if args[0] == device_id: + if isinstance(failure, BaseException): + raise failure + return failure + return object() + + return step + + +@pytest.mark.parametrize( + "failing_step, outcome, stage, error_type", + [ + ("initialize_device_from_definition", RuntimeError("串口打不开"), "construct", "RuntimeError"), + ("initialize_device_from_definition", None, "construct", "RuntimeError"), # DeviceInitError:实例创建返回空 + ( + "resolve_device_definition", + ValueError("物料权威中设备 pump 存在注册表 available_sites 未声明的 Site: ['held_material']"), + "definition", + "ValueError", + ), + ], +) +def test_a_failing_device_enters_maintenance_and_the_host_keeps_going( + monkeypatch, failing_step, outcome, stage, error_type +) -> None: + monkeypatch.setattr(initialize_module, "resolve_device_definition", lambda *args, **kwargs: object()) + monkeypatch.setattr(initialize_module, "initialize_device_from_definition", lambda *args: object()) + monkeypatch.setattr(initialize_module, failing_step, _broken("pump", outcome)) + host = _Host() + + host.initialize_device("pump", _config("pump")) + host.initialize_device("balance", _config("balance")) + + assert host.registered == ["balance"] + record = host._maintenance_devices["pump"] + assert record["maintenance"] is True and record["backend"] == "ros2" + assert record["stage"] == stage and record["error_type"] == error_type + assert record["registry_name"] == "pump_driver" and "pump" in record["reason"] + + +def test_graph_configuration_errors_are_not_maintenance(monkeypatch) -> None: + def missing(device_id, *_args, **_kwargs): + raise DeviceClassInvalid(f"Device [{device_id}] registry 'ghost' not found.") + + monkeypatch.setattr(initialize_module, "resolve_device_definition", missing) + host = _Host() + + host.initialize_device("ghost", _config("ghost")) + + assert host.registered == [] + assert "ghost" not in getattr(host, "_maintenance_devices", {}) + + +def test_the_slave_path_still_raises(monkeypatch) -> None: + """Slave 进程(含 ``--root_devices_as_slaves``)用 ``initialize_device_from_dict``:构造失败照旧抛出。""" + + monkeypatch.setattr(initialize_module, "resolve_device_definition", lambda *args, **kwargs: object()) + + def boom(*_args): + raise RuntimeError("构造时故意失败") + + monkeypatch.setattr(initialize_module, "initialize_device_from_definition", boom) + + with pytest.raises(RuntimeError, match="构造时故意失败"): + initialize_module.initialize_device_from_dict("fault_boom", _config("fault_boom")) diff --git a/unilabos/client/host/hostlink/local_runtime.py b/unilabos/client/host/hostlink/local_runtime.py index e04f117d72..7dab333628 100644 --- a/unilabos/client/host/hostlink/local_runtime.py +++ b/unilabos/client/host/hostlink/local_runtime.py @@ -24,7 +24,7 @@ from unilabos.client.host.runtime.action import ActionContext, bind_action_context from unilabos.client.host.runtime.test_mode import build_test_mode_return, driver_runs_in_test_mode from unilabos.config.config import BasicConfig -from unilabos.client.host.runtime.exception import TimeoutException +from unilabos.client.host.runtime.exception import DeviceStartupError, TimeoutException from unilabos.client.host.runtime.driver_creator import ( is_workstation_driver, pylabrobot_setup_finished, @@ -1268,14 +1268,18 @@ class HostLinkDriverSpec: class HostLinkLocalRuntime: """管理一个 HostLink backend 进程内的全部本地驱动实例。""" - def __init__(self) -> None: + def __init__(self, *, isolate_device_failures: bool = False) -> None: self.backend_name = "hostlink" + #: Host 进程里为 True:一台设备装配 / 构造 / 初始化失败只让它进入维护模式,Host 与其余设备照常。 + #: Slave 进程保持 False:失败即退出,交给受管进程的重启策略(``--root_devices_as_slaves``)。 + self.isolate_device_failures = bool(isolate_device_failures) self.devices: dict[str, HostLinkDeviceNode] = {} #: 图中声明的 host_node 身份(device_id -> 资源 uuid),供内置 host #: 服务设备注册时复用,保证图导出与权威身份一致。 self.graph_host_resource_uuids: dict[str, str] = {} - #: 设备图中没有启动的设备(device_id -> 原因记录):backend 不支持而跳过的,以及持有的物料 - #: 建不成 PLR 实例而进入维护模式的(记录带 ``maintenance`` / ``material_uuid`` / ``material_type``); + #: 设备图中没有启动的设备(device_id -> 原因记录):backend 不支持而跳过的,持有的物料 + #: 建不成 PLR 实例而进入维护模式的(记录带 ``maintenance`` / ``material_uuid`` / ``material_type``), + #: 以及装配 / 构造 / 初始化失败而进入维护模式的(记录带 ``maintenance`` / ``stage`` / ``error_type``); #: 由能力快照、``/api/v1/hostlink/peers`` 与 ``/api/v1/health`` 上报。 self.unavailable_devices: dict[str, dict[str, Any]] = {} self.topic_bus = LocalTopicBus() @@ -1644,20 +1648,84 @@ async def route_action_async( return await operation return await asyncio.wait_for(operation, float(timeout)) + def mark_unavailable( + self, + device_id: str, + *, + registry_name: str, + reason: str, + supported_backends: Optional[list[str]] = None, + parent_device_id: str = "", + extra: Optional[dict[str, Any]] = None, + ) -> None: + """登记一台没有启动的设备(backend 不支持、维护模式、父设备不可用)并写 ERROR 日志。""" + + record: dict[str, Any] = { + "device_id": device_id, + "registry_name": registry_name, + "backend": self.backend_name, + "reason": reason, + **(extra or {}), + } + if supported_backends is not None: + record["supported_backends"] = list(supported_backends) + if parent_device_id: + record["parent_device_id"] = parent_device_id + self.unavailable_devices[device_id] = record + logging.getLogger(__name__).error( + "[HostLink] 设备 %s(%s)不可用,未启动:%s;其余设备照常启动", + device_id, + registry_name or "-", + reason, + ) + + def _enter_maintenance(self, node: HostLinkDeviceNode, error: Exception) -> None: + """启动失败的设备进入维护模式:移出运行时(连同已启动的子设备),登记不可用原因。""" + + failure = DeviceStartupError(stage="initialize", error=error, device_id=node.device_id) + descendants: list[HostLinkDeviceNode] = [] + pending = list(node.sub_devices.values()) + while pending: + child = pending.pop(0) + descendants.append(child) + pending.extend(child.sub_devices.values()) + self.remove_device(node.device_id) + record = failure.unavailable_record() + self.mark_unavailable( + node.device_id, + registry_name=node.registry_name, + reason=record.pop("reason"), + parent_device_id=node.parent_device_id, + extra=record, + ) + for child in descendants: + self.mark_unavailable( + child.device_id, + registry_name=child.registry_name, + reason=f"父设备 {child.parent_device_id!r} 在 backend hostlink 上不可用,子设备一并停止", + parent_device_id=child.parent_device_id, + ) + def start(self) -> None: self._stopped.clear() started: list[HostLinkDeviceNode] = [] - try: - # 设备图按父节点优先加入;反向启动可保证 Workstation post_init - # 运行前,其 sub-device 的 action/service/status 已全部就绪。 - for node in reversed(tuple(self.devices.values())): + # 设备图按父节点优先加入;反向启动可保证 Workstation post_init + # 运行前,其 sub-device 的 action/service/status 已全部就绪。 + for node in reversed(tuple(self.devices.values())): + if self.devices.get(node.device_id) is not node: + continue + try: node.start() started.append(node) - self._started = True - except Exception: - for node in reversed(started): - node.stop() - raise + except Exception as exc: + if not self.isolate_device_failures: + for running in reversed(started): + running.stop() + raise + # Host 进程:一台设备初始化失败只让它进入维护模式 + logging.getLogger(__name__).exception("HostLink 设备初始化失败:%s", node.device_id) + self._enter_maintenance(node, exc) + self._started = True def call_action( self, diff --git a/unilabos/client/host/hostlink/main_hostlink_run.py b/unilabos/client/host/hostlink/main_hostlink_run.py index 74f6802713..5ae2b6ce72 100644 --- a/unilabos/client/host/hostlink/main_hostlink_run.py +++ b/unilabos/client/host/hostlink/main_hostlink_run.py @@ -10,7 +10,12 @@ iter_device_config_entries, resolve_device_definition, ) -from unilabos.client.host.runtime.exception import DeviceBackendUnsupported, DeviceMaterialError +from unilabos.client.host.runtime.exception import ( + DeviceBackendUnsupported, + DeviceClassInvalid, + DeviceMaintenanceError, + DeviceStartupError, +) from unilabos.client.host.hostlink.backend import HostLinkBackend from unilabos.client.host.hostlink.local_runtime import ( HostLinkDriverSpec, @@ -44,6 +49,9 @@ def populate_runtime( 每台设备经 ``resolve_device_definition`` 装配:物料权威可达时按权威优先取回 Site 快照与持有的物料,所以 Slave 要在 HostLink 连上之后再调用。 + + 持有的物料建不成时这台设备进入维护模式;``runtime.isolate_device_failures``(Host 进程) + 时装配 / 构造失败同样只让这台设备进入维护模式,否则(Slave 进程)照旧抛出。 """ if devices_config is None: @@ -99,6 +107,23 @@ def populate_runtime( parent_device_id=entry.parent_device_id, ) continue + except DeviceMaintenanceError as exc: + _enter_maintenance(runtime, entry, exc, registry_name=str(node.res_content.template_name or "")) + continue + except DeviceClassInvalid: + # 图配置错误(模板名非法、注册表里没有这个设备)照旧让启动失败 + raise + except Exception as exc: + if not runtime.isolate_device_failures: + raise + # Host 进程:权威状态装配不起来、驱动导入失败,只让这台设备进入维护模式 + _enter_maintenance( + runtime, + entry, + DeviceStartupError(stage="definition", error=exc), + registry_name=str(node.res_content.template_name or ""), + ) + continue try: runtime.add_driver( HostLinkDriverSpec( @@ -116,21 +141,49 @@ def populate_runtime( hardware_interface=definition.hardware_interface, ) ) - except DeviceMaterialError as exc: + except DeviceMaintenanceError as exc: # 维护模式:持有的物料建不成 PLR 实例,这台设备不启动(子设备随之跳过),其余照常 - exc.device_id = device_id - record = exc.unavailable_record() - _mark_unavailable( + _enter_maintenance(runtime, entry, exc, registry_name=definition.registry_name) + except Exception as exc: + if not runtime.isolate_device_failures: + raise + # Host 进程:驱动构造失败只让这台设备进入维护模式 + _enter_maintenance( runtime, - device_id, + entry, + DeviceStartupError(stage="construct", error=exc), registry_name=definition.registry_name, - reason=record.pop("reason"), - parent_device_id=entry.parent_device_id, - extra=record, ) return runtime +def _enter_maintenance( + runtime: HostLinkLocalRuntime, + entry: Any, + error: DeviceMaintenanceError, + *, + registry_name: str, +) -> None: + """这台设备不启动(子设备随之跳过),原因登记为不可用设备;Host 与其余设备照常。""" + + cause = error.__cause__ or error + logger.error( + "[HostLink] 设备 %s 启动失败的原始异常", + entry.device_id, + exc_info=(type(cause), cause, cause.__traceback__), + ) + error.device_id = entry.device_id + record = error.unavailable_record() + _mark_unavailable( + runtime, + entry.device_id, + registry_name=registry_name, + reason=record.pop("reason"), + parent_device_id=entry.parent_device_id, + extra=record, + ) + + def _mark_unavailable( runtime: HostLinkLocalRuntime, device_id: str, @@ -141,28 +194,18 @@ def _mark_unavailable( parent_device_id: str = "", extra: Optional[dict[str, Any]] = None, ) -> None: - record: dict[str, Any] = { - "device_id": device_id, - "registry_name": registry_name, - "backend": "hostlink", - "reason": reason, - **(extra or {}), - } - if supported_backends is not None: - record["supported_backends"] = list(supported_backends) - if parent_device_id: - record["parent_device_id"] = parent_device_id - runtime.unavailable_devices[device_id] = record - logger.error( - "[HostLink] 设备 %s(%s)不可用,未启动:%s;其余设备照常启动", + runtime.mark_unavailable( device_id, - registry_name or "-", - reason, + registry_name=registry_name, + reason=reason, + supported_backends=supported_backends, + parent_device_id=parent_device_id, + extra=extra, ) def unavailable_devices() -> list[dict[str, Any]]: - """本进程 HostLink runtime 没有启动的设备(backend 不支持、物料建不成时的维护模式;供诊断 / 健康接口)。""" + """本进程 HostLink runtime 没有启动的设备(backend 不支持、维护模式;供诊断 / 健康接口)。""" runtime = _runtime local = getattr(runtime, "local", None) @@ -220,7 +263,8 @@ def _run( bridges: Optional[list[Any]] = None, ) -> None: global _host_node, _runtime - runtime = HostLinkBackend(HostLinkLocalRuntime(), is_slave=is_slave) + # 设备失败的隔离只在 Host 进程:Slave 失败即退出,由受管进程按重启策略处理 + runtime = HostLinkBackend(HostLinkLocalRuntime(isolate_device_failures=not is_slave), is_slave=is_slave) _runtime = runtime try: runtime.start( diff --git a/unilabos/client/host/ros2/initialize_device.py b/unilabos/client/host/ros2/initialize_device.py index f452f568ce..5f0fcfb549 100644 --- a/unilabos/client/host/ros2/initialize_device.py +++ b/unilabos/client/host/ros2/initialize_device.py @@ -1,6 +1,6 @@ from typing import Optional -from unilabos.client.host.runtime.definition import resolve_device_definition +from unilabos.client.host.runtime.definition import DeviceDefinition, resolve_device_definition from unilabos.registry.registry import lab_registry # noqa: F401 - 兼容嵌入方/测试 from unilabos.client.host.ros2.device_node_wrapper import ros2_device_node from unilabos.client.host.ros2.base_device_node import ROS2DeviceNode, DeviceInitError @@ -27,6 +27,14 @@ def initialize_device_from_dict(device_id, device_config: ResourceDictInstance) device_config, backend_name="ros2", ) + return initialize_device_from_definition(device_id, device_config, definition) + + +def initialize_device_from_definition( + device_id, device_config: ResourceDictInstance, definition: DeviceDefinition +) -> Optional[ROS2DeviceNode]: + """按已解析的设备定义构造设备节点(Host 据此分清装配失败与构造失败)。""" + # 不管是 ROS2 驱动还是 Python 驱动,都统一包装为设备节点(HostNode 除外)。 device_node_type = ros2_device_node( definition.driver_class, diff --git a/unilabos/client/host/ros2/presets/host_node.py b/unilabos/client/host/ros2/presets/host_node.py index 60e0566f70..bccf783f57 100644 --- a/unilabos/client/host/ros2/presets/host_node.py +++ b/unilabos/client/host/ros2/presets/host_node.py @@ -44,7 +44,7 @@ ) from unilabos.client.host.ros2.presets.controller_node import ControllerNode from unilabos.client.host.runtime.definition import is_host_node_config -from unilabos.client.host.runtime.exception import DeviceClassInvalid, DeviceMaterialError +from unilabos.client.host.runtime.exception import DeviceClassInvalid, DeviceMaintenanceError, DeviceStartupError from unilabos.client.host.runtime.host_adapter import ( HostAdapterBase, execution_result_bridges, @@ -509,7 +509,7 @@ def unavailable_devices(self) -> Dict[str, Dict[str, Any]]: from unilabos.server.services.device_processes import managed_device_unavailability records = managed_device_unavailability() - # 持有的物料建不成 PLR 实例、进入维护模式的本机设备 + # 进入维护模式的本机设备(持有的物料建不成 PLR 实例、装配 / 构造失败) records.update(self.__dict__.get("_maintenance_devices") or {}) return records @@ -680,24 +680,51 @@ def _create_action_clients_for_device(self, device_id: str, namespace: str) -> N def initialize_device(self, device_id: str, device_config: ResourceDictInstance) -> None: """根据配置初始化本机设备(经 ROS2 通用管线),并创建动作客户端。""" - from unilabos.client.host.ros2.initialize_device import initialize_device_from_dict + from unilabos.client.host.ros2 import initialize_device as initializer self.lab_logger().info(f"[Host Node] Initializing device: {device_id}") - try: - d = initialize_device_from_dict(device_id, device_config) - except DeviceClassInvalid as e: - if isinstance(e, DeviceMaterialError): - # 维护模式:持有的物料建不成 PLR 实例,设备不启动;与 HostLink 同一份不可用记录 - e.device_id = device_id - self.__dict__.setdefault("_maintenance_devices", {})[device_id] = { - "device_id": device_id, - "registry_name": str(device_config.res_content.template_name or ""), - "backend": "ros2", - **e.unavailable_record(), - } - self.lab_logger().error(f"[Host Node] Device class invalid: {e}") - d = None + # Host 进程里的设备:装配 / 构造失败只让这台设备进入维护模式,Host 与其余设备照常。 + # 自己有 Slave 的设备(--root_devices_as_slaves)不经这里,失败照旧由 Slave 退出与重启策略处理。 + maintenance: Optional[DeviceMaintenanceError] = None + failed = object() + + def attempt(stage: str, step: Any) -> Any: + nonlocal maintenance + try: + return step() + except DeviceMaintenanceError as e: + maintenance = e + except DeviceClassInvalid as e: + self.lab_logger().error(f"[Host Node] Device class invalid: {e}") + except Exception as e: # noqa: BLE001 - 见上 + self.lab_logger().error(f"[Host Node] 设备 {device_id} 启动失败: {e}\n{traceback.format_exc()}") + maintenance = DeviceStartupError(stage=stage, error=e) + return failed + + d = None + definition = attempt( + "definition", lambda: initializer.resolve_device_definition(device_id, device_config, backend_name="ros2") + ) + if definition is not failed: + d = attempt( + "construct", lambda: initializer.initialize_device_from_definition(device_id, device_config, definition) + ) + if d is failed: + d = None + elif d is None: + # 驱动实例创建返回空(DeviceInitError) + maintenance = DeviceStartupError(stage="construct", error=RuntimeError("设备实例创建失败")) + if maintenance is not None: + # 维护模式:设备不启动;与 HostLink 同一份不可用记录 + maintenance.device_id = device_id + self.__dict__.setdefault("_maintenance_devices", {})[device_id] = { + "device_id": device_id, + "registry_name": str(device_config.res_content.template_name or ""), + "backend": "ros2", + **maintenance.unavailable_record(), + } + self.lab_logger().error(f"[Host Node] {maintenance}") if d is None: return self._register_local_device(device_id, d) diff --git a/unilabos/client/host/runtime/exception.py b/unilabos/client/host/runtime/exception.py index d74b93cf95..73082089bf 100644 --- a/unilabos/client/host/runtime/exception.py +++ b/unilabos/client/host/runtime/exception.py @@ -32,7 +32,48 @@ def __init__( ) -class DeviceMaterialError(DeviceClassInvalid): +class DeviceMaintenanceError(DeviceClassInvalid): + """这台设备起不来、进入维护模式:设备不启动(子设备随之跳过),Host 照常运行、其余设备照常启动。 + + 原因经 :meth:`unavailable_record` 登记为不可用设备,HostLink 与 ROS 2 同一份记录,经能力快照到达 + ``GET /api/v1/devices``,并出现在 ``/api/v1/health`` 里。注册表缺失、模板名非法等图配置错误不属于 + 这一类,仍是 :class:`DeviceClassInvalid`。 + """ + + device_id: str = "" + + def unavailable_record(self) -> Dict[str, Any]: + return {"maintenance": True, "reason": str(self)} + + +class DeviceStartupError(DeviceMaintenanceError): + """设备装配、构造或初始化失败:权威里的设备状态装配不起来(如 Site 与注册表对不上)、驱动导入失败、 + 构造器或 ``post_init`` / ``setup`` / ``initialize`` 抛错。``stage`` 是 ``definition`` / ``construct`` / + ``initialize`` 之一。 + """ + + STAGES = {"definition": "装配", "construct": "构造", "initialize": "初始化"} + + def __init__(self, *, stage: str, error: BaseException, device_id: str = "") -> None: + if stage not in self.STAGES: + raise ValueError(f"未知的设备启动阶段: {stage!r}") + self.stage = stage + self.error_type = type(error).__name__ + self.detail = str(error) + self.device_id = str(device_id or "") + super().__init__(self.detail) + # 原始异常(带 traceback)留给日志 + self.__cause__ = error + + def __str__(self) -> str: + device = f"设备 {self.device_id} " if self.device_id else "设备" + return f"{device}{self.STAGES[self.stage]}失败,设备进入维护模式:{self.error_type}: {self.detail}" + + def unavailable_record(self) -> Dict[str, Any]: + return {**super().unavailable_record(), "stage": self.stage, "error_type": self.error_type} + + +class DeviceMaterialError(DeviceMaintenanceError): """设备持有的物料建不成 PLR 实例(缺 / 写错 ``config.type``、类不存在、反序列化失败)。 设备进入维护模式:这台设备不启动,Host 照常运行、其余设备照常启动;原因(设备、物料 uuid、 @@ -58,8 +99,7 @@ def unavailable_record(self) -> Dict[str, Any]: """不可用设备记录里的维护模式字段(与 backend 不支持等原因同一份记录)。""" return { - "maintenance": True, - "reason": str(self), + **super().unavailable_record(), "material_uuid": self.material_uuid, "material_type": ( self.material_type From cba165dc73d702c083aa9ed93e92baf90b576578 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:41:44 +0800 Subject: [PATCH 04/27] fix(materials): stop inferring site occupancy from equal coordinates Graph reconciliation marked a site occupied whenever a child of the site's owner sat at the same coordinates. A device's gripper site is often a zero placeholder at the device origin, so a deck or store carrier mounted at that origin was recorded as held by the gripper and transfers through that gripper waited on gripper_site_occupied forever; the same happened to any plain child that happened to share a site's coordinates. Site occupancy now comes only from an explicit occupied_material_uuid (legacy occupied_by is still converted at the legacy read boundary) and from the PLR structure itself (occupants under carrier holders, sites serialized from native PLR sites). --- tests/server/test_graph_carrier_holders.py | 56 +++++++++++++++++++++ unilabos/server/services/materials/graph.py | 38 ++------------ 2 files changed, 60 insertions(+), 34 deletions(-) diff --git a/tests/server/test_graph_carrier_holders.py b/tests/server/test_graph_carrier_holders.py index f791cb0de9..ea3bb9c2c1 100644 --- a/tests/server/test_graph_carrier_holders.py +++ b/tests/server/test_graph_carrier_holders.py @@ -50,3 +50,59 @@ def test_carrier_graph_with_holders_restores_on_the_host() -> None: assert restored["A01"].resource.unilabos_uuid == bottle_uuid assert restored["A02"].resource is None assert restored["A03"].resource is None + + +def _device_with_gripper_and_deck(*, occupied: str | None = None) -> tuple[list[dict], str, str]: + """设备的夹爪 Site 是原点占位,台面载架挂在设备原点:坐标相同,台面并不在夹爪上。""" + + device_uuid, deck_uuid = str(uuid4()), str(uuid4()) + origin = {"x": 0.0, "y": 0.0, "z": 0.0} + device = { + "id": "liquid_handler", "uuid": device_uuid, "type": "device", "class": "test_liquid_handler", + "template_name": "test_liquid_handler", "parent": None, "config": {}, "pose": {"position": origin}, + "sites": [ + {"label": "transfer_gripper", "index": "transfer_gripper", "pose": {"position": origin}, + "meta_data": {"role": "handler.transfer_gripper"}, "occupied_material_uuid": occupied}, + {"label": "waste_position", "index": "waste_position", "pose": {"position": {"x": 300.0, "y": 0.0, "z": 0.0}}, + "occupied_material_uuid": None}, + ], + } + deck = { + "id": "workdeck", "uuid": deck_uuid, "type": "deck", "class": "test_deck", "template_name": "test_deck", + "parent_uuid": device_uuid, "config": {"type": "Deck"}, "pose": {"position": origin}, + } + waste = { + "id": "waste_plate", "uuid": str(uuid4()), "type": "plate", "class": "test_plate", "template_name": "test_plate", + "parent_uuid": device_uuid, "config": {"type": "Plate"}, "pose": {"position": {"x": 300.0, "y": 0.0, "z": 0.0}}, + } + return [device, deck, waste], device_uuid, deck_uuid + + +def test_equal_coordinates_do_not_make_a_child_occupy_a_site() -> None: + """占用只认显式声明与 PLR 结构:台面在设备原点不等于它在原点的夹爪 Site 上(以前搬运一直等 + ``gripper_site_occupied``),子物料坐标等于普通 Site 也不代表占用。""" + + nodes, device_uuid, _deck_uuid = _device_with_gripper_and_deck() + + normalized, _ = reconcile_graph_payload({"nodes": nodes, "links": []}, None, str(uuid4())) + + device = next(node for node in normalized["nodes"] if node["uuid"] == device_uuid) + assert {site["label"]: site["occupied_material_uuid"] for site in device["sites"]} == { + "transfer_gripper": None, + "waste_position": None, + } + + +def test_explicit_site_occupancy_is_kept() -> None: + plate_uuid = str(uuid4()) + nodes, device_uuid, _deck_uuid = _device_with_gripper_and_deck(occupied=plate_uuid) + nodes.append({ + "id": "held_plate", "uuid": plate_uuid, "type": "plate", "class": "test_plate", "template_name": "test_plate", + "parent_uuid": device_uuid, "config": {"type": "Plate"}, "pose": {"position": {"x": 0.0, "y": 0.0, "z": 0.0}}, + }) + + normalized, _ = reconcile_graph_payload({"nodes": nodes, "links": []}, None, str(uuid4())) + + device = next(node for node in normalized["nodes"] if node["uuid"] == device_uuid) + assert device["sites"][0]["occupied_material_uuid"] == plate_uuid + assert device["sites"][1]["occupied_material_uuid"] is None diff --git a/unilabos/server/services/materials/graph.py b/unilabos/server/services/materials/graph.py index 647abaeb5d..af8017294f 100644 --- a/unilabos/server/services/materials/graph.py +++ b/unilabos/server/services/materials/graph.py @@ -407,40 +407,10 @@ def previous_for(node: Mapping[str, Any]) -> Optional[Mapping[str, Any]]: [(str(child["uuid"]), child.get("type"), child["config"]) for child in children], ) - # ── 占用关系对账:子物料按 parent + 位置匹配写入 Site 占用。── - # 权威快照必须自带占用(树重建/deserialize 时 child 尚未注入 uuid, - # 依赖 Site 的 expected_occupant 回填),创建入口是唯一发号边界。 - for node in nodes: - sites = node.get("sites") - if not isinstance(sites, list) or not sites: - continue - node_id = _node_id(node) - node_uuid = str(node["uuid"]) - for child in nodes: - child_parent_uuid = str(child.get("parent_uuid") or "") - if child_parent_uuid: - if child_parent_uuid != node_uuid: - continue - elif str(child.get("parent") or "") != node_id: - continue - if str(child.get("type") or "") == "resource_holder": - # 载架的槽位 holder 是 Site 本身的结构节点,按构造就在 Site 的位置上; - # 占用物料挂在 holder 下,holder 自己不占用 Site。 - continue - child_position = ((child.get("pose") or {}).get("position")) or {} - child_key = tuple( - float(child_position.get(axis, 0.0) or 0.0) for axis in ("x", "y", "z") - ) - for site in sites: - if site.get("occupied_material_uuid"): - continue - site_position = ((site.get("pose") or {}).get("position")) or {} - site_key = tuple( - float(site_position.get(axis, 0.0) or 0.0) for axis in ("x", "y", "z") - ) - if site_key == child_key: - site["occupied_material_uuid"] = child["uuid"] - break + # ── 占用关系只认显式声明:Site 的 occupied_material_uuid(旧图的 occupied_by 在 legacy + # 读图边界换成 uuid),以及 PLR 结构本身(载架槽位 holder 下的子物料、PLR 序列化时由 + # 原生 Site 写出的占用)。子物料坐标恰好等于某个 Site 坐标不代表它占着这个 Site: + # 设备的夹爪 Site 常是原点占位,挂在设备原点的台面 / 堆栈库会被当成夹爪上的物料。── # ── diff 分类(发号与占用全部就绪后计算)── matched_previous_uuids: set[str] = set() From 9f4eaa92fef35a363dc54110f1820cf94dd201de Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:16:06 +0800 Subject: [PATCH 05/27] fix(host): reject a ResourceSlot that resolves to a device A ResourceSlot only names a material. Handing a driver a device reference dict when a ResourceSlot resolved to a device (previous commit) made the parameter polymorphic; HostLink and ROS 2 now raise before the driver is called, naming the parameter and the device and pointing to DeviceSlot (whose value, the device id, reaches the driver unchanged). The clear error for a tree that yields no PLR material stays. --- docs/developer_guide/action_standard.md | 4 +- .../host/hostlink/test_local_runtime.py | 56 +++++++++++++------ .../host/ros2/test_device_node_contract.py | 29 +++++----- .../client/host/runtime/test_resource_slot.py | 34 +++++------ .../client/host/hostlink/local_runtime.py | 23 +++----- unilabos/client/host/ros2/base_device_node.py | 33 +++-------- unilabos/client/host/runtime/resource_slot.py | 44 +++++++-------- unilabos/registry/placeholder_type.py | 4 +- 8 files changed, 113 insertions(+), 114 deletions(-) diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 7fcce4a3f7..ed1a3dcbe2 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -31,8 +31,8 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) `{"name": ...}`(派发前由调度器向物料权威解析出 uuid)、上游端口传来的扁平资源树(列表)、uuid 字符串; 能否解析出权威 uuid 由派发前的物料锁检查保证。不可空的物料参数给空值(`{}` / `""` / `[]`)报 「物料参数 … 没有给物料」;可空的物料参数留空等于没给。 -- 物料参数指向设备本身时(例如搬运动作的所属物料是机械臂,夹爪库位挂在设备上),驱动拿到的不是 PLR 实例, - 而是设备引用 `{"uuid", "id", "name", "type": "device"}`:设备子树里只放 PLR 物料,设备本身不是 PLR 物料。 +- `ResourceSlot` 只指物料。设备不是物料:给物料参数传设备(或它解析到设备)时 Host 在调用驱动前报错,指出参数与设备。 + 参数要的是设备时注解为 `DeviceSlot`(值是设备 id,原样交给驱动,不做物料转换)。 - 物料参数还可以**按库位绑定**:`{"site_uuid": "<库位 uuid>"}`(`list[ResourceSlot]` 的每一项也可以),表示「此刻占着这个 库位的物料」。工作流入口参数、节点静态参数、单点动作参数都可以这样写。建任务与运行预检走同一条解析路径 (`server/services/runtime/workflow/material_sites.py`,物料权威只读事实 `POST /api/v1/inventory/site-admission`): diff --git a/tests/client/host/hostlink/test_local_runtime.py b/tests/client/host/hostlink/test_local_runtime.py index 065b0d4ce7..023017e8be 100644 --- a/tests/client/host/hostlink/test_local_runtime.py +++ b/tests/client/host/hostlink/test_local_runtime.py @@ -17,7 +17,7 @@ from unilabos.client.host.runtime import BackendCapabilityError from unilabos.client.host.runtime.action import ActionContext from unilabos.registry.decorators import topic_config -from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot from unilabos.resources.resource_tracker import DeviceNodeResourceTracker @@ -611,6 +611,9 @@ def __init__(self, device_id=None, config=None): def pick_material(self, material: ResourceSlot, target_owner: ResourceSlot) -> dict: return {"material": material.name, "target_owner": target_owner} + def pick_into_gripper(self, material: ResourceSlot, target_owner: DeviceSlot) -> dict: + return {"material": material.name, "target_owner": target_owner} + class _AuthorityTrees: """物料权威的最小替身:按 uuid 返回整棵子树(with_children)。""" @@ -645,7 +648,9 @@ def device(device_id: str, uuid: str) -> dict: graph = graph_resource_tree([device("robot", ROBOT_UUID), device("workdeck", WORKDECK_DEVICE_UUID), *deck_nodes]) runtime = HostLinkLocalRuntime() - runtime.add_driver(HostLinkDriverSpec("robot", TransferDriver, {}, action_names=("pick_material",))) + runtime.add_driver( + HostLinkDriverSpec("robot", TransferDriver, {}, action_names=("pick_material", "pick_into_gripper")) + ) runtime.start() node = runtime.devices["robot"] node.__dict__["_device_resource_service"] = _AuthorityTrees(graph) @@ -658,41 +663,56 @@ def device(device_id: str, uuid: str) -> dict: @pytest.mark.parametrize("owner_uuid, owner_id", [(ROBOT_UUID, "robot"), (WORKDECK_DEVICE_UUID, "workdeck")]) -def test_resource_slot_pointing_at_a_device_gets_a_device_reference(owner_uuid, owner_id) -> None: - """搬运动作的所属物料是设备本身(机械臂夹爪库位挂在设备上;台面设备下挂着 PLR 物料)。 +def test_resource_slot_pointing_at_a_device_is_rejected_before_the_driver(owner_uuid, owner_id) -> None: + """ResourceSlot 只指物料:传进来的是设备(机械臂本身;台面设备下挂着 PLR 物料也一样)时明确报错。 - 设备不是 PLR 物料,本地快照里没有它,权威取回的是设备树:不能当 PLR 树转换(以前 - ``to_plr_resources()[0]`` 越界,动作在调用驱动前失败),驱动拿到设备引用。 + 以前权威取回设备树后 ``to_plr_resources()[0]`` 越界,报 "list index out of range";现在指出参数与设备, + 并说明设备参数用 DeviceSlot。 """ runtime, _graph = _transfer_runtime() try: - result = runtime.call_action( - "robot", "pick_material", material={"uuid": "held-plate-uuid"}, target_owner={"uuid": owner_uuid} - ) + with pytest.raises(ValueError) as caught: + runtime.call_action( + "robot", "pick_material", material={"uuid": "held-plate-uuid"}, target_owner={"uuid": owner_uuid} + ) finally: runtime.stop() - assert result["material"] == "held_plate" - owner = result["target_owner"] - assert owner["uuid"] == owner_uuid and owner["id"] == owner_id and owner["type"] == "device" - assert isinstance(owner["name"], str) and owner["name"] + message = str(caught.value) + assert "target_owner" in message and owner_id in message and owner_uuid in message + assert "DeviceSlot" in message and "设备不是物料" in message -def test_resource_slot_tree_rooted_at_a_device_gets_a_device_reference() -> None: - """上游端口传来的扁平树以设备为根时同样不走 PLR 转换。""" +def test_resource_slot_tree_rooted_at_a_device_is_rejected() -> None: + """上游端口传来的扁平树以设备为根时同样报错,不转 PLR。""" runtime, graph = _transfer_runtime() robot_tree = next(tree for tree in graph.dump() if tree[0]["uuid"] == ROBOT_UUID) + try: + with pytest.raises(ValueError, match="DeviceSlot"): + runtime.call_action("robot", "pick_material", material={"uuid": "held-plate-uuid"}, target_owner=robot_tree) + finally: + runtime.stop() + + +def test_device_slot_reaches_the_driver_as_the_device_id() -> None: + """DeviceSlot 原样交给驱动(设备 id 字符串),不做物料转换、不回权威查询。""" + + runtime, _graph = _transfer_runtime() + node = runtime.devices["robot"] + authority = node.__dict__["_device_resource_service"] + queried: list = [] + authority.get_resources_sync = lambda uuids, with_children=True: queried.append(uuids) try: result = runtime.call_action( - "robot", "pick_material", material={"uuid": "held-plate-uuid"}, target_owner=robot_tree + "robot", "pick_into_gripper", material={"uuid": "held-plate-uuid"}, target_owner="robot" ) finally: runtime.stop() - assert result["target_owner"]["uuid"] == ROBOT_UUID - assert result["target_owner"]["type"] == "device" + assert result == {"material": "held_plate", "target_owner": "robot"} + assert type(result["target_owner"]) is str and queried == [] def test_hostlink_runtime_honors_topic_config_period_and_name() -> None: diff --git a/tests/client/host/ros2/test_device_node_contract.py b/tests/client/host/ros2/test_device_node_contract.py index f45f4de911..0df8ac963c 100644 --- a/tests/client/host/ros2/test_device_node_contract.py +++ b/tests/client/host/ros2/test_device_node_contract.py @@ -250,11 +250,14 @@ def create_timer(self, *_args, **_kwargs): } -def test_ros2_resource_slot_pointing_at_a_device_gets_a_device_reference() -> None: - """与 HostLink 同一规则:设备不是 PLR 物料,ResourceSlot 指向设备时驱动拿到设备引用。""" +def test_ros2_resource_slot_pointing_at_a_device_is_rejected() -> None: + """与 HostLink 同一规则:ResourceSlot 只指物料,指向设备时明确报错(设备参数用 DeviceSlot)。""" import logging + import pytest + + from unilabos.client.host.runtime.resource_slot import DeviceResourceSlotError from unilabos.resources.resource_tracker import ( DeviceNodeResourceTracker, ResourceTreeInstance, @@ -293,16 +296,16 @@ def lab_logger(self): return logging.getLogger(__name__) node = Node() - expected = {"uuid": robot_uuid, "id": "robot", "type": "device"} - - def subset(value): - return {key: value[key] for key in expected} - - assert subset(node._resolve_slot_value_sync({"uuid": robot_uuid})) == expected - assert subset(asyncio.run(node._convert_resource_async({"uuid": robot_uuid}))) == expected robot_tree = next(tree for tree in graph.dump() if tree[0]["uuid"] == robot_uuid) - assert subset(node._assemble_single_resource(ResourceTreeSet.load([robot_tree]))) == expected - # 设备与 PLR 物料一起查:顺序与输入一致,PLR 物料照常装配 - device, loose = node._convert_resources_sync(robot_uuid, plate_nodes[0]["uuid"]) - assert subset(device) == expected + for resolve in ( + lambda: node._resolve_slot_value_sync({"uuid": robot_uuid}), + lambda: asyncio.run(node._convert_resource_async({"uuid": robot_uuid})), + lambda: node._assemble_single_resource(ResourceTreeSet.load([robot_tree])), + lambda: node._convert_resources_sync(robot_uuid, plate_nodes[0]["uuid"]), + ): + with pytest.raises(DeviceResourceSlotError, match="DeviceSlot") as caught: + resolve() + assert "robot" in str(caught.value) and robot_uuid in str(caught.value) + # 物料照常装配 + (loose,) = node._convert_resources_sync(plate_nodes[0]["uuid"]) assert loose.name == "loose_plate" diff --git a/tests/client/host/runtime/test_resource_slot.py b/tests/client/host/runtime/test_resource_slot.py index 0018e717d8..bdf66ee9de 100644 --- a/tests/client/host/runtime/test_resource_slot.py +++ b/tests/client/host/runtime/test_resource_slot.py @@ -100,33 +100,33 @@ def _device_node(device_id: str, uuid: str) -> dict: "template_name": "test_device", "parent": None, "config": {}} -def test_device_slot_reference_only_for_a_device_root(): +def test_a_slot_tree_rooted_at_a_device_names_the_parameter_and_the_device(): from unilabos.resources.resource_tracker import ResourceTreeSet from unilabos.server.services.materials.graph import graph_resource_tree - from unilabos.client.host.runtime.resource_slot import device_slot_reference + from unilabos.client.host.runtime.resource_slot import ( + DeviceResourceSlotError, + first_plr_resource, + reject_device_slot, + ) from tests.plr_fixtures import plate robot = graph_resource_tree([_device_node("robot", "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f61")]) - assert device_slot_reference(robot) == { - "uuid": "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f61", - "id": "robot", - "name": robot.trees[0].root_node.res_content.name, - "type": "device", - } + with pytest.raises(DeviceResourceSlotError) as caught: + first_plr_resource(robot, "slot-ref", "target_owner") + message = str(caught.value) + assert "参数 target_owner" in message and "robot" in message and "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f61" in message + assert "设备不是物料" in message and "DeviceSlot" in message plates = ResourceTreeSet.from_plr_resources([plate("p")], known_random_uuid=True) - assert device_slot_reference(plates) is None + reject_device_slot(plates, "sample") + assert first_plr_resource(plates, "slot-ref").name == "p" def test_a_slot_tree_without_plr_materials_fails_with_a_clear_error(): - """``to_plr_resources`` 跳过设备树:一个 PLR 物料都转不出时说清是哪个引用,不再 IndexError。""" + """一个 PLR 物料都转不出(空树)时说清是哪个引用,不再 IndexError。""" - from unilabos.server.services.materials.graph import graph_resource_tree + from unilabos.resources.resource_tracker import ResourceTreeSet from unilabos.client.host.runtime.resource_slot import first_plr_resource - devices = graph_resource_tree([ - _device_node("left", "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f62"), - _device_node("right", "6f0d1f3e-0c7a-4a55-9b7e-1d2c3b4a5f63"), - ]) with pytest.raises(ValueError, match="没有 PLR 物料") as caught: - first_plr_resource(devices, "slot-ref") - assert "slot-ref" in str(caught.value) and "left" in str(caught.value) + first_plr_resource(ResourceTreeSet([]), "slot-ref") + assert "slot-ref" in str(caught.value) and "空树" in str(caught.value) diff --git a/unilabos/client/host/hostlink/local_runtime.py b/unilabos/client/host/hostlink/local_runtime.py index 7dab333628..73c12683ab 100644 --- a/unilabos/client/host/hostlink/local_runtime.py +++ b/unilabos/client/host/hostlink/local_runtime.py @@ -34,7 +34,6 @@ from unilabos.client.host.runtime.node import BackendCapabilityError, DeviceNode from unilabos.client.host.runtime.resource import ResourceService from unilabos.client.host.runtime.resource_slot import ( - device_slot_reference, first_plr_resource, is_unset_resource_slot, ) @@ -869,10 +868,10 @@ def _map_action_arguments( mapped[target_name] = value return mapped - def _resolve_resource_slot(self, value: Any) -> Any: + def _resolve_resource_slot(self, value: Any, parameter: str = "") -> Any: """Resolve one ResourceSlot from this device's authoritative snapshot. - 指向设备本身(设备不是 PLR 物料)时交给驱动设备引用,见 ``device_slot_reference``。 + ResourceSlot 只指物料:解析到设备时报错并指出参数(设备参数用 ``DeviceSlot``)。 """ kind, payload = parse_resource_slot(value) @@ -887,10 +886,9 @@ def _resolve_resource_slot(self, value: Any) -> Any: "单个 ResourceSlot 必须恰好包含一棵资源树," f"实际为 {len(tree_set.trees)} 棵" ) - device = device_slot_reference(tree_set) - if device is not None: - return device - resource = first_plr_resource(tree_set, tree_set.trees[0].root_node.res_content.uuid) + resource = first_plr_resource( + tree_set, tree_set.trees[0].root_node.res_content.uuid, parameter + ) matches = self.resource_tracker.figure_resource(resource, try_mode=True) if len(matches) > 1: raise ValueError(f"ResourceSlot 匹配到多个本地资源:{matches}") @@ -905,11 +903,8 @@ def _resolve_resource_slot(self, value: Any) -> Any: identity = payload.get("uuid") or payload.get("id") or payload.get("name") tree_set = self._fetch_reference_from_authority(payload) if tree_set is not None and len(tree_set.trees): - # 设备节点不在本地 PLR 快照里,权威取回的是设备树:设备本身不转 PLR - device = device_slot_reference(tree_set) - if device is not None: - return device - resource = first_plr_resource(tree_set, identity) + # 设备节点不在本地 PLR 快照里:权威取回设备树时明确报错,不越界 + resource = first_plr_resource(tree_set, identity, parameter) refigured = self.resource_tracker.figure_resource(resource, try_mode=True) if len(refigured) == 1: return refigured[0] @@ -970,13 +965,13 @@ def _resolve_action_resources( if is_unset_resource_slot(value): resolved[name] = None else: - resolved[name] = self._resolve_resource_slot(value) + resolved[name] = self._resolve_resource_slot(value, name) elif shape == "list": values = resolved[name] if not isinstance(values, list): raise TypeError(f"ResourceSlot 列表参数 {name!r} 必须是列表") resolved[name] = [ - self._resolve_resource_slot(value) for value in values + self._resolve_resource_slot(value, name) for value in values ] if PARAM_SAMPLE_UUIDS in signature.parameters: diff --git a/unilabos/client/host/ros2/base_device_node.py b/unilabos/client/host/ros2/base_device_node.py index 5e88a998d6..67c246506f 100644 --- a/unilabos/client/host/ros2/base_device_node.py +++ b/unilabos/client/host/ros2/base_device_node.py @@ -33,9 +33,9 @@ from unilabos.client.host.runtime.node import DeviceNode from unilabos.client.host.runtime.action import bind_action_context from unilabos.client.host.runtime.resource_slot import ( - device_slot_reference, first_plr_resource, is_unset_resource_slot, + reject_device_slot, resource_slot_shapes, ) from unilabos.client.host.runtime.async_utils import schedule_async_func @@ -1573,7 +1573,7 @@ def _execute_driver_command(self, string: str): self.lab_logger().error( f"转换ResourceSlot参数 {arg_name} 失败: {e}\n{traceback.format_exc()}" ) - raise JsonCommandInitError(f"ResourceSlot参数转换失败: {arg_name}") + raise JsonCommandInitError(f"ResourceSlot参数转换失败: {arg_name}:{e}") # 处理 ResourceSlot 列表:逐元素剥离 elif slot_shape == "list": @@ -1587,7 +1587,7 @@ def _execute_driver_command(self, string: str): self.lab_logger().error( f"转换ResourceSlot列表参数 {arg_name} 失败: {e}\n{traceback.format_exc()}" ) - raise JsonCommandInitError(f"ResourceSlot列表参数转换失败: {arg_name}") + raise JsonCommandInitError(f"ResourceSlot列表参数转换失败: {arg_name}:{e}") # ROS 2 执行没有框架上下文:可空的 ActionContext 参数得到 None,不可空的现建一个 return function(**bind_action_context(function, function_args, None)) except KeyError as ex: @@ -1612,20 +1612,13 @@ def _convert_resources_sync(self, *uuids: str) -> List["ResourcePLR"]: tree_set = self._require_resource_service().get_resources_sync(uuids_list, with_children=True) if not len(tree_set.trees): raise Exception(f"资源查询返回空树: {uuids_list}") - # 设备本身不是 PLR 物料(to_plr_resources 跳过设备树):按 uuid 交给驱动设备引用 - devices: Dict[str, Dict[str, str]] = {} - plr_trees = [] - for tree in tree_set.trees: - reference = device_slot_reference(ResourceTreeSet([tree])) - if reference is None: - plr_trees.append(tree) - else: - devices[reference["uuid"]] = reference + # ResourceSlot 只指物料:查到设备时明确报错(to_plr_resources 跳过设备树,下面会错位) + reject_device_slot(tree_set) plr_resources = tree_set.to_plr_resources() # 通过资源跟踪器获取本地实例 figured_resources: List[ResourcePLR] = [] - for plr_resource, tree in zip(plr_resources, plr_trees): + for plr_resource, tree in zip(plr_resources, tree_set.trees): res = self.resource_tracker.figure_resource(plr_resource, try_mode=True) if len(res) == 0: self.lab_logger().warning(f"资源转换未能索引到实例: {tree.root_node.res_content},返回新建实例") @@ -1637,9 +1630,6 @@ def _convert_resources_sync(self, *uuids: str) -> List["ResourcePLR"]: mapped_plr_resources = [] for uuid in uuids_list: - if uuid in devices: - mapped_plr_resources.append(devices[uuid]) - continue found = None for plr_resource in figured_resources: r = find_resource_by_uuid(plr_resource, uuid) @@ -1662,9 +1652,6 @@ def _assemble_single_resource(self, tree_set: "ResourceTreeSet") -> "ResourcePLR if len(tree_set.trees) != 1: names = [t.root_node.res_content.name for t in tree_set.trees] raise ValueError(f"单物料输入要求恰好一个根物料,实际得到 {len(tree_set.trees)} 个根:{names}") - device = device_slot_reference(tree_set) - if device is not None: - return device plr = first_plr_resource(tree_set, tree_set.trees[0].root_node.res_content.uuid) res = self.resource_tracker.figure_resource(plr, try_mode=True) if len(res) == 1: @@ -1767,7 +1754,7 @@ async def _execute_driver_command_async(self, string: str): self.lab_logger().error( f"转换ResourceSlot参数 {arg_name} 失败: {e}\n{traceback.format_exc()}" ) - raise JsonCommandInitError(f"ResourceSlot参数转换失败: {arg_name}") + raise JsonCommandInitError(f"ResourceSlot参数转换失败: {arg_name}:{e}") # 处理 ResourceSlot 列表:逐元素剥离 elif slot_shape == "list": @@ -1781,7 +1768,7 @@ async def _execute_driver_command_async(self, string: str): self.lab_logger().error( f"转换ResourceSlot列表参数 {arg_name} 失败: {e}\n{traceback.format_exc()}" ) - raise JsonCommandInitError(f"ResourceSlot列表参数转换失败: {arg_name}") + raise JsonCommandInitError(f"ResourceSlot列表参数转换失败: {arg_name}:{e}") # ROS 2 执行没有框架上下文:可空的 ActionContext 参数得到 None,不可空的现建一个 return await function(**bind_action_context(function, function_args, None)) @@ -1799,9 +1786,7 @@ async def _convert_resource_async(self, resource_data: "ResourceDictType"): if unilabos_uuid: resource_tree = await self.get_resource([unilabos_uuid], with_children=True) - device = device_slot_reference(resource_tree) - if device is not None: - return device + reject_device_slot(resource_tree) plr_resources = resource_tree.to_plr_resources() if plr_resources: plr_resource = plr_resources[0] diff --git a/unilabos/client/host/runtime/resource_slot.py b/unilabos/client/host/runtime/resource_slot.py index 8f011c8cde..2b2735830f 100644 --- a/unilabos/client/host/runtime/resource_slot.py +++ b/unilabos/client/host/runtime/resource_slot.py @@ -67,36 +67,32 @@ def is_unset_resource_slot(value: Any) -> bool: return False -def device_slot_reference(tree_set: Any) -> Optional[dict[str, str]]: - """ResourceSlot 解析到的是设备本身时,返回交给驱动的设备引用;否则返回 ``None``。 +class DeviceResourceSlotError(ValueError): + """ResourceSlot 指向了设备:设备不是物料,设备参数用 ``DeviceSlot``(值是设备 id)。""" - 设备不是 PLR 物料:设备子树里只放 PLR 物料,设备节点本身不反序列化(``to_plr_resources`` - 跳过设备树),没有 PLR 实例可给。搬运动作把设备当所属物料时(例如机械臂的夹爪库位挂在设备上), - 驱动拿到 ``{"uuid", "id", "name", "type": "device"}``,与 ``{"uuid": ...}`` 引用同形。 - ``tree_set`` 是权威取回或上游传来的单棵 ``ResourceTreeSet``。 - """ - trees = getattr(tree_set, "trees", None) or [] - if len(trees) != 1: - return None - root = trees[0].root_node.res_content - if str(getattr(root, "type", "") or "") != "device": - return None - return { - "uuid": str(root.uuid or ""), - "id": str(root.id or ""), - "name": str(root.name or root.id or ""), - "type": "device", - } +def reject_device_slot(tree_set: Any, parameter: str = "") -> None: + """ResourceSlot 解析到的树以设备为根时报错,指出参数与设备。 + + ResourceSlot 只指物料:设备子树里放的是 PLR 物料,设备本身不是物料,不转 PLR(``to_plr_resources`` + 跳过设备树)。动作要的是设备(例如搬运的目标是机械臂自己的夹爪库位)时,参数应注解为 ``DeviceSlot``。 + """ + for tree in getattr(tree_set, "trees", None) or []: + root = tree.root_node.res_content + if str(getattr(root, "type", "") or "") != "device": + continue + where = f"参数 {parameter} " if parameter else "ResourceSlot " + raise DeviceResourceSlotError( + f"{where}指向设备 {root.id}({root.uuid}):设备不是物料,ResourceSlot 只接受物料;" + "设备参数请注解为 DeviceSlot(值是设备 id)" + ) -def first_plr_resource(tree_set: Any, identity: Any) -> Any: - """单个 ResourceSlot 的资源树转成 PLR 后的根实例;一个 PLR 物料都转不出时明确报错(而不是越界)。 - 调用方先用 :func:`device_slot_reference` 处理设备本身;``to_plr_resources`` 只会在树里全是设备时 - 返回空列表,这里兜底说清是哪个引用。 - """ +def first_plr_resource(tree_set: Any, identity: Any, parameter: str = "") -> Any: + """单个 ResourceSlot 的资源树转成 PLR 后的根实例;指向设备或一个 PLR 物料都转不出时明确报错(而不是越界)。""" + reject_device_slot(tree_set, parameter) resources = tree_set.to_plr_resources() if not resources: roots = [ diff --git a/unilabos/registry/placeholder_type.py b/unilabos/registry/placeholder_type.py index d97f40c6e0..b4e56fa5a5 100644 --- a/unilabos/registry/placeholder_type.py +++ b/unilabos/registry/placeholder_type.py @@ -8,8 +8,8 @@ class ResourceSlot(Resource): 1. 作为 @action 函数参数类型(**暴露给外部调用的契约**):表示「**一个完整的物料**」。 框架已在 send_goal 把原始入参解析为单个 PLR ``Resource`` 实例,函数体内拿到的就是它, - 直接当普通 Resource 用即可,无需关心 list/dict。例外:指向设备本身时(设备不是 PLR 物料), - 拿到的是设备引用 ``{"uuid", "id", "name", "type": "device"}``。 + 直接当普通 Resource 用即可,无需关心 list/dict。ResourceSlot 只指物料,指向设备时 Host 报错; + 参数要的是设备时用 ``DeviceSlot``(值是设备 id)。 2. 作为原始入参(**仅框架内部解析阶段**):见 ``ResourceSlotRawInput``,可能是 list(一棵树的扁平节点组,handle ``@flatten`` 运行期形态)或 dict(资源引用,前端 schema 填写形态)。 From 69a16781796f935ffbe1d90f8afc9fdbf00ce625 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:42 +0800 Subject: [PATCH 06/27] feat(workflow): declare allowed resource templates on @workflow Workflow material inputs had no way to restrict their templates: an Annotated[ResourceSlot, AllowedResourceTemplates(...)] input was rejected because the symbols could not be bound to the registry. @workflow(allowed_templates={input: [registry resource id, ...]}) now carries the restriction while the input stays a plain ResourceSlot / List[ResourceSlot]: - the decorator and static compilation (workflow_ast) read the literal; a key that is not a ResourceSlot input fails registration; - publishing (template payload, authoring compile) resolves the ids to resource template uuids through the materials authority - the community.. prefix may be omitted when unique - and fails on an unknown id; the uuids land in the input (and implicit output) schema extension allowed_resource_template_uuids already used by composite handles, so workflow details and the template catalog carry them for frontend filtering; - run preflight and task creation reject a site-bound input whose occupant has another template (material_site_invalid / invalid_material_site, reason template_mismatch) and a {uuid} input of another template (material_template_mismatch / invalid_material_template). AllowedResourceTemplates on a workflow input still fails, now pointing to @workflow(allowed_templates=...). --- docs/developer_guide/interfaces/workflows.md | 22 ++- .../developer_guide/v1_file_index/workflow.md | 2 +- .../test_workflow_allowed_templates.py | 173 ++++++++++++++++++ tests/server/test_material_site_binding.py | 74 ++++++++ unilabos/registry/workflow_ast.py | 16 ++ unilabos/registry/workflow_contract.py | 94 +++++++++- unilabos/registry/workflows.py | 79 +++++++- unilabos/server/api/envelope.py | 2 + .../runtime/workflow/authoring_compiler.py | 1 + .../runtime/workflow/material_sites.py | 72 +++++++- .../runtime/workflow/run_preflight.py | 34 +++- .../services/runtime/workflow/service.py | 38 +++- 12 files changed, 589 insertions(+), 18 deletions(-) create mode 100644 tests/registry/test_workflow_allowed_templates.py diff --git a/docs/developer_guide/interfaces/workflows.md b/docs/developer_guide/interfaces/workflows.md index df4737d743..e20d9def39 100644 --- a/docs/developer_guide/interfaces/workflows.md +++ b/docs/developer_guide/interfaces/workflows.md @@ -93,7 +93,27 @@ node.param = {"volume": {"kind": "workflow_input", "parameter": "volume"}, "spee | `DeviceSlot` | `{"$slot": "DeviceSlot"}` | 设备 id 字符串 | 可以(设备 id 是图里的稳定名字) | | `SiteSlot` | `{"$slot": "SiteSlot"}` | ResourceSite uuid 字符串 | 不可以(库位是具体实例) | -`DeviceSlot` / `SiteSlot` 不是物料:不加物料锁、不成为隐式输出,`AllowedResourceTemplates` 只能用在 `ResourceSlot` 上。 +`DeviceSlot` / `SiteSlot` 不是物料:不加物料锁、不成为隐式输出。 + +物料输入允许哪些资源模板写在装饰器上,输入本身仍是 `ResourceSlot` / `list[ResourceSlot]`: + +```python +@workflow("Cyclize plates", allowed_templates={ + "plate_1": ["deep_well_plate_96", "collection_plate_96"], +}) +def cyclize_plates(ctx, *, plate_1: ResourceSlot, ...): ... +``` + +- 键必须是 `ResourceSlot` / `list[ResourceSlot]` 输入,否则注册失败;值是注册表资源 id(社区包的 `community.<包>.` + 前缀可省略,省略后要唯一)。源码静态编译读这个字面量。 +- 发布时(设备包模板随注册表上报、作者编译)按物料权威把 id 解析成资源模板 uuid,未知 id 发布失败;解析结果写进该输入 + (与同名隐式输出)schema 的 `allowed_resource_template_uuids`,即 `{"$slot": "ResourceSlot", "allowed_resource_template_uuids": [...]}`, + 工作流详情与模板目录的输入 schema 都带它,前端按它筛选。 +- 运行预检与建任务按它核对:按库位绑定(`{"site_uuid"}`)的占用物料不符报 `material_site_invalid`(预检 + `invalid_material_site`,`details.reason=template_mismatch`);直接给的 `{"uuid"}` 物料不符报 `material_template_mismatch` + (预检 `invalid_material_template`)。 +- 旧写法 `plate_1: Annotated[ResourceSlot, AllowedResourceTemplates(...)]` 写在工作流输入上照旧报错,错误信息指向 + `@workflow(allowed_templates=...)`;动作参数上的 `Annotated` 写法不变。 它们的值形状就是字符串,可以接到节点上同名类型的参数或普通字符串参数(节点参数里 `DeviceSlot` / `SiteSlot` 渲染为 `{"type": "string"}`);`DeviceSlot` 与 `SiteSlot` 之间、它们与 `ResourceSlot` 之间不能互接。 diff --git a/docs/developer_guide/v1_file_index/workflow.md b/docs/developer_guide/v1_file_index/workflow.md index 8747405505..ff7205813f 100644 --- a/docs/developer_guide/v1_file_index/workflow.md +++ b/docs/developer_guide/v1_file_index/workflow.md @@ -154,6 +154,6 @@ | `unilabos/workflow/wf_utils.py` | 151 | PORTED | server/services/runtime/workflow/upload.py + app/cli/workflow.py(`unilab workflow upload`) | | | `unilabos/workflow/workflow_boundary.py` | 247 | PORTED | entry_parameters.py `resolve_declared_output`(声明输出缺失/类型不符即任务失败) | | | `unilabos/workflow/workflow_boundary_binding.py` | 280 | PORTED | entry_parameters.py `_OutputResolver` | | -| `unilabos/workflow/workflow_io.py` | 1028 | PARTIAL | server/services/runtime/workflow/workflow_io.py + value_schema.py `schema_is_assignable` + entry_parameters.py | 工作流输入不支持 `AllowedResourceTemplates`(registry/workflow_contract.py 直接报「资源模板筛选尚未绑定注册表」);ResourceSlot 透传/连线的模板兼容不校验(见 material_graph_validation) | +| `unilabos/workflow/workflow_io.py` | 1028 | PARTIAL | server/services/runtime/workflow/workflow_io.py + value_schema.py `schema_is_assignable` + entry_parameters.py | 工作流输入的模板筛选改写在 `@workflow(allowed_templates=...)`(发布时解析成 `allowed_resource_template_uuids`,预检 / 建任务核对;输入上的 `AllowedResourceTemplates` 报错并指向新写法);ResourceSlot 透传/连线的模板兼容不校验(见 material_graph_validation) | | `unilabos/workflow/workflow_spec_compiler.py` | 1238 | DROPPED | #4(执行计划→旧 EdgeScheduler 规格;dev `_build_dag` 直接消费计划) | | | `unilabos/workflow/workflow_type.py` | 35 | PORTED | operation_category.py `normalize_workflow_type` | | diff --git a/tests/registry/test_workflow_allowed_templates.py b/tests/registry/test_workflow_allowed_templates.py new file mode 100644 index 0000000000..6cb10546a4 --- /dev/null +++ b/tests/registry/test_workflow_allowed_templates.py @@ -0,0 +1,173 @@ +"""工作流物料输入的允许模板写在装饰器上:``@workflow(allowed_templates={输入名: [注册表资源 id, ...]})``。 + +输入本身照常注解为 ``ResourceSlot`` / ``List[ResourceSlot]``;键不是这样的输入时注册失败。发布时(模板载荷 / 作者编译) +按物料权威把注册表资源 id 解析成资源模板 uuid(未知 id 发布失败),写进输入 schema 的 +``allowed_resource_template_uuids``——动作 / 组合工作流已在用的同一个扩展,前端据此筛选。 +``Annotated[ResourceSlot, AllowedResourceTemplates(...)]`` 写在工作流输入上仍报错,并指向新写法。 +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import List, Optional +from uuid import uuid4 + +import pytest + +from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.workflow_ast import WorkflowSourceError, compile_workflow_source +from unilabos.registry.workflows import ( + build_workflow_template_payload, + clear_registered_workflows, + get_registered_workflows, + workflow, +) + +DEEP_WELL = str(uuid4()) +COLLECTION = str(uuid4()) +TROUGH = str(uuid4()) +TEMPLATES = { + "community.demo_pkg.deep_well_plate": DEEP_WELL, + "community.demo_pkg.collection_plate": COLLECTION, + "community.demo_pkg.reagent_trough": TROUGH, + "community.other_pkg.reagent_trough": str(uuid4()), +} + + +class _Gateway: + def list_templates(self, **_kwargs): + return [SimpleNamespace(name=name, template_uuid=identity) for name, identity in TEMPLATES.items()] + + +@pytest.fixture(autouse=True) +def _materials(monkeypatch): + from unilabos.server import execution_composition + + monkeypatch.setattr(execution_composition, "get_materials_gateway", lambda: _Gateway()) + snapshot = get_registered_workflows() + clear_registered_workflows() + yield + clear_registered_workflows() + from unilabos.registry.workflows import _registered_workflows + + _registered_workflows.update(snapshot) + + +def _single_definition(): + [definition] = get_registered_workflows().values() + return definition + + +def _inputs(payload) -> dict: + return {item["name"]: item["schema"] for item in payload["io"]["input_contract"]["parameters"]} + + +def test_allowed_templates_resolve_into_the_input_schema_extension() -> None: + @workflow( + "环化", + allowed_templates={ + "plate_1": ["deep_well_plate", "community.demo_pkg.collection_plate"], + "plates": "deep_well_plate", + }, + ) + def cyclize(ctx, *, plate_1: ResourceSlot, plates: List[ResourceSlot], spare: Optional[ResourceSlot] = None, + volume: float = 1.0): + ctx.run("handler/couple", {"plate": plate_1, "plates": plates}) + + definition = _single_definition() + assert definition.allowed_templates == { + "plate_1": ["deep_well_plate", "community.demo_pkg.collection_plate"], + "plates": ["deep_well_plate"], + } + payload = build_workflow_template_payload(definition) + + inputs = _inputs(payload) + assert inputs["plate_1"] == {"$slot": "ResourceSlot", "allowed_resource_template_uuids": [DEEP_WELL, COLLECTION]} + assert inputs["plates"]["items"] == {"$slot": "ResourceSlot", "allowed_resource_template_uuids": [DEEP_WELL]} + assert "allowed_resource_template_uuids" not in str(inputs["spare"]) + # 同名的隐式输出(物料原样传出)带同一份允许模板 + implicit = {item["name"]: item["schema"] for item in payload["io"]["output_contract"]["outputs"]} + assert implicit["plate_1"] == inputs["plate_1"] + + # 写进去的就是工作流输入合同认的扩展(存库 / 详情接口按它规范化) + from unilabos.server.services.runtime.workflow.workflow_io import normalize_input_contract + + normalized = normalize_input_contract(payload["io"]["input_contract"]) + assert normalized["parameters"][0]["schema"]["allowed_resource_template_uuids"] == [DEEP_WELL, COLLECTION] + + +@pytest.mark.parametrize( + "allowed, message", + [ + ({"missing": ["deep_well_plate"]}, "不是工作流输入"), + ({"volume": ["deep_well_plate"]}, "必须是 ResourceSlot / List[ResourceSlot] 输入"), + ({"plate_1": []}, "非空"), + ({"plate_1": [3]}, "不是注册表资源 id"), + ], +) +def test_keys_must_be_resource_slot_inputs(allowed, message) -> None: + with pytest.raises(ValueError, match=message.replace("[", r"\[").replace("]", r"\]")): + + @workflow("环化", allowed_templates=allowed) + def cyclize(ctx, *, plate_1: ResourceSlot, volume: float = 1.0): + ctx.run("handler/couple", {"plate": plate_1}) + + assert get_registered_workflows() == {} + + +@pytest.mark.parametrize( + "identity, message", + [("no_such_plate", "注册表里没有的资源"), ("reagent_trough", "匹配到多个注册表资源")], +) +def test_unknown_or_ambiguous_ids_fail_publishing(identity, message) -> None: + @workflow("环化", allowed_templates={"plate_1": [identity]}) + def cyclize(ctx, *, plate_1: ResourceSlot): + ctx.run("handler/couple", {"plate": plate_1}) + + with pytest.raises(ValueError, match=message): + build_workflow_template_payload(_single_definition()) + + +def test_static_compilation_reads_the_literal() -> None: + program = compile_workflow_source( + """ +from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.workflows import workflow + +@workflow("环化", allowed_templates={"plate_1": ["deep_well_plate", "collection_plate"]}) +def cyclize(ctx, *, plate_1: ResourceSlot): + ctx.run("handler/couple", {"plate": plate_1}) +""" + ) + assert program.allowed_templates == {"plate_1": ["deep_well_plate", "collection_plate"]} + with pytest.raises(WorkflowSourceError, match="不是工作流输入") as caught: + compile_workflow_source( + """ +from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.workflows import workflow + +@workflow("环化", + allowed_templates={"plate_9": ["deep_well_plate"]}) +def cyclize(ctx, *, plate_1: ResourceSlot): + ctx.run("handler/couple", {"plate": plate_1}) +""" + ) + assert caught.value.line == 6 + + +def test_annotated_allowed_resource_templates_on_a_workflow_input_points_to_the_decorator() -> None: + source = """ +from typing import Annotated +from unilabos.registry.annotations import AllowedResourceTemplates +from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.workflows import workflow +from lab.plates import DeepWellPlate + +@workflow("环化") +def cyclize(ctx, *, plate_1: Annotated[ResourceSlot, AllowedResourceTemplates(DeepWellPlate)]): + ctx.run("handler/couple", {"plate": plate_1}) +""" + with pytest.raises(WorkflowSourceError) as caught: + compile_workflow_source(source) + message = str(caught.value) + assert "plate_1" in message and "@workflow(" in message and "allowed_templates=" in message diff --git a/tests/server/test_material_site_binding.py b/tests/server/test_material_site_binding.py index bb18ab676f..b8175f9108 100644 --- a/tests/server/test_material_site_binding.py +++ b/tests/server/test_material_site_binding.py @@ -263,3 +263,77 @@ def test_resource_slot_input_schema_accepts_the_site_form() -> None: assert validate_value({"$slot": "ResourceSlot"}, {"site_uuid": site.upper()}) == {"site_uuid": site} with pytest.raises(WorkflowValueSchemaError): validate_value({"$slot": "ResourceSlot"}, {"site_uuid": "A1"}) + + +def _typed_carrier(stack: Stack) -> tuple[dict[str, str], dict[str, str]]: + """一个两位载架:A 位是深孔板,B 位是试剂槽;模板 uuid 由物料权威登记(工作流输入的允许模板按 uuid 核对)。""" + + templates = {name: str(uuid4()) for name in ("deep_well_plate", "reagent_trough")} + for name, identity in templates.items(): + stack.materials.put_template(_mutation("put_template"), ResourceTemplateWrite( + template_uuid=identity, name=name, display_name=name, resource_type="container", class_name="Container")) + _template(stack, "carrier") + + def identity(name: str, template: str) -> MaterialIdentityWrite: + return MaterialIdentityWrite(resource_id=f"{name}-{uuid4()}", name=f"{name}-{uuid4()}", template_name=template, + resource_type="container", class_name="Container") + + tree = stack.materials.create_tree(_mutation("create_material_tree"), MaterialTreeCreate(nodes=[ + MaterialNodeCreate(client_ref="carrier", identity=identity("carrier", "carrier"), sites=[ + SiteCreate(template_name="slot", site_index=0, label="A", occupied_client_ref="plate"), + SiteCreate(template_name="slot", site_index=1, label="B", occupied_client_ref="trough")]), + MaterialNodeCreate(client_ref="plate", parent_client_ref="carrier", identity=identity("plate", "deep_well_plate")), + MaterialNodeCreate(client_ref="trough", parent_client_ref="carrier", identity=identity("trough", "reagent_trough")), + ])).data + carrier = tree.client_ref_map["carrier"] + sites = {site.label: site.site_uuid for site in stack.materials.get_material(carrier).sites} + return templates, {**sites, "plate": tree.client_ref_map["plate"], "trough": tree.client_ref_map["trough"]} + + +def _allowlisted_input(template_uuids: list[str]) -> dict: + slot = {"$slot": "ResourceSlot", "allowed_resource_template_uuids": template_uuids} + return {"input_contract": {"version": 1, "parameters": [{"name": "plate_1", "schema": slot, "required": True}]}, + "output_contract": {"version": 1, "outputs": [{"name": "plate_1", "schema": slot, "implicit": True}]}, + "output_bindings": {"plate_1": {"kind": "workflow_input", "parameter": "plate_1"}}} + + +@pytest.mark.parametrize("form", ["site", "uuid"]) +def test_workflow_input_outside_its_allowed_templates_is_rejected_at_preflight_and_submission(tmp_path, form) -> None: + """``@workflow(allowed_templates=...)`` 写进输入 schema 的允许模板:按库位绑定与直接给 ``{"uuid"}`` 都核对。""" + + stack = Stack(tmp_path) + try: + templates, refs = _typed_carrier(stack) + node = _node({"sample": {"kind": "workflow_input", "parameter": "plate_1"}}) + record = _workflow(stack, [node], io=_allowlisted_input([templates["deep_well_plate"]])) + wrong = {"plate_1": {"site_uuid": refs["B"]} if form == "site" else {"uuid": refs["trough"]}} + right = {"plate_1": {"site_uuid": refs["A"]} if form == "site" else {"uuid": refs["plate"]}} + code = "material_site_invalid" if form == "site" else "material_template_mismatch" + + with pytest.raises(WorkflowError) as caught: + _create(stack, record, wrong) + assert caught.value.code == code + assert caught.value.details["reason"] == "template_mismatch" and caught.value.details["parameter"] == "plate_1" + assert "plate_1" in caught.value.message and "reagent_trough" in caught.value.message + assert stack.workflow.list_tasks(page=1, page_size=10)["items"] == [] + + client = TestClient(create_workflow_app(stack.workflow)) + response = client.post("/api/v1/workflow-tasks", json={"workflow_uuid": record["uuid"], "input": wrong}).json() + assert response["code"] == 1000 and response["error"]["code"] == code + report = client.post(f"/api/v1/workflows/{record['uuid']}/run-preflight", json={"input": wrong}).json()["data"] + assert report["status"] == "invalid" + [blocked] = [item for item in report["checks"] if item["blocking"]] + assert blocked["code"] == ("invalid_material_site" if form == "site" else "invalid_material_template") + assert blocked["details"]["reason"] == "template_mismatch" + + ok = client.post(f"/api/v1/workflows/{record['uuid']}/run-preflight", json={"input": right}).json()["data"] + # 这里没有在线设备(device_action_unavailable 照常阻塞),只看物料这一项 + assert not [item for item in ok["checks"] if item["blocking"] and item["type"] == "resources"] + task = _create(stack, record, right) + assert task["input"] == {"plate_1": {"uuid": refs["plate"]}} + + # 工作流详情的输入 schema 带着前端筛选要用的允许模板 + detail = client.get(f"/api/v1/workflows/{record['uuid']}").json()["data"] + assert templates["deep_well_plate"] in str(detail) and "allowed_resource_template_uuids" in str(detail) + finally: + stack.close() diff --git a/unilabos/registry/workflow_ast.py b/unilabos/registry/workflow_ast.py index 8bdbb8b6a1..85255536db 100644 --- a/unilabos/registry/workflow_ast.py +++ b/unilabos/registry/workflow_ast.py @@ -88,6 +88,8 @@ class StaticWorkflowSource: display_name: str = "" description: str = "" tags: list[str] = field(default_factory=list) + #: ``@workflow(allowed_templates=...)``:输入名 → 允许的注册表资源 id(发布时解析成资源模板 uuid) + allowed_templates: dict[str, list[str]] = field(default_factory=dict) #: 步骤 key → (起始行, 起始列, 结束行, 结束列),行列从 1 开始,列按 UTF-8 字节计 step_ranges: dict[str, tuple[int, int, int, int]] = field(default_factory=dict) #: 步骤 key → 锚点声明的节点 UUID @@ -172,6 +174,7 @@ def compile_workflow_source(python_source: str, *, function_name: Optional[str] output_contract=output_contract, constants=constants, source_lines=lines, ) decorator = next((dec for dec in function.decorator_list if _is_workflow_decorator(dec)), None) + allowed_literal: Any = None if isinstance(decorator, ast.Call): try: if decorator.args: @@ -183,8 +186,21 @@ def compile_workflow_source(python_source: str, *, function_name: Optional[str] result.description = str(ast.literal_eval(keyword.value)) elif keyword.arg == "tags": result.tags = [str(tag) for tag in ast.literal_eval(keyword.value)] + elif keyword.arg == "allowed_templates": + allowed_node = keyword.value + allowed_literal = ast.literal_eval(keyword.value) except (ValueError, TypeError, SyntaxError): raise WorkflowSourceError("@workflow 参数必须是字面量", line=decorator.lineno) from None + if allowed_literal is not None: + from unilabos.registry.workflow_contract import apply_allowed_templates, normalize_allowed_templates + + try: + result.allowed_templates = normalize_allowed_templates(allowed_literal) + apply_allowed_templates(input_contract, result.allowed_templates) + except ValueError as exc: + raise WorkflowSourceError( + f"{function.name}:{exc}", line=allowed_node.lineno, column=allowed_node.col_offset, + ) from None return result diff --git a/unilabos/registry/workflow_contract.py b/unilabos/registry/workflow_contract.py index bd2156a140..a2b90cb03a 100644 --- a/unilabos/registry/workflow_contract.py +++ b/unilabos/registry/workflow_contract.py @@ -75,7 +75,11 @@ def parse_workflow_contract_symbols( parsed = parse_parameter_annotation(arg.arg, arg.annotation, default=NO_DEFAULT if default is None else default, imports=imports) if parsed.resource_templates: - raise ValueError("工作流输入的资源模板筛选尚未绑定注册表;不能丢弃 AllowedResourceTemplates 声明") + raise ValueError( + f"工作流输入 {arg.arg!r} 不能用 Annotated[ResourceSlot, AllowedResourceTemplates(...)] 限定资源模板;" + f"输入写成 {arg.arg}: ResourceSlot,模板写在装饰器上:" + f"@workflow(..., allowed_templates={{{arg.arg!r}: [\"<注册表资源 id>\", ...]}})" + ) parameters.append(parsed.to_dict()) declaration = function.returns if isinstance(declaration, ast.Constant) and isinstance(declaration.value, str): @@ -98,3 +102,91 @@ def resource_schema(schema: dict[str, Any]) -> bool: if resource_schema(parameter["schema"]) and parameter["name"] not in explicit: outputs["outputs"].append({"name": parameter["name"], "schema": parameter["schema"], "implicit": True}) return {"version": 1, "parameters": parameters}, outputs + + +def normalize_allowed_templates(value: Any) -> dict[str, list[str]]: + """``@workflow(allowed_templates=...)`` 的字面量 → ``{输入名: [注册表资源 id, ...]}``(去重、保序)。 + + 键是工作流输入名;值是一个或多个注册表资源 id(字符串)。写法不对抛 ``ValueError``。 + """ + + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("@workflow 的 allowed_templates 必须是 {输入名: [注册表资源 id, ...]} 字典") + result: dict[str, list[str]] = {} + for key, raw in value.items(): + if not isinstance(key, str) or not key.isidentifier(): + raise ValueError(f"@workflow 的 allowed_templates 键 {key!r} 必须是工作流输入名") + items = [raw] if isinstance(raw, str) else raw + if not isinstance(items, (list, tuple)) or not items: + raise ValueError(f"@workflow 的 allowed_templates[{key!r}] 必须是非空的注册表资源 id 列表") + ids: list[str] = [] + for item in items: + if not isinstance(item, str) or not item.strip() or item != item.strip(): + raise ValueError(f"@workflow 的 allowed_templates[{key!r}] 里 {item!r} 不是注册表资源 id") + if item not in ids: + ids.append(item) + result[key] = ids + return result + + +def _resource_slot_schemas(schema: Any) -> list[dict[str, Any]]: + """输入 schema 里承载模板筛选的 ResourceSlot 槽位:单个、列表元素或可空成员。""" + + if not isinstance(schema, dict): + return [] + if schema.get("$slot") == "ResourceSlot": + return [schema] + found = _resource_slot_schemas(schema.get("items")) + for member in schema.get("anyOf") or []: + found.extend(_resource_slot_schemas(member)) + return found + + +def apply_allowed_templates( + input_contract: dict[str, Any], + allowed_templates: dict[str, list[str]], + *, + output_contract: dict[str, Any] | None = None, + resolve: Callable[[str], str] | None = None, +) -> tuple[dict[str, Any], dict[str, Any] | None]: + """校验并落实 ``@workflow(allowed_templates=...)``。 + + 键必须是注解为 ``ResourceSlot`` / ``List[ResourceSlot]`` 的工作流输入,否则抛 ``ValueError``(注册失败)。 + 给了 ``resolve``(注册表资源 id → 资源模板 uuid,未知 id 抛 ``ValueError``)时,把解析出的 uuid 写进该输入 + (及同名隐式输出)的 ResourceSlot schema 扩展 ``allowed_resource_template_uuids``:前端按它筛选, + 预检 / 建任务按它拒绝模板不符的物料。返回新的 ``(input_contract, output_contract)``,不改入参。 + """ + + import copy + + inputs = copy.deepcopy(input_contract) + outputs = copy.deepcopy(output_contract) if output_contract is not None else None + by_name = {item["name"]: item for item in inputs.get("parameters", [])} + for name in allowed_templates: + descriptor = by_name.get(name) + if descriptor is None: + raise ValueError(f"@workflow 的 allowed_templates 键 {name!r} 不是工作流输入") + if not _resource_slot_schemas(descriptor.get("schema")): + raise ValueError( + f"@workflow 的 allowed_templates 键 {name!r} 必须是 ResourceSlot / List[ResourceSlot] 输入" + ) + if resolve is None: + return inputs, outputs + implicit = { + item["name"]: item for item in (outputs or {}).get("outputs", []) if item.get("implicit") is True + } + for name, ids in allowed_templates.items(): + uuids: list[str] = [] + for identity in ids: + template_uuid = resolve(identity) + if template_uuid not in uuids: + uuids.append(template_uuid) + for descriptor in (by_name[name], implicit.get(name)): + if descriptor is None: + continue + descriptor["schema"] = copy.deepcopy(descriptor["schema"]) + for slot in _resource_slot_schemas(descriptor["schema"]): + slot["allowed_resource_template_uuids"] = list(uuids) + return inputs, outputs diff --git a/unilabos/registry/workflows.py b/unilabos/registry/workflows.py index cf616f02d4..51bb21ef85 100644 --- a/unilabos/registry/workflows.py +++ b/unilabos/registry/workflows.py @@ -205,6 +205,8 @@ class WorkflowDefinition: tags: List[str] fn: Callable[["WorkflowBuildContext"], Any] guide: Optional[WorkflowGuide] = None + #: ``@workflow(allowed_templates=...)``:输入名 → 允许的注册表资源 id(发布时解析成资源模板 uuid) + allowed_templates: Dict[str, List[str]] = field(default_factory=dict) def collect(self) -> "WorkflowBuildContext": """按源码静态编译出步骤及输入输出声明,不调用作者函数。""" @@ -614,6 +616,7 @@ def workflow( description: str = "", tags: Optional[Sequence[str]] = None, guide: Optional[Any] = None, + allowed_templates: Optional[Mapping[str, Any]] = None, **removed_options: Any, ): """把模块级函数注册为设备包自带的工作流模板。 @@ -628,6 +631,10 @@ def workflow( guide: 操作指引(``WorkflowGuide`` 或同形 dict):``preparation`` 运行前要在前端做的 准备(出库、挂到哪台设备哪个位点、确认设备在线……)、``expected`` 预期效果、 ``notes`` 注意事项。配合每步的 ``description`` 组成前端的"全流程"说明。 + allowed_templates: 物料输入允许的资源模板 ``{输入名: [注册表资源 id, ...]}``;输入本身照常注解为 + ``ResourceSlot`` / ``List[ResourceSlot]``(键不是这样的输入时注册失败)。发布时按注册表解析成资源 + 模板 uuid(未知 id 发布失败),写进输入 schema 的 ``allowed_resource_template_uuids``:前端据此筛选, + 预检与建任务拒绝模板不符的物料。社区包资源 id 的 ``community.<包>.`` 前缀可省略(唯一时)。 removed_options: 只接受已移除的 ``compiler``,让旧驱动包照常加载:``compiler="ast"`` 的值被忽略, 按定义告警一次;其他取值报错并提示去掉参数(规则见 ``registry/workflow_options.py``)。 """ @@ -639,9 +646,16 @@ def workflow( raise ValueError("@workflow 必须提供非空 display_name") ignored_options = ignored_workflow_options(removed_options) normalized_guide = _normalize_guide(guide) + from unilabos.registry.workflow_contract import normalize_allowed_templates + + normalized_templates = normalize_allowed_templates( + dict(allowed_templates) if isinstance(allowed_templates, Mapping) else allowed_templates + ) def decorator(fn: Callable[[WorkflowBuildContext], Any]): source_path = f"{fn.__module__}:{fn.__qualname__}" + if normalized_templates: + _check_allowed_template_inputs(fn, normalized_templates) definition = WorkflowDefinition( uuid=workflow_uuid_for(source_path), source_path=source_path, @@ -655,6 +669,7 @@ def decorator(fn: Callable[[WorkflowBuildContext], Any]): ), fn=fn, guide=normalized_guide, + allowed_templates=normalized_templates, ) if ignored_options: # 与 AST 扫描同一身份(模块:函数):同一定义在一个进程里只告警一次 @@ -671,6 +686,55 @@ def decorator(fn: Callable[[WorkflowBuildContext], Any]): return decorator +def _check_allowed_template_inputs(fn: Callable[..., Any], allowed: Dict[str, List[str]]) -> None: + """``allowed_templates`` 的键必须是 ResourceSlot / List[ResourceSlot] 输入:在装饰时就失败(注册失败)。""" + + import ast + import inspect + import textwrap + + from unilabos.registry.workflow_contract import apply_allowed_templates, parse_workflow_contract + + try: + tree = ast.parse(textwrap.dedent(inspect.getsource(fn))) + except (OSError, TypeError, SyntaxError) as exc: + raise ValueError(f"@workflow {fn.__qualname__}:allowed_templates 需要可读取的函数源码") from exc + function = next(item for item in tree.body if isinstance(item, ast.FunctionDef)) + input_contract, _outputs = parse_workflow_contract(fn, function) + try: + apply_allowed_templates(input_contract, allowed) + except ValueError as exc: + raise ValueError(f"@workflow {fn.__qualname__}:{exc}") from None + + +def resource_template_resolver(gateway: Any = None) -> Callable[[str], str]: + """注册表资源 id → 物料权威里的资源模板 uuid(模板名就是注册表资源 id)。 + + 社区包的资源 id 带 ``community.<包>.`` 前缀:精确匹配不到时按 ``.`` 结尾唯一匹配。没有物料权威、 + id 不存在或匹配到多个时抛 ``ValueError``(发布失败)。 + """ + + if gateway is None: + from unilabos.server.execution_composition import get_materials_gateway + + gateway = get_materials_gateway() + if gateway is None: + raise ValueError("工作流输入的资源模板筛选要按物料权威解析资源模板 uuid,当前进程没有物料权威") + templates = {str(item.name): str(item.template_uuid) for item in gateway.list_templates()} + + def resolve(identity: str) -> str: + if identity in templates: + return templates[identity] + matches = sorted(name for name in templates if name.endswith(f".{identity}")) + if len(matches) == 1: + return templates[matches[0]] + if not matches: + raise ValueError(f"allowed_templates 引用了注册表里没有的资源 {identity!r}") + raise ValueError(f"allowed_templates 的 {identity!r} 匹配到多个注册表资源 {matches},请写完整 id") + + return resolve + + def get_registered_workflows() -> Dict[str, WorkflowDefinition]: """返回当前进程已注册的工作流(uuid -> 定义)。""" @@ -853,6 +917,15 @@ def build_workflow_template_payload(definition: WorkflowDefinition) -> Dict[str, collected = definition.collect() steps = collected.steps + input_contract, output_contract = collected.input_contract, collected.output_contract + allowed_templates = dict(getattr(definition, "allowed_templates", None) or {}) + if allowed_templates: + from unilabos.registry.workflow_contract import apply_allowed_templates + + resolve = getattr(definition, "resolve_template", None) or resource_template_resolver() + input_contract, output_contract = apply_allowed_templates( + input_contract, allowed_templates, output_contract=output_contract, resolve=resolve + ) roles: Dict[str, Dict[str, Any]] = {} nodes: List[Dict[str, Any]] = [] for index, step in enumerate(steps): @@ -947,9 +1020,9 @@ def build_workflow_template_payload(definition: WorkflowDefinition) -> Dict[str, if unknown_resources: raise ValueError(f"资源作用域引用未声明的设备角色:{sorted(unknown_resources)}") payload["resource_scopes"] = collected.resource_scopes - if collected.input_contract["parameters"] or collected.output_contract["outputs"]: - payload["io"] = {"input_contract": collected.input_contract, - "output_contract": collected.output_contract, "output_bindings": collected.output_bindings} + if input_contract["parameters"] or output_contract["outputs"]: + payload["io"] = {"input_contract": input_contract, + "output_contract": output_contract, "output_bindings": collected.output_bindings} return payload diff --git a/unilabos/server/api/envelope.py b/unilabos/server/api/envelope.py index c44057ca9b..d73351e7d4 100644 --- a/unilabos/server/api/envelope.py +++ b/unilabos/server/api/envelope.py @@ -328,6 +328,8 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "preflight_failed", # 物料参数按库位绑定失败(库位不存在 / 为空 / 模板不符,细节在 error.details) "material_site_invalid", + # 工作流物料输入直接给的物料不是 @workflow(allowed_templates=...) 允许的模板(细节在 error.details) + "material_template_mismatch", # 库位参数按所属物料选择的写法不对(没有 Material.site 关系、放入物料不确定……,细节在 error.details) "site_selection_invalid", }) diff --git a/unilabos/server/services/runtime/workflow/authoring_compiler.py b/unilabos/server/services/runtime/workflow/authoring_compiler.py index 6e64054ef1..2f4858f81a 100644 --- a/unilabos/server/services/runtime/workflow/authoring_compiler.py +++ b/unilabos/server/services/runtime/workflow/authoring_compiler.py @@ -210,6 +210,7 @@ def _compile_graph( description=program.description, tags=program.tags, guide=None, + allowed_templates=program.allowed_templates, ) try: template = build_workflow_template_payload(definition) # type: ignore[arg-type] diff --git a/unilabos/server/services/runtime/workflow/material_sites.py b/unilabos/server/services/runtime/workflow/material_sites.py index 6ae4dae3e4..f30f3aee3e 100644 --- a/unilabos/server/services/runtime/workflow/material_sites.py +++ b/unilabos/server/services/runtime/workflow/material_sites.py @@ -8,6 +8,10 @@ 3. :func:`bind_material_sites` 把计划节点参数(含暂停改参时重新代入用的 ``entry_param_template``)与任务输入里的 ``{"site_uuid"}`` 换成占用物料的 ``{"uuid": ...}``。参数写了 ``AllowedResourceTemplates(...)`` 时核对占用物料的模板。 +工作流输入的允许模板来自 ``@workflow(allowed_templates=...)``,发布时写进输入 schema 的 +``allowed_resource_template_uuids``(:func:`input_template_allowlists`);按库位绑定与直接给 ``{"uuid"}`` 的输入都按它核对 +(后者见 :func:`check_input_material_templates`)。 + 之后它就是普通物料参数:默认共享物料锁、派发前的物料核对照旧。库位不存在、库位是空的、占用物料不是参数允许的模板 都是预检错误(:class:`MaterialSiteError`,``reason`` 分别为 ``site_not_found`` / ``site_empty`` / ``template_mismatch``),消息里写明库位与参数。 @@ -15,7 +19,7 @@ from __future__ import annotations -from collections.abc import Iterable, Mapping +from collections.abc import Callable, Iterable, Mapping, Sequence from typing import Any, Optional from unilabos.protocol.runtime.site_references import site_reference @@ -86,9 +90,53 @@ def _template_symbols(schema: Any, parameter: str) -> list[str]: return list(symbols.get(parameter) or []) +def input_template_allowlists(contract: Optional[Mapping[str, Any]]) -> dict[str, list[str]]: + """工作流输入合同里各物料输入允许的资源模板 uuid(ResourceSlot schema 的 ``allowed_resource_template_uuids``)。""" + + from .handle_projection import resource_slot_schema + + allowlists: dict[str, list[str]] = {} + for descriptor in (contract or {}).get("parameters") or []: + slot = resource_slot_schema(descriptor.get("schema") or {}) + uuids = (slot or {}).get("allowed_resource_template_uuids") + if uuids: + allowlists[str(descriptor["name"])] = [str(item) for item in uuids] + return allowlists + + +def _template_mismatch(where: str, material: str, template_name: Any, allowed: Iterable[str]) -> str: + return (f"{where}:物料 {material}(模板 {template_name})不是允许的资源模板" + f"({'、'.join(str(item) for item in allowed)})") + + +def check_input_material_templates( + input_value: Optional[Mapping[str, Any]], allowlists: Mapping[str, Sequence[str]], + template_of: Callable[[str], Mapping[str, Any]], +) -> None: + """直接给 ``{"uuid"}`` 的工作流物料输入按允许模板核对;``template_of(物料 uuid)`` 给 ``template_uuid`` / ``template_name``。 + + 按库位绑定的输入在 :func:`bind_material_sites` 里按同一份允许模板核对;不符抛 :class:`MaterialSiteError` + (``reason=template_mismatch``,``site_uuid`` 为空,``details`` 带 ``material_uuid``)。 + """ + + for name, allowed in allowlists.items(): + for item in _values((input_value or {}).get(name)): + if not isinstance(item, Mapping) or not isinstance(item.get("uuid"), str) or site_reference(item): + continue + facts = template_of(item["uuid"]) + if str(facts.get("template_uuid") or "") not in allowed: + error = MaterialSiteError( + TEMPLATE_MISMATCH, + _template_mismatch(f"工作流输入 {name}", item["uuid"], facts.get("template_name"), allowed), + parameter=name, site_uuid="", + ) + error.details["material_uuid"] = item["uuid"] + raise error + + def resolve_site_material( facts: Mapping[str, Any], site_uuid: str, *, parameter: str, node_uuid: Optional[str] = None, - template_symbols: Iterable[str] = (), + template_symbols: Iterable[str] = (), template_uuids: Iterable[str] = (), ) -> dict[str, str]: """一个 ``{"site_uuid"}`` → 占用物料的 ``{"uuid"}``;库位不存在 / 为空 / 模板不符时抛 :class:`MaterialSiteError`。""" @@ -114,22 +162,31 @@ def resolve_site_material( f"(模板 {occupant.get('template_name')})不是参数允许的资源模板({'、'.join(symbols)})", parameter=parameter, site_uuid=site_uuid, node_uuid=node_uuid, ) + allowed = list(template_uuids) + if allowed and str(occupant.get("template_uuid") or "") not in allowed: + raise MaterialSiteError( + TEMPLATE_MISMATCH, + _template_mismatch(f"{where} 按库位 {label} 绑定物料", occupant.get("material_uuid"), + occupant.get("template_name"), allowed), + parameter=parameter, site_uuid=site_uuid, node_uuid=node_uuid, + ) return {"uuid": str(occupant["material_uuid"])} def _bind_param( param: dict[str, Any], facts: Mapping[str, Any], *, node_uuid: Optional[str], schema: Any, - bindings: list[dict[str, Any]], + bindings: list[dict[str, Any]], allowlists: Optional[Mapping[str, Sequence[str]]] = None, ) -> None: for name, value in list(param.items()): symbols = _template_symbols(schema, name) + uuids = list((allowlists or {}).get(name) or []) def bind(item: Any) -> Any: site = site_reference(item) if site is None: return item material = resolve_site_material(facts, site, parameter=name, node_uuid=node_uuid, - template_symbols=symbols) + template_symbols=symbols, template_uuids=uuids) record = {"parameter": name, "site_uuid": site, "material_uuid": material["uuid"]} if node_uuid is not None: record["node_uuid"] = node_uuid @@ -154,11 +211,13 @@ def bind_param_sites( def bind_material_sites( plan: Optional[dict[str, Any]], input_value: Optional[dict[str, Any]], facts: Mapping[str, Any], + *, input_contract: Optional[Mapping[str, Any]] = None, ) -> list[dict[str, Any]]: """就地把计划与任务输入里的 ``{"site_uuid"}`` 换成占用物料 ``{"uuid"}``,返回绑定记录。 计划节点的 ``param`` 与 ``entry_param_template``(暂停改参时按它重新代入)一起换;任务输入里的同形值也换, 改参后重新代入的仍是冻结的物料。绑定记录写进计划的 ``material_site_bindings``(追溯用)。 + ``input_contract`` 给了时任务输入按其中的允许模板(:func:`input_template_allowlists`)核对占用物料。 """ bindings: list[dict[str, Any]] = [] @@ -169,7 +228,8 @@ def bind_material_sites( if isinstance(template, dict): _bind_param(template, facts, node_uuid=node["uuid"], schema=schema, bindings=[]) if input_value is not None: - _bind_param(input_value, facts, node_uuid=None, schema=None, bindings=bindings) + _bind_param(input_value, facts, node_uuid=None, schema=None, bindings=bindings, + allowlists=input_template_allowlists(input_contract)) if plan is not None and bindings: plan["material_site_bindings"] = bindings return bindings @@ -186,6 +246,8 @@ def bind_jobs(plan: Mapping[str, Any], jobs: Iterable[dict[str, Any]]) -> None: __all__ = [ "MaterialSiteError", + "check_input_material_templates", + "input_template_allowlists", "SITE_EMPTY", "SITE_NOT_FOUND", "TEMPLATE_MISMATCH", diff --git a/unilabos/server/services/runtime/workflow/run_preflight.py b/unilabos/server/services/runtime/workflow/run_preflight.py index 233f702fe7..0c55640388 100644 --- a/unilabos/server/services/runtime/workflow/run_preflight.py +++ b/unilabos/server/services/runtime/workflow/run_preflight.py @@ -79,7 +79,8 @@ def check(kind: str, status: str, code: str, message: str, *, node=None, details raise ValueError("运行模式无效") if expected_revision is not None and expected_revision != graph["workflow"]["revision"]: raise ValueError("工作流修订已变化,请刷新后重新预检") - resolved = resolve_task_input(declared_input_contract(graph["workflow"]), input_value) + input_contract = declared_input_contract(graph["workflow"]) + resolved = resolve_task_input(input_contract, input_value) plan, _jobs = service._build_execution_plan( graph, run_mode=run_mode, target_node_uuid=target_node_uuid, entry_input=resolved, ) @@ -107,12 +108,20 @@ def check(kind: str, status: str, code: str, message: str, *, node=None, details check("inventory", "passed", "inventory_bindings_applied", "库存绑定已对应到计划中的库存需求", details={"bindings": bindings}) # 按库位绑定的物料参数({"site_uuid"}):与建任务同一条解析路径,换成此刻占着库位的物料 - from .material_sites import MaterialSiteError, bind_material_sites, read_site_facts, site_references + from .material_sites import ( + MaterialSiteError, + bind_material_sites, + check_input_material_templates, + input_template_allowlists, + read_site_facts, + site_references, + ) references = site_references([resolved, *(node.get("param") or {} for node in plan["nodes"])]) if references: try: - site_bindings = bind_material_sites(plan, dict(resolved), read_site_facts(materials, references)) + site_bindings = bind_material_sites(plan, dict(resolved), read_site_facts(materials, references), + input_contract=input_contract) except MaterialSiteError as error: node = next((item for item in plan["nodes"] if item["uuid"] == error.details.get("node_uuid")), None) check("resources", "blocked", "invalid_material_site", error.message, node=node, details=error.details) @@ -122,6 +131,17 @@ def check(kind: str, status: str, code: str, message: str, *, node=None, details return finalize(report) check("resources", "passed", "material_sites_bound", "按库位绑定的物料参数已解析为库位上的物料", details={"bindings": site_bindings}) + # 直接给 {"uuid"} 的工作流物料输入:按 @workflow(allowed_templates=...) 核对模板(按库位绑定的已在上面核对) + allowlists = input_template_allowlists(input_contract) + if allowlists and materials is not None: + try: + check_input_material_templates(resolved, allowlists, lambda identity: material_template_facts(materials, identity)) + except MaterialSiteError as error: + check("resources", "blocked", "invalid_material_template", error.message, details=error.details) + return finalize(report) + except (RuntimeError, OSError) as error: + check("resources", "blocked", "material_template_unavailable", f"无法读取工作流物料输入的模板:{error}") + return finalize(report) # 按所属物料选择的库位参数({"owner_uuid"}):任务准入时才选定并预留,这里只读候选 from .site_selections import SiteSelectionError, check_owner_sites, owner_site_requests, read_owner_facts @@ -240,6 +260,14 @@ def check(kind: str, status: str, code: str, message: str, *, node=None, details return finalize(report) +def material_template_facts(materials: Any, identity: str) -> dict[str, Any]: + """物料的模板事实(``template_uuid`` / ``template_name``),供工作流物料输入的模板核对。""" + + material = materials.get_material(identity).material + template_uuid = str(material.template_uuid or "") + return {"template_uuid": template_uuid, "template_name": getattr(material, "template_name", None) or template_uuid} + + def finalize(report: dict[str, Any]) -> dict[str, Any]: checks = report["checks"] for status in ("passed", "blocked", "deferred", "confirmation_required"): diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 02441ea8f7..2ddd9f2565 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -156,6 +156,7 @@ ), "site_binding_invalid": (422, "工作流 Site 绑定未完成"), "material_site_invalid": (422, "物料参数按库位绑定失败"), + "material_template_mismatch": (422, "工作流物料输入不是允许的资源模板"), "site_selection_invalid": (422, "库位参数按所属物料选择失败"), "invalid_composite_child_type": (400, "只有实验操作可以作为子工作流被引用"), "invalid_composite_child_status": (409, "被引用的实验操作当前修订尚未发布"), @@ -1507,7 +1508,10 @@ def create_workflow_task( return existing resolved: Dict[str, Dict[str, Any]] = {} # 按库位绑定的物料参数({"site_uuid"})同样在事务外读库位事实,事务内换成占用物料并冻结 - site_facts = self._material_site_facts(self.get_graph(workflow_uuid), input_value) + current_graph = self.get_graph(workflow_uuid) + site_facts = self._material_site_facts(current_graph, input_value) + # 直接给 {"uuid"} 的工作流物料输入按 @workflow(allowed_templates=...) 核对模板(同样在事务外读物料库) + self._check_input_material_templates(current_graph, input_value) # 绑定指向的库存实例在建任务事务外读取(物料库是另一个权威,不在 runtime 写锁内访问); # 事务内按冻结计划把绑定落到对应需求,不匹配即拒绝建任务。 binding_sources: Optional[Dict[str, Dict[str, Any]]] = {} @@ -1528,7 +1532,8 @@ def build_plan(graph: Dict[str, Any]) -> Any: entry_input=resolved["input"], ) # 按库位绑定的物料参数解析成占用物料,计划、attempt 参数与任务输入一起冻结 - self._bind_material_sites(plan, jobs, resolved["input"], site_facts) + self._bind_material_sites(plan, jobs, resolved["input"], site_facts, + input_contract=declared_input_contract(graph["workflow"])) # 按所属物料选择的库位参数在任务准入时由调度器选定;写法不对(没有 Material.site 关系、放入物料不确定、 # 与所属物料参数不一致)建任务时就拒绝 self._check_site_selections(plan) @@ -1596,15 +1601,40 @@ def _material_site_facts( except (RuntimeError, OSError) as exc: raise WorkflowError("invalid_input", detail=f"无法读取按库位绑定的库位:{exc}") from None + def _check_input_material_templates( + self, graph: Optional[Dict[str, Any]], input_value: Optional[Dict[str, Any]], + ) -> None: + """工作流物料输入直接给 ``{"uuid"}`` 时按允许模板核对;按库位绑定的在 :meth:`_bind_material_sites` 里核对。""" + + from .material_sites import MaterialSiteError, check_input_material_templates, input_template_allowlists + from .run_preflight import material_template_facts + + if graph is None or not input_value: + return + try: + allowlists = input_template_allowlists(declared_input_contract(graph["workflow"])) + except EntryParameterError as exc: + raise WorkflowError("invalid_input", detail=str(exc)) from None + if not allowlists or self._preflight_materials is None: + return + try: + check_input_material_templates( + input_value, allowlists, lambda identity: material_template_facts(self._preflight_materials, identity) + ) + except MaterialSiteError as exc: + raise WorkflowError("material_template_mismatch", detail=exc.message, details=exc.details) from None + except (RuntimeError, OSError) as exc: + raise WorkflowError("invalid_input", detail=f"无法读取工作流物料输入的模板:{exc}") from None + @staticmethod def _bind_material_sites( plan: Dict[str, Any], jobs: List[Dict[str, Any]], input_value: Optional[Dict[str, Any]], - facts: Dict[str, Dict[str, Any]], + facts: Dict[str, Dict[str, Any]], *, input_contract: Optional[Dict[str, Any]] = None, ) -> None: from .material_sites import MaterialSiteError, bind_jobs, bind_material_sites try: - if bind_material_sites(plan, input_value, facts): + if bind_material_sites(plan, input_value, facts, input_contract=input_contract): bind_jobs(plan, jobs) except MaterialSiteError as exc: raise WorkflowError("material_site_invalid", detail=exc.message, details=exc.details) from None From 62b60966b4c104d44ce997ed94337ce8089c9f42 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:02:59 +0800 Subject: [PATCH 07/27] docs(action-standard): redesign Material as declared material actions Material declares the real material actions of an action: move, two-step pick / place and dispense, with sites given as SiteSlot (site uuid), the owner derived from the site and the carrier a DeviceSlot defaulting to the executing device. Device tenancy, in-place checks, the site picker hint and order sensitivity stay in material= as experimental. Parameters are locked by type (ResourceSlot material lock, DeviceSlot device lock, SiteSlot site lock); Material.uses is removed. Also document how declared Material relates to the runtime materials helpers: a declared move is settled by the core, so the driver must not also transfer / assign the same material. Record the one-time incompatible change and the old-to-new mapping. --- docs/developer_guide/action_standard.md | 166 +++++++++++++++++++----- 1 file changed, 130 insertions(+), 36 deletions(-) diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index ed1a3dcbe2..2816137457 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -16,8 +16,8 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) | `x: X = None`(默认值是 `None`) | 同 `Optional[X]` | 严格 | | `Annotated[X, Field(ge=, le=, min_length=, max_length=, title=, description=)]` | 带范围与说明 | 严格 | | `ResourceSlot` / `list[ResourceSlot]` | 物料引用 `{"uuid": ...}`(或按库位绑定的 `{"site_uuid": ...}`,准入时解析),加物料锁 | 严格;Host 解析成物料实例 | -| `DeviceSlot` / `SiteSlot` | 设备 ID / 库位 UUID 字符串 | 严格 | -| `SiteSlot` 且写了 `material=Material.site("site", owner=...)` | 库位 UUID(或按所属物料选择的 `{"owner_uuid": ...}`,准入时选定),带库位关系(`x-unilabos-site-selector`) | 严格;预检与派发前核对库位归属与占用 | +| `DeviceSlot` / `SiteSlot` | 设备 ID / 库位 UUID 字符串(字段带 `x-unilabos-slot: "device"` / `"site"`),加设备锁 / 库位锁 | 严格 | +| `SiteSlot` 且写了 `material=Material.site_picker("site", of=...)` | 库位 UUID(或按所属物料选择的 `{"owner_uuid": ...}`,准入时选定),带库位关系(`x-unilabos-site-selector`) | 严格;预检与派发前核对库位归属与占用 | | `dict`、`Dict[str, Any]`、`Mapping` | 任意 JSON 对象 | 只校验是对象 | | 没写注解、`Any`、`object` | 任意 JSON 值(`{}`) | 不限值 | | 严格解析器不认识的注解(`Union[int, str]`、`List[Optional[float]]`、枚举、PLR / pydantic 类型……) | 退回注册表原来的签名类型推断 | 按推断结果;推断不出的部分接受任意值 | @@ -95,41 +95,113 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 ## 资源语义:`material=` -一个动作对物料 / 设备的语义只用 `@action` 的一个字段声明,值是 `Material` 的一个方法调用,多个语义写成列表。 -字符串都是动作的参数名,注册时对照签名检查(参数不存在、物料参数不是 `ResourceSlot` 都会注册失败)。 +`Material` 声明的是动作**真实的物料动作**:搬运一件容器、两步搬运、在容器之间转移内容物。调度器在派发前按它解析 +来源、目标与搬运设备,动作成功后由核心一次结算物料位置 / 内容物(`PhysicalMove` / 搬运回执、`AliquotReceipt`)。 +不代表物料动作的声明(跨动作的设备独占、原位检查、库位选择器提示、顺序约束)仍然写在 `material=` 里,但属于 +**实验性**功能:注册时按定义告警一次「实验性功能」,语义与写法以后可能调整。 + +一个动作的语义只用 `@action` 的这一个字段声明,值是 `Material` 的一个方法调用,多个语义写成列表。 +字符串参数都是动作的参数名,注册时对照签名检查参数存在、类型正确: + +| 角色 | 参数类型 | 值 | +| --- | --- | --- | +| 物料(`material`、`from_material`、`to_materials`、`for_material`) | `ResourceSlot`(`to_materials` 可以是多个参数) | 物料引用;`ResourceSlot` 不能指向设备 | +| 库位(`to_site`、`from_site`、`site_picker` 的库位参数) | `SiteSlot` | 库位 uuid | +| 设备(`carrier_device`、`device`、`from_device`) | `DeviceSlot` | 设备 id;省略就是**执行设备** | ```python from unilabos.registry.decorators import Material, action -from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="装载样品", material=Material.load("sample", device="vessel")) -def load_sample(self, sample: ResourceSlot, vessel: str) -> CustodyResult: ... +@action(display_name="搬运板", material=Material.move("plate", to_site="target_site")) +def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="原位处理", material=[Material.in_place("sample"), Material.order_sensitive()]) -def stir(self, sample: ResourceSlot) -> None: ... +@action(display_name="抓取", material=Material.pick("plate")) +def pick_plate(self, plate: ResourceSlot) -> dict: ... + +@action(display_name="放下", material=Material.place("plate", to_site="target_site")) +def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... + +@action(display_name="移液", material=Material.dispense(from_material="source", to_materials=["target"])) +def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... ``` +### 物料动作(稳定) + +| 写法 | 含义 | 内部合同字段 | +| --- | --- | --- | +| `Material.move("plate", to_site="target_site", from_site=None, carrier_device=None)` | 一个动作把容器搬到 `to_site` | `transfer` | +| `Material.pick("plate", from_site=None, carrier_device=None)` | 两步搬运第一步:从来源库位抓到搬运设备的夹爪库位 | `transfer_step`(pick) | +| `Material.place("plate", to_site="target_site", carrier_device=None)` | 两步搬运第二步:从夹爪库位放到 `to_site` | `transfer_step`(place) | +| `Material.dispense(from_material="source", to_materials=["target", ...])` | 按驱动回报的实际量,在容器之间转移内容物 | `aliquot`(`AliquotReceipt`) | + +- **所属方由库位决定**:`to_site` / `from_site` 是库位 uuid,调度器向物料权威读出库位的所属方——可以是载架 + (仓库、板位……),也可以是设备根节点(设备自身的库位),不再单独写所属物料参数。 +- **来源**:`from_site` 省略时用物料权威记录的当前位置;给出时必须和权威一致,不一致时动作排队等待 + (`wait_reason.code=transfer_source_site_missing`),物料被规划后挪走则进入动作执行前预检决策。 +- **搬运设备**:`carrier_device` 省略时就是执行设备;写了就必须是 `DeviceSlot` 参数(值是设备 id,调度器解析成该设备的物料)。 + 搬运途中物料在搬运设备角色为 `gripper` 的夹爪库位上:设备的 `available_sites` 里必须有且只有一个可见的、 + `meta_data.role == "gripper"` 的库位。`move` 期间这个库位被预留、夹爪必须空着(或正夹着要搬的这件物料), + 动作成功后物料直接结算到 `to_site`。 +- **两步搬运**:`pick` 成功后物料在夹爪库位上,任务托管搬运设备(跨动作的设备独占,其他任务不能用它);`place` 要求物料 + 仍在同一夹爪库位上,成功后物料在 `to_site`、夹爪库位空出、托管释放。`pick` 的 `from_site` 省略时从权威当前位置抓取。 +- **分装 / 移液**:`dispense` 的来源与每个目标都是 `ResourceSlot`;驱动按实际量回报 `AliquotReceipt`,核心按回执结算内容物。 + 语义与以前的 `Material.aliquot` 完全相同,只是改名。 +- 这几种都会锁住涉及的物料(物料锁)与来源 / 目标库位所属的设备(设备锁);`move` / `pick` / `place` 之间不能组合 + (一个动作只能有一种搬运声明),`dispense` 可以与它们之外的实验性声明同时写。 +- 物料的**消耗 / 新建**这次不做声明式写法:消耗仍然用工作流节点上的 `inventory=`,新建仍在驱动里调用 `materials.create`(见下节)。 + +### 声明式 `Material` 与运行时 `materials` 的分工 + +两者都会改变物料权威里的事实,但时机和归属不同: + +| | 声明式 `Material`(`registry/material_roles.py`) | 运行时 `materials`(`unilabos.resources.materials`) | +| --- | --- | --- | +| 写在哪里 | `@action(material=...)` | 驱动代码里,动作执行时调用 | +| 谁读 / 谁执行 | 调度器派发前读:解析来源、目标、搬运设备,加锁、预留库位;动作成功后**核心**结算 | 驱动直接调用,立即改权威 | +| 典型操作 | `move` / `pick` / `place`(`PhysicalMove` / 搬运回执)、`dispense`(`AliquotReceipt`) | `create` / `ensure` / `get` / `search` / `resolve` / `assign` / `update` / `remove` / `snapshot` / `transfer` / `apply_substances` …… | + +规则: + +- 用 `Material.move` / `pick` / `place` 声明了的搬运,物料位置由核心按搬运回执结算;驱动**不能**再对同一件物料调用 + `materials.transfer` / `materials.assign`(会重复写位置,与核心的结算冲突)。驱动只负责物理动作并按需返回回执。 +- `dispense` 声明了的内容物转移由核心按 `AliquotReceipt` 结算;驱动不再对同一来源 / 目标手动写内容物。 +- `materials.*` 只用于**没有声明**的运行时变化:新建物料(`create`)、写内容物(`apply_substances`,用于没有 `dispense` 的动作)、 + 删除(`remove`)、启动时对齐(`ensure`)、查询(`get` / `search` / `resolve` / `snapshot`)等。 +- `create` / `ensure` 这次没有声明式对应写法。 + +### 实验性声明 + +仍然写在 `material=` 里;注册时按定义告警一次「实验性功能」。 + | 写法 | 含义 | 内部合同字段 | | --- | --- | --- | -| `Material.load("sample", device="vessel")` | 装进设备,任务托管设备直到卸载 | `device_tenancy`(取得设备) | -| `Material.unload("sample", device="vessel")` | 从设备取出,结束托管 | `device_tenancy`(释放设备) | -| `Material.load("sample", device="b", from_device="a")` | 设备间转移:从 a 转到 b | `device_tenancy`(取得 b、释放 a) | -| `Material.in_place("sample")` | 物料必须仍在执行设备内 | `operate_in_place` | -| `Material.pick("sample", owner="owner", site="site", carriers=["carrier"])` | 搬运第一步:抓到搬运器 | `transfer_step`(pick) | -| `Material.place("sample", owner="owner", site="site", carriers=["carrier"])` | 搬运第二步:放到目标库位 | `transfer_step`(place) | -| `Material.transfer("plate", to="target", site="site", gripper="arm.gripper", source=..., source_site=..., source_site_name=..., site_name=..., motion=[...], tools=[...])` | 一次完成的机械臂搬运 | `transfer` | -| `Material.aliquot(source="source", targets=["target"])` | 按实测量从来源分装到全部目标 | `aliquot` | -| `Material.uses(device=[...], tool=[...], motion=[...], site=[...], material=[...])` | 动作还占用这些资源参数 | `resource_params`(取代 `required_device_params`) | +| `Material.load("sample", device=None, from_device=None)` | 装进设备,任务托管设备直到卸载;`from_device` 同时从另一台设备转出 | `device_tenancy`(取得设备,可同时释放 `from_device`) | +| `Material.unload("sample", device=None)` | 从设备取出,结束托管 | `device_tenancy`(释放设备) | +| `Material.in_place("sample")` | 物料必须仍在执行设备内(由之前的 `load` 托管着) | `operate_in_place` | +| `Material.site_picker("site", of=None, for_material=None, occupied="show")` | 前端库位选择器提示:库位参数 `site` 列出 `of` 的库位 | 不进资源合同:写进 `site` 参数 schema 的 `x-unilabos-site-selector` | | `Material.order_sensitive()` | 同一资源上的兄弟动作必须显式排序(只约束计划) | `order_sensitive` | -| `Material.site("site", owner="carrier", occupant="sample", show_occupied=True, allow_occupied=False)` | 库位参数 `site` 属于物料参数 `carrier`,放进去的是 `sample`;已占用的库位是否列出 / 能否选 | 不进资源合同:写进 `site` 参数 schema 的 `x-unilabos-site-selector` | -同一个合同字段只能出现一次(例如 `load` 与 `unload` 不能写在同一个动作上,设备间转移用 `from_device=`); -`uses` 可以和其他语义同时写。内部仍规范化成第 2 版资源合同,调度器按它执行托管、搬运与分装结算。 +- `load` / `unload` 的 `device` / `from_device` 是 `DeviceSlot` 参数,省略就是执行设备;语义与以前相同(设备间转移用 + `from_device=`;`load` 与 `unload` 不能写在同一个动作上)。 +- 同一个合同字段只能出现一次。内部仍规范化成第 2 版资源合同,调度器按它执行托管、搬运与分装结算。 + +### 按类型加锁 + +参数一律按**类型**校验与加锁,不再按动作声明额外占用(`Material.uses` 已删除): + +| 参数类型 | 锁 | +| --- | --- | +| `ResourceSlot` / `list[ResourceSlot]`(以及选择器为 `unilabos_resources` 的参数) | 物料锁(现状) | +| `DeviceSlot` / `list[DeviceSlot]` | 设备锁:值是设备 id,派发前核对它是已登记的设备,与该设备上正在执行的动作互斥 | +| `SiteSlot` | 库位锁:值是库位 uuid,按「所属物料 + 库位」加锁;值不是已登记的库位 uuid(例如库位名)时不加锁 | + +空值(`None` / `""` / `[]`)不加锁。`always_free` 只免除执行设备自身的动作锁,按类型加的设备锁 / 库位锁照旧。 -### 库位参数:`SiteSlot` 与 `Material.site` +### 库位参数:`SiteSlot` 与 `Material.site_picker`(实验性) -库位参数只有一个类型 `SiteSlot`(值是库位 UUID,前端用库位选择器填写)。库位属于哪个物料、放进去的是哪个物料、 -已占用的库位怎么处理,属于资源语义,写在 `material=` 里: +库位参数只有一个类型 `SiteSlot`(值是库位 UUID,前端用库位选择器填写)。选择器列出哪个所属方的库位、放进去的是哪件物料、 +已占用的库位怎么处理,写在 `Material.site_picker`: ```python from unilabos.registry.decorators import Material, action @@ -137,23 +209,27 @@ from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot @action( display_name="放到库位", - material=Material.site("site", owner="carrier", occupant="sample", allow_occupied=False), + material=Material.site_picker("site", of="carrier", for_material="sample", occupied="show"), ) def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = None) -> None: ... ``` -- `site` 必须注解为 `SiteSlot`(可空写法 `SiteSlot = None` / `Optional[SiteSlot]` 也行);`owner` 必填,`occupant` 可省略; - `owner` / `occupant` 必须是单个 `ResourceSlot` 参数。写错在注册时报错。 -- `show_occupied`(默认 `True`)决定前端是否列出已占用的库位,`allow_occupied`(默认 `False`)决定已占用的库位能否选; - 运行预检与派发前核对所选库位属于 `owner`,且(不允许占用时)没有被 `occupant` 以外的物料占着。 -- 只写 `SiteSlot`、不写 `Material.site` 的参数照旧是库位选择器,只是没有这层关系的核对。 +- `site` 必须注解为 `SiteSlot`(可空写法 `SiteSlot = None` / `Optional[SiteSlot]` 也行)。 +- `of` 是所属方:单个 `ResourceSlot`(所属物料)或 `DeviceSlot`(所属设备的根节点)参数;省略时是执行设备的根节点。 +- `for_material` 是要放进这个库位的物料参数(单个 `ResourceSlot`,可省略)。 +- `occupied`:`"hide"` 不列出已占用的库位,`"show"`(默认)列出但不能选,`"allow"` 列出且能选。 + 运行预检与派发前核对所选库位属于所属方,且(不是 `"allow"` 时)没有被 `for_material` 以外的物料占着。 +- 生成的 `x-unilabos-site-selector` 扩展形状不变:`{"version": 1, "owner": , "occupant": , + "show_occupied": ..., "allow_occupied": ...}`;`of` 省略时 `owner` 为 `null`(执行设备根节点),`of` 是 `DeviceSlot` + 参数时它的值是设备 id。 +- 只写 `SiteSlot`、不写 `Material.site_picker` 的参数照旧是库位选择器,只是没有这层关系的核对。 #### 按所属物料选库位:`{"owner_uuid": ...}` -带 `Material.site` 关系的库位参数(以及工作流入口参数里的 `SiteSlot`)可以不给库位 uuid,而给 +带 `Material.site_picker` 关系的库位参数(以及工作流入口参数里的 `SiteSlot`)可以不给库位 uuid,而给 `{"owner_uuid": "<所属物料 uuid>"}`,由调度器在**任务准入**时挑一个库位: -- 候选是所属物料下(可见的)库位里,接收规则接受放入物料(`Material.site` 的 `occupant` 参数;它按库位绑定时先解析)的: +- 候选是所属物料下(可见的)库位里,接收规则接受放入物料(`site_picker` 的 `for_material` 参数;它按库位绑定时先解析)的: 库位模板白名单(`extra.allowed_resource_template_uuids`,6008 那一条)与 `allowed_resource_categories`(放入物料模板的 `category` 要与它相交)都满足,空列表表示不限。按库位序号选第一个空着、没有活动入口预留、没有未结算物理动作占着的。 - 选中后用物料权威的入口预留占住(`POST /api/v1/inventory/ingress-reservations` 的 `owner_material_uuid` 写法, @@ -165,9 +241,9 @@ def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = No (`stage=preflight`、`reason=no_acceptable_site`,`details` 带参数、节点、所属物料);运行预检给 `invalid_site_selection`。 接受的库位此刻都被占着或已被预留是临时条件:任务保持 `pending` 排队,attempt 的 `wait_reason.code=site_group_unavailable`, 有任务结束或 5 秒兜底重算时按创建先后重试;运行预检给 `site_selection_unavailable`(可以提交,提交后排队)。 -- 写法本身不对时建任务就拒绝(`error.code=site_selection_invalid`,`error.details.reason`):参数没有 `Material.site` 关系 - (`no_site_relation`)、关系没有声明 `occupant`(`occupant_undeclared`)、放入物料在建任务时不确定(来自上游结果, - `occupant_unknown`)、与 `owner` 参数给的物料不一致(`owner_mismatch`)。 +- 写法本身不对时建任务就拒绝(`error.code=site_selection_invalid`,`error.details.reason`):参数没有 `Material.site_picker` 关系 + (`no_site_relation`)、关系没有声明 `for_material`(`occupant_undeclared`)、放入物料在建任务时不确定(来自上游结果, + `occupant_unknown`)、与 `of` 参数给的物料不一致(`owner_mismatch`)。 - 给精确的库位 uuid 照旧,不经过选择与预留。 ## 前端选择器:`placeholder_keys` @@ -222,10 +298,28 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | `@action(contract="typed")` / `contract="legacy"` | 去掉:所有 JSON 动作同一标准 | | `@action(resource_contract={...})` | `@action(material=Material.xxx(...))`,对照表见上 | | `Annotated[T, Placeholder(PLACEHOLDER_...)]`(`unilabos.registry.annotations.Placeholder`) | `@action(placeholder_keys={"参数名": PLACEHOLDER_...})`,参数照常注解为 `T` | -| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(material=Material.site("参数名", owner=..., occupant=..., show_occupied=..., allow_occupied=...))`;生成的 schema 扩展与以前相同 | +| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(material=Material.site_picker("参数名", of=..., for_material=..., occupied=...))`;生成的 schema 扩展与以前相同 | | JSON 动作的 `@action(goal={...})` / `result={...}` 重命名 | 去掉:字段名就是参数名 / 返回 TypedDict 的字段名(要改名就改参数名) | | 按名字注入的动作上下文:参数叫 `action_context` 但没有 `ActionContext` 注解 | 注解为 `Optional[ActionContext]`(`from unilabos.client.host.runtime.action import ActionContext`),名字随意;没有注解的 `action_context` 参数注册时报错(自动动作同样) | +### `Material` 辅助 API 重做(一次性不兼容) + +`Material` 改为声明真实的物料动作(见「资源语义」)。下面的旧写法在装饰器(导入时)与注册表 AST 扫描里都直接报错, +错误信息给出新写法;不做转换。 + +| 删除的写法 | 新写法 | +| --- | --- | +| `Material.transfer("plate", to="owner", site="site" \| site_name="site", gripper="arm.gripper", source=..., source_site=..., source_site_name=..., motion=..., tools=...)` | `Material.move("plate", to_site="site", from_site=None, carrier_device=None)`:库位参数改成 `SiteSlot`(值是库位 uuid),所属方由库位决定,不写 `to` / `source`;搬运设备的夹爪库位角色统一为 `gripper`,不写 `gripper=`;`motion` / `tools` 去掉(设备参数按类型加锁) | +| `Material.pick("plate", owner="owner", site="site", carriers=["carrier"])` | `Material.pick("plate", from_site=None, carrier_device=None)`:搬运设备是 `DeviceSlot` 参数,省略即执行设备 | +| `Material.place("plate", owner="owner", site="site", carriers=["carrier"])` | `Material.place("plate", to_site="site", carrier_device=None)` | +| `Material.aliquot(source="source", targets=["target"])` | `Material.dispense(from_material="source", to_materials=["target"])`(语义不变) | +| `Material.site("site", owner="carrier", occupant="sample", show_occupied=..., allow_occupied=...)` | `Material.site_picker("site", of="carrier", for_material="sample", occupied="hide" \| "show" \| "allow")`(`show_occupied=False` → `"hide"`;`allow_occupied=True` → `"allow"`;其余 → `"show"`) | +| `Material.uses(device=[...], tool=[...], motion=[...], site=[...], material=[...])` | 删除:参数按类型加锁(`ResourceSlot` 物料锁、`DeviceSlot` 设备锁、`SiteSlot` 库位锁),把参数注解成对应类型即可 | +| `Material.load("sample", device="vessel")`(`vessel` 是 `str` / `ResourceSlot`) | `vessel` 注解为 `DeviceSlot`;装进执行设备本身时省略 `device=` | + +行为上的变化:`DeviceSlot` / `SiteSlot` 参数现在默认加设备锁 / 库位锁;`load` / `unload` / `in_place` / `site_picker` / +`order_sensitive` 注册时告警一次「实验性功能」。 + 行为上的变化: - 以前的普通动作不校验参数,必填参数缺了会被 `goal_default` 补成 0 / 空串;现在缺了直接报错。 From e95406373ce3c503a02b9ec4e3f590b34f43561d Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:18 +0800 Subject: [PATCH 08/27] feat(registry)!: declare material actions with Material.move / pick / place / dispense Material now declares the real material actions of an action: - Material.move(material, *, to_site, from_site=None, carrier_device=None) normalizes to the transfer contract with no owner parameters (the owner is derived from the site uuid), gripper role "gripper" and an optional carrier_device_param; - Material.pick / place(material, *, from_site / to_site, carrier_device) normalize to transfer_step with an empty owner and an empty carrier list meaning the executing device; - Material.dispense(*, from_material, to_materials) is the old aliquot. Device tenancy, in-place checks, the site picker hint (Material.site_picker, occupied="hide" | "show" | "allow", the x-unilabos-site-selector shape unchanged, owner may be a DeviceSlot or null for the executing device) and order sensitivity stay in material= and warn once per definition as experimental. load / unload take DeviceSlot devices and default to the executing device ("$executor" in the contract). Registration checks every referenced parameter against the signature in both the decorator and the AST scan: materials are ResourceSlot, sites SiteSlot, devices DeviceSlot. Material.transfer / aliquot / site / uses and pick / place with owner / site / carriers fail with the new spelling. DeviceSlot / SiteSlot fields carry x-unilabos-slot so the scheduler can lock them by type; the AST cache version is bumped. --- .../registry/test_action_resource_contract.py | 259 +++++---- tests/registry/test_backend_metadata.py | 2 +- tests/registry/test_site_selector_contract.py | 49 +- unilabos/protocol/runtime/site_references.py | 2 +- unilabos/registry/action_contract_schema.py | 4 +- unilabos/registry/action_options.py | 13 +- unilabos/registry/action_resource_contract.py | 157 +++--- unilabos/registry/action_schema.py | 50 +- unilabos/registry/ast_registry_scanner.py | 14 +- unilabos/registry/decorators.py | 81 ++- unilabos/registry/material_roles.py | 490 ++++++++++++------ unilabos/registry/registry.py | 2 +- unilabos/registry/site_selector_schema.py | 27 +- .../registry/site_selector_value_schema.py | 14 +- 14 files changed, 782 insertions(+), 382 deletions(-) diff --git a/tests/registry/test_action_resource_contract.py b/tests/registry/test_action_resource_contract.py index 761bdb4d8e..505c44df50 100644 --- a/tests/registry/test_action_resource_contract.py +++ b/tests/registry/test_action_resource_contract.py @@ -3,27 +3,30 @@ from __future__ import annotations import importlib.util +import logging import sys from pathlib import Path import pytest from unilabos.registry.action_options import RemovedActionOptionError -from unilabos.registry.action_resource_contract import ActionResourceContractError +from unilabos.registry.action_resource_contract import EXECUTING_DEVICE from unilabos.registry.ast_registry_scanner import _parse_file from unilabos.registry.decorators import Material, action -from unilabos.registry.material_roles import MaterialRoleError, material_contract +from unilabos.registry.material_roles import MaterialRoleError, material_contract, material_site_selectors + +_SIGNATURE = ( + "self, material: ResourceSlot, target_site: SiteSlot, source_site: SiteSlot, " + "arm_device: DeviceSlot, vessel_device: DeviceSlot, other: ResourceSlot, label: str" +) def _source(material: str, *, signature: str | None = None) -> str: - signature = signature or ( - "self, material: ResourceSlot, source_device: ResourceSlot, source_site: str, " - "target_device: ResourceSlot, target_site_uuid: str" - ) + signature = signature or _SIGNATURE return f''' from typing import TypedDict from unilabos.registry.decorators import Material, action, device -from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot class Result(TypedDict): material: ResourceSlot @@ -32,7 +35,7 @@ class Result(TypedDict): class Robot: @action(material={material}) def move({signature}) -> Result: - """执行一次设备间物料转运。""" + """执行一次物料动作。""" raise NotImplementedError ''' @@ -59,130 +62,204 @@ def _import(tmp_path: Path, source: str, name: str = "robot_runtime"): return module -def test_material_roles_freeze_into_the_canonical_action_schema(tmp_path: Path) -> None: - """设备间托管、完整搬运与资源参数合成一个字段,规范化成第 2 版合同冻结进 schema。""" - - action_entry = _scan_action( - tmp_path, - """[ - Material.load("material", device="target_device", from_device="source_device"), - Material.transfer( - "material", to="target_device", site="target_site_uuid", - source="source_device", source_site_name="source_site", gripper="robot.gripper", - ), - Material.uses(device=["source_device", "target_device"]), - ]""", - ) - - contract = action_entry["canonical_schema"]["x-unilabos-action-contract"]["resource_contract"] - assert contract["version"] == 2 - assert contract["resource_params"] == [ - {"param": "source_device", "role": "device"}, - {"param": "target_device", "role": "device"}, - ] - assert contract["device_tenancy"] == { - "mode": "task_while_loaded", - "material_param": "material", - "acquire_device_param": "target_device", - "release_device_param": "source_device", - } - assert contract["transfer"] == { - "material_param": "material", - "source_owner_param": "source_device", - "source_site_uuid_param": "", - "source_site_name_param": "source_site", - "target_owner_param": "target_device", - "target_site_uuid_param": "target_site_uuid", - "target_site_name_param": "", - "gripper_site_role": "robot.gripper", +def _contract(entry: dict) -> dict: + return entry["canonical_schema"]["x-unilabos-action-contract"]["resource_contract"] + + +def test_move_freezes_into_the_transfer_contract_with_site_derived_owner(tmp_path: Path) -> None: + """Material.move:所属方由库位决定(不写所属物料参数),搬运设备省略即执行设备。""" + + contract = _contract(_scan_action(tmp_path, 'Material.move("material", to_site="target_site")')) + assert contract == { + "version": 2, + "transfer": { + "material_param": "material", + "source_owner_param": "", + "source_site_uuid_param": "", + "source_site_name_param": "", + "target_owner_param": "", + "target_site_uuid_param": "target_site", + "target_site_name_param": "", + "gripper_site_role": "gripper", + }, } + explicit = _contract(_scan_action( + tmp_path, 'Material.move("material", to_site="target_site", from_site="source_site", carrier_device="arm_device")' + )) + assert explicit["transfer"]["source_site_uuid_param"] == "source_site" + assert explicit["transfer"]["carrier_device_param"] == "arm_device" def test_decorator_and_ast_scan_produce_the_same_contract(tmp_path: Path) -> None: - material = '[Material.in_place("material"), Material.order_sensitive()]' - scanned = _scan_action(tmp_path, material)["canonical_schema"]["x-unilabos-action-contract"]["resource_contract"] + material = '[Material.pick("material", from_site="source_site", carrier_device="arm_device")]' + scanned = _contract(_scan_action(tmp_path, material)) module = _import(tmp_path, _source(material)) assert module.Robot.move._action_registry_meta["resource_contract"] == scanned - assert scanned == {"version": 2, "operate_in_place": {"material_param": "material"}, "order_sensitive": True} + assert scanned == {"version": 2, "transfer_step": { + "operation": "pick", "material_param": "material", "owner_param": "", + "site_param": "source_site", "carrier_params": ["arm_device"], + }} @pytest.mark.parametrize( ("role", "expected"), [ ( - Material.load("s", device="v"), + Material.load("s"), {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", - "acquire_device_param": "v", "release_device_param": ""}}, + "acquire_device_param": EXECUTING_DEVICE, "release_device_param": ""}}, + ), + ( + Material.load("s", device="b", from_device="a"), + {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", + "acquire_device_param": "b", "release_device_param": "a"}}, ), ( Material.unload("s", device="v"), {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", "acquire_device_param": "", "release_device_param": "v"}}, ), + ( + Material.unload("s"), + {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", + "acquire_device_param": "", "release_device_param": EXECUTING_DEVICE}}, + ), (Material.in_place("s"), {"operate_in_place": {"material_param": "s"}}), ( - Material.pick("s", owner="o", site="t", carriers=["c"]), - {"transfer_step": {"operation": "pick", "material_param": "s", "owner_param": "o", - "site_param": "t", "carrier_params": ["c"]}}, + Material.pick("s"), + {"transfer_step": {"operation": "pick", "material_param": "s", "owner_param": "", + "site_param": "", "carrier_params": []}}, ), ( - Material.place("s", owner="o", site="t", carriers="c"), - {"transfer_step": {"operation": "place", "material_param": "s", "owner_param": "o", + Material.place("s", to_site="t", carrier_device="c"), + {"transfer_step": {"operation": "place", "material_param": "s", "owner_param": "", "site_param": "t", "carrier_params": ["c"]}}, ), ( - Material.aliquot(source="a", targets=["b", "c"]), + Material.dispense(from_material="a", to_materials=["b", "c"]), {"aliquot": {"source_material_param": "a", "target_material_params": ["b", "c"]}}, ), - (Material.order_sensitive(), {"order_sensitive": True}), - ( - Material.uses(device="d", tool=["t"], motion="m", site="s", material="x"), - {"resource_params": [ - {"param": "d", "role": "device"}, {"param": "t", "role": "tool"}, {"param": "m", "role": "motion"}, - {"param": "s", "role": "site"}, {"param": "x", "role": "material"}, - ]}, - ), ( - Material.transfer("s", to="o", site_name="n", gripper="g", motion=["arm"], tools="hand"), - {"transfer": {"material_param": "s", "source_owner_param": "", "source_site_uuid_param": "", - "source_site_name_param": "", "target_owner_param": "o", "target_site_uuid_param": "", - "target_site_name_param": "n", "gripper_site_role": "g", - "motion_resource_roles": ["arm"], "tool_resource_roles": ["hand"]}}, + Material.dispense(from_material="a", to_materials="b"), + {"aliquot": {"source_material_param": "a", "target_material_params": ["b"]}}, ), + (Material.order_sensitive(), {"order_sensitive": True}), ], ) def test_every_role_maps_to_the_existing_contract_field(role, expected) -> None: assert material_contract(role) == {"version": 2, **expected} +def test_site_picker_keeps_the_site_selector_shape() -> None: + assert material_site_selectors(Material.site_picker("site", of="carrier", for_material="s")) == { + "site": {"version": 1, "owner": "carrier", "occupant": "s", "show_occupied": True, "allow_occupied": False} + } + assert material_site_selectors(Material.site_picker("site", occupied="hide"))["site"] == { + "version": 1, "owner": None, "occupant": None, "show_occupied": False, "allow_occupied": False, + } + assert material_site_selectors(Material.site_picker("site", of="o", occupied="allow"))["site"]["allow_occupied"] + with pytest.raises(MaterialRoleError, match="hide"): + Material.site_picker("site", occupied="never") + + def test_conflicting_or_invalid_roles_are_rejected() -> None: with pytest.raises(MaterialRoleError, match="不能写在同一个动作上"): material_contract([Material.load("s", device="a"), Material.unload("s", device="b")]) + with pytest.raises(MaterialRoleError, match="不能写在同一个动作上"): + material_contract([Material.move("s", to_site="t"), Material.pick("s")]) with pytest.raises(MaterialRoleError): material_contract({"device_tenancy": {}}) - with pytest.raises(MaterialRoleError): - Material.pick("s", owner="o", site="t", carriers=[]) - with pytest.raises(MaterialRoleError, match="写法无效"): - material_contract(Material.load("s", device="v", from_device="v")) - - -def test_unknown_parameter_is_a_registration_error(tmp_path: Path) -> None: - with pytest.raises(ActionResourceContractError) as caught: - _scan_action(tmp_path, 'Material.in_place("missing")') - assert caught.value.code == "unknown_action_resource_parameter" - with pytest.raises(MaterialRoleError, match="missing"): - _import(tmp_path, _source('Material.in_place("missing")'), name="robot_unknown") - - -def test_tenancy_device_parameter_accepts_readable_id_but_material_stays_resource_slot(tmp_path: Path) -> None: - signature = "self, material: ResourceSlot, target_device: str" - action_entry = _scan_action(tmp_path, 'Material.load("material", device="target_device")', signature=signature) - schema = action_entry["canonical_schema"] - assert schema["properties"]["goal"]["properties"]["target_device"]["type"] == "string" - with pytest.raises(ActionResourceContractError): - _scan_action( - tmp_path, 'Material.load("material", device="target_device")', signature="self, material: str, target_device: str" - ) + with pytest.raises(MaterialRoleError, match="不能是同一个参数"): + Material.load("s", device="v", from_device="v") + with pytest.raises(MaterialRoleError, match="不同的参数"): + Material.dispense(from_material="a", to_materials=["a"]) + + +@pytest.mark.parametrize( + ("call", "hint"), + [ + ('Material.transfer("material", to="other", site="target_site", gripper="robot.gripper")', "Material.move"), + ('Material.aliquot(source="material", targets=["other"])', "Material.dispense"), + ('Material.site("target_site", owner="other", occupant="material")', "Material.site_picker"), + ('Material.uses(device=["arm_device"])', "按类型加锁"), + ('Material.pick("material", owner="other", site="source_site", carriers=["other"])', "carrier_device"), + ('Material.place("material", owner="other", site="target_site", carriers=["other"])', "to_site"), + ], +) +def test_legacy_spellings_fail_in_the_decorator_and_in_the_scan(tmp_path: Path, call: str, hint: str) -> None: + """旧写法:装饰器(导入时)与 AST 扫描都直接报错,错误信息给出新写法。""" + + with pytest.raises(MaterialRoleError, match=hint): + _scan_action(tmp_path, call) + with pytest.raises(MaterialRoleError, match=hint): + _import(tmp_path, _source(call), name="robot_legacy") + + +@pytest.mark.parametrize( + ("call", "hint"), + [ + ('Material.move("material", to_site="label")', "必须注解为 SiteSlot"), + ('Material.move("material", to_site="target_site", carrier_device="other")', "必须注解为 DeviceSlot"), + ('Material.pick("label")', "必须注解为单个 ResourceSlot"), + ('Material.load("material", device="other")', "必须注解为 DeviceSlot"), + ('Material.site_picker("label")', "SiteSlot"), + ('Material.site_picker("target_site", of="label")', "ResourceSlot 或 DeviceSlot"), + ('Material.dispense(from_material="material", to_materials=["arm_device"])', "必须注解为单个 ResourceSlot"), + ('Material.in_place("missing")', "签名里没有的参数.*missing"), + ], +) +def test_parameter_types_are_checked_against_the_signature(tmp_path: Path, call: str, hint: str) -> None: + """字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;装饰器与 AST 扫描同一口径。""" + + with pytest.raises(ValueError, match=hint): + _scan_action(tmp_path, call) + with pytest.raises(ValueError, match=hint): + _import(tmp_path, _source(call), name="robot_types") + + +def test_device_owner_and_omitted_owner_are_accepted_by_the_site_picker(tmp_path: Path) -> None: + entry = _scan_action(tmp_path, '[Material.site_picker("target_site", of="arm_device", for_material="material")]') + field = entry["canonical_schema"]["properties"]["goal"]["properties"]["target_site"] + assert field["x-unilabos-site-selector"]["owner"] == "arm_device" + assert field["x-unilabos-editor-control"] == "site_selector" + entry = _scan_action(tmp_path, '[Material.site_picker("target_site", occupied="allow")]') + selector = entry["canonical_schema"]["properties"]["goal"]["properties"]["target_site"]["x-unilabos-site-selector"] + assert selector == {"version": 1, "owner": None, "occupant": None, "show_occupied": True, "allow_occupied": True} + + +def test_slot_parameters_carry_their_kind_in_the_schema(tmp_path: Path) -> None: + """DeviceSlot / SiteSlot 字段带 x-unilabos-slot:调度器按它给设备 / 库位加锁。""" + + goal = _scan_action(tmp_path, 'Material.pick("material")')["canonical_schema"]["properties"]["goal"]["properties"] + assert goal["arm_device"]["x-unilabos-slot"] == "device" + assert goal["target_site"]["x-unilabos-slot"] == "site" + assert "x-unilabos-slot" not in goal["label"] + + +def test_experimental_roles_warn_once_per_definition(tmp_path: Path, caplog) -> None: + caplog.set_level(logging.WARNING) + material = '[Material.load("material", device="vessel_device"), Material.order_sensitive()]' + _scan_action(tmp_path, material) + _scan_action(tmp_path, material) + warnings = [record.getMessage() for record in caplog.records if "实验性功能" in record.getMessage()] + assert len(warnings) == 1 + assert "Material.load" in warnings[0] and "Material.order_sensitive" in warnings[0] + caplog.clear() + _scan_action(tmp_path, 'Material.move("material", to_site="target_site")', signature=_SIGNATURE + ", extra: str = ''") + assert not [record for record in caplog.records if "实验性功能" in record.getMessage()] + + +def test_experimental_warning_from_the_decorator(caplog) -> None: + from unilabos.registry.placeholder_type import ResourceSlot + + caplog.set_level(logging.WARNING) + + class Driver: + @action(material=Material.in_place("sample")) + def stir_experimental(self, sample: ResourceSlot) -> None: + pass + + assert any("实验性功能 Material.in_place" in record.getMessage() for record in caplog.records) @pytest.mark.parametrize( diff --git a/tests/registry/test_backend_metadata.py b/tests/registry/test_backend_metadata.py index 0cf2941784..996b11f2bc 100644 --- a/tests/registry/test_backend_metadata.py +++ b/tests/registry/test_backend_metadata.py @@ -267,7 +267,7 @@ def test_ast_cache_rejects_previous_metadata_version(tmp_path) -> None: cache = load_scan_cache(cache_path) - assert _CACHE_VERSION == 26 + assert _CACHE_VERSION == 27 assert cache == {"version": _CACHE_VERSION, "files": {}} diff --git a/tests/registry/test_site_selector_contract.py b/tests/registry/test_site_selector_contract.py index e30baa14a5..3ba4ed100c 100644 --- a/tests/registry/test_site_selector_contract.py +++ b/tests/registry/test_site_selector_contract.py @@ -1,7 +1,7 @@ -"""库位参数(``SiteSlot``)与物料参数的关系:``@action(material=Material.site(...))``。 +"""库位参数(``SiteSlot``)与物料参数的关系:``@action(material=Material.site_picker(...))``。 ``SiteSelector`` 已与 ``SiteSlot`` 合一:库位参数只有一个类型 ``SiteSlot``,库位属于哪个物料参数、放进去的是 -哪个物料参数、已占用库位的显示 / 可选策略写在 ``Material.site``。生成的 ``x-unilabos-site-selector`` 扩展与 +哪个物料参数、已占用库位的显示 / 可选策略写在 ``Material.site_picker``。生成的 ``x-unilabos-site-selector`` 扩展与 原 ``SiteSelector`` 相同,连接点投影、运行预检与派发前的库位门禁照旧按它工作。 """ @@ -67,7 +67,7 @@ def _scan(tmp_path: Path, material: str, signature: str, *, header: str = "") -> return entry["class"]["action_value_mappings"]["action"] -_FULL = 'Material.site("site", owner="warehouse", occupant="resource", show_occupied=True, allow_occupied=False)' +_FULL = 'Material.site_picker("site", of="warehouse", for_material="resource", occupied="show")' _FULL_SIGNATURE = "warehouse: ResourceSlot, resource: ResourceSlot, site: SiteSlot = None" @@ -76,7 +76,7 @@ def _without_description(field: dict[str, Any]) -> dict[str, Any]: def test_material_site_builds_the_same_extension_as_the_removed_site_selector() -> None: - role = Material.site("site", owner="warehouse", occupant="resource", show_occupied=True, allow_occupied=False) + role = Material.site_picker("site", of="warehouse", for_material="resource", occupied="show") assert material_site_selectors(role) == {"site": _SITE_SELECTOR_FIELD["x-unilabos-site-selector"]} # 库位关系不进资源合同:只写库位关系的动作没有资源合同,与其他语义写在一起时互不影响 assert material_contract(role) == {} @@ -85,17 +85,18 @@ def test_material_site_builds_the_same_extension_as_the_removed_site_selector() "operate_in_place": {"material_param": "resource"}, } with pytest.raises(MaterialRoleError): - Material.site("site", owner="warehouse", show_occupied="yes") + Material.site_picker("site", of="warehouse", occupied="yes") with pytest.raises(MaterialRoleError, match="自身"): - Material.site("site", owner="site") + Material.site_picker("site", of="site") with pytest.raises(MaterialRoleError, match="多条"): - material_site_selectors([Material.site("site", owner="a"), Material.site("site", owner="b")]) + material_site_selectors([Material.site_picker("site", of="a"), Material.site_picker("site", of="b")]) def test_action_site_parameter_compiles_complete_relation_metadata(tmp_path: Path) -> None: action_entry = _scan(tmp_path, _FULL, _FULL_SIGNATURE) site = action_entry["schema"]["properties"]["goal"]["properties"]["site"] - assert _without_description(site) == _SITE_SELECTOR_FIELD + # 选择器扩展与原 SiteSelector 相同;另外标出槽位类型(调度器按它加库位锁) + assert _without_description(site) == {**_SITE_SELECTOR_FIELD, "x-unilabos-slot": "site"} assert action_entry["placeholder_keys"]["site"] == "unilabos_sites" assert action_entry["materials_need_lock"] == ["warehouse", "resource"] assert "resource_contract" not in action_entry["schema"]["x-unilabos-action-contract"] @@ -104,7 +105,7 @@ def test_action_site_parameter_compiles_complete_relation_metadata(tmp_path: Pat def test_decorator_records_the_same_relation(tmp_path: Path) -> None: from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot - @action(material=Material.site("site", owner="warehouse")) + @action(material=Material.site_picker("site", of="warehouse")) def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass @@ -113,7 +114,7 @@ def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: } with pytest.raises(MaterialRoleError, match="missing"): - @action(material=Material.site("site", owner="missing")) + @action(material=Material.site_picker("site", of="missing")) def bad(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass @@ -123,43 +124,43 @@ def bad(self, warehouse: ResourceSlot, site: SiteSlot) -> None: [ pytest.param( "warehouse: ResourceSlot, resource: ResourceSlot, site: SiteSlot", - 'Material.site("site", owner="missing", occupant="resource")', - "owner='missing'", + 'Material.site_picker("site", of="missing", for_material="resource")', + "of='missing'", id="missing-owner", ), pytest.param( "warehouse: str, resource: ResourceSlot, site: SiteSlot", - 'Material.site("site", owner="warehouse", occupant="resource")', - "owner='warehouse'", + 'Material.site_picker("site", of="warehouse", for_material="resource")', + "of='warehouse'", id="scalar-owner", ), pytest.param( "warehouse: ResourceSlot, resource: str, site: SiteSlot", - 'Material.site("site", owner="warehouse", occupant="resource")', - "occupant='resource'", + 'Material.site_picker("site", of="warehouse", for_material="resource")', + "for_material='resource'", id="scalar-occupant", ), pytest.param( "warehouse: list[ResourceSlot], site: SiteSlot", - 'Material.site("site", owner="warehouse")', + 'Material.site_picker("site", of="warehouse")', "单个 ResourceSlot", id="list-owner", ), pytest.param( "warehouse: ResourceSlot, site: str", - 'Material.site("site", owner="warehouse")', + 'Material.site_picker("site", of="warehouse")', "必须注解为 SiteSlot", id="plain-string-site", ), pytest.param( "warehouse: ResourceSlot, site: list[SiteSlot]", - 'Material.site("site", owner="warehouse")', + 'Material.site_picker("site", of="warehouse")', "必须注解为 SiteSlot", id="site-list", ), pytest.param( "warehouse: ResourceSlot", - 'Material.site("site", owner="warehouse")', + 'Material.site_picker("site", of="warehouse")', "签名里没有", id="missing-site", ), @@ -214,7 +215,7 @@ def place(self, warehouse: ResourceSlot, site: Annotated[str, SiteSelector(owner def test_material_site_allows_omitting_the_optional_occupant(tmp_path: Path) -> None: action_entry = _scan( - tmp_path, 'Material.site("site", owner="warehouse")', "warehouse: ResourceSlot, site: SiteSlot" + tmp_path, 'Material.site_picker("site", of="warehouse")', "warehouse: ResourceSlot, site: SiteSlot" ) site = action_entry["schema"]["properties"]["goal"]["properties"]["site"] assert site["type"] == "string" @@ -275,7 +276,7 @@ def test_action_template_handle_projects_complete_site_selector_metadata(tmp_pat def test_action_template_projection_rejects_invalid_site_selector_extensions( tmp_path: Path, field_name: str, schema_change: dict[str, object], message: str ) -> None: - schema = _scan(tmp_path, 'Material.site("site", owner="warehouse")', "warehouse: ResourceSlot, site: SiteSlot")[ + schema = _scan(tmp_path, 'Material.site_picker("site", of="warehouse")', "warehouse: ResourceSlot, site: SiteSlot")[ "schema" ] field_schema = schema["properties"]["goal"]["properties"][field_name] @@ -308,7 +309,7 @@ def get_material(self, identity: str) -> Any: @pytest.mark.parametrize("allow_occupied", [False, True]) def test_preflight_and_dispatch_gate_follow_the_material_site_relation(tmp_path: Path, allow_occupied: bool) -> None: - """运行预检与派发前共用的库位门禁按 Material.site 生成的扩展核对归属与占用,行为与原 SiteSelector 相同。""" + """运行预检与派发前共用的库位门禁按 Material.site_picker 生成的扩展核对归属与占用,行为与原 SiteSelector 相同。""" from unilabos.server.services.runtime.workflow.run_preflight import ( ResourceUnavailableError, @@ -316,7 +317,7 @@ def test_preflight_and_dispatch_gate_follow_the_material_site_relation(tmp_path: ) material = ( - f'Material.site("site", owner="warehouse", occupant="resource", allow_occupied={allow_occupied})' + f'Material.site_picker("site", of="warehouse", for_material="resource", occupied={'"allow"' if allow_occupied else '"show"'})' ) schema = _scan(tmp_path, material, "warehouse: ResourceSlot, resource: ResourceSlot, site: SiteSlot")["schema"] materials = _Materials() diff --git a/unilabos/protocol/runtime/site_references.py b/unilabos/protocol/runtime/site_references.py index 6d776d6646..5fc808c06f 100644 --- a/unilabos/protocol/runtime/site_references.py +++ b/unilabos/protocol/runtime/site_references.py @@ -3,7 +3,7 @@ - 物料参数(``ResourceSlot`` / ``list[ResourceSlot]``)按库位绑定:``{"site_uuid": "<库位 uuid>"}``, 表示「此刻占着这个库位的物料」。建任务 / 运行预检时解析成占用物料的 ``{"uuid": ...}`` 并冻结进任务, 之后物料被挪走也不改变任务用的是哪件物料。 -- 库位参数(``SiteSlot``,带 ``Material.site`` 关系)按所属物料选择:``{"owner_uuid": "<所属物料 uuid>"}``, +- 库位参数(``SiteSlot``,带 ``Material.site_picker`` 关系)按所属物料选择:``{"owner_uuid": "<所属物料 uuid>"}``, 表示「这个物料下一个接受放入物料的空库位」。任务准入时调度器按库位序号选一个、经入口预留占住, 并把选中的库位 uuid 冻结进任务。 diff --git a/unilabos/registry/action_contract_schema.py b/unilabos/registry/action_contract_schema.py index b413ebf2a8..cf06f2bb9c 100644 --- a/unilabos/registry/action_contract_schema.py +++ b/unilabos/registry/action_contract_schema.py @@ -226,9 +226,9 @@ def _action_value_schema( return rendered # 设备 / 库位槽位在动作参数上就是字符串(与 action_schema 的 DeviceSlot / SiteSlot 渲染一致) if value.get("$slot") == "DeviceSlot": - return {"type": "string", "description": "device reference"} + return {"type": "string", "description": "device reference", "x-unilabos-slot": "device"} if value.get("$slot") == "SiteSlot": - return {"type": "string", "description": "site reference (ResourceSite uuid)"} + return {"type": "string", "description": "site reference (ResourceSite uuid)", "x-unilabos-slot": "site"} nullable_members = value.get("anyOf") if isinstance(nullable_members, list) and len(nullable_members) == 2: diff --git a/unilabos/registry/action_options.py b/unilabos/registry/action_options.py index a7963274f8..f2e8f21e67 100644 --- a/unilabos/registry/action_options.py +++ b/unilabos/registry/action_options.py @@ -7,8 +7,8 @@ - JSON 动作的 ``goal=`` / ``result=`` 重命名:字段名就是参数名 / 返回 TypedDict 的字段名 (ROS 动作类型的 ``goal`` / ``result`` 字段映射照旧); - 参数注解里的 ``Placeholder(...)``:前端选择器写在 ``@action(placeholder_keys={...})``; -- 参数注解里的 ``SiteSelector(...)``:库位参数注解为 ``SiteSlot``,库位关系写成 - ``material=Material.site(...)``; +- 参数注解里的 ``SiteSelector(...)``:库位参数注解为 ``SiteSlot``,库位选择器提示写成 + ``material=Material.site_picker(...)``; - 按名字注入的动作上下文(参数叫 ``action_context`` 却没有 ``ActionContext`` 注解):框架按类型注入, 注解为 ``Optional[ActionContext]``(见 :mod:`unilabos.registry.action_context`)。 @@ -26,8 +26,9 @@ REMOVED_ACTION_OPTIONS: Dict[str, str] = { "contract": "所有 JSON 动作统一按签名生成并校验 schema,去掉 contract= 即可", "resource_contract": ( - "资源语义改用 material=Material.xxx(...),例如 material=Material.load(\"sample\", device=\"vessel\")、" - "material=Material.in_place(\"sample\")、material=[Material.in_place(\"sample\"), Material.order_sensitive()]" + "资源语义改用 material=Material.xxx(...),例如 material=Material.move(\"plate\", to_site=\"target_site\")、" + "material=Material.dispense(from_material=\"source\", to_materials=[\"target\"])、" + "material=[Material.in_place(\"sample\"), Material.order_sensitive()]" ), } #: 只对 JSON 动作(没写 action_type)删除的选项 → 新写法。 @@ -43,8 +44,8 @@ "参数类型照常写,去掉 Annotated[..., Placeholder(...)] 外壳" ), "SiteSelector": ( - "库位参数注解为 SiteSlot,库位关系写成 @action(material=Material.site(\"库位参数\", " - "owner=\"拥有库位的物料参数\", occupant=\"放进去的物料参数\", show_occupied=True, allow_occupied=False))" + "库位参数注解为 SiteSlot,库位选择器提示写成 @action(material=Material.site_picker(\"库位参数\", " + "of=\"拥有库位的物料或设备参数\", for_material=\"放进去的物料参数\", occupied=\"show\"))" ), } #: 已删除注解的导入身份(``模块:名字``)→ 名字。 diff --git a/unilabos/registry/action_resource_contract.py b/unilabos/registry/action_resource_contract.py index 88a1fc00ca..3a8646b0a2 100644 --- a/unilabos/registry/action_resource_contract.py +++ b/unilabos/registry/action_resource_contract.py @@ -19,7 +19,12 @@ "motion_resource_roles", "tool_resource_roles", ) +#: transfer 的可选字段:搬运设备参数(``DeviceSlot``),省略时是执行设备。 +TRANSFER_OPTIONAL_FIELDS: tuple[str, ...] = ("carrier_device_param",) RESOURCE_PARAM_ROLES = frozenset({"device", "tool", "motion", "site", "material"}) +#: 设备托管合同里表示「执行设备本身」的记号(``Material.load`` / ``unload`` 省略 ``device`` 时); +#: 参数名不可能以 ``$`` 开头,调度器把它解析成执行动作的设备。 +EXECUTING_DEVICE = "$executor" class ActionResourceContractError(ValueError): @@ -128,31 +133,7 @@ def normalize_action_resource_contract( _fail("invalid_order_sensitive", "/order_sensitive", "order_sensitive 必须是布尔值") normalized["order_sensitive"] = value["order_sensitive"] if "transfer_step" in value: - step = value["transfer_step"] - fields = {"operation", "material_param", "owner_param", "site_param", "carrier_params"} - if ( - version != 2 - or not isinstance(step, Mapping) - or set(step) != fields - or step.get("operation") not in {"pick", "place"} - ): - _fail( - "invalid_transfer_step", - "/transfer_step", - "transfer_step 需要 v2、pick/place 和完整参数映射", - ) - normalized["transfer_step"] = { - "operation": step["operation"], - **{ - key: _parameter_name(step[key], f"/transfer_step/{key}") - for key in ("material_param", "owner_param", "site_param") - }, - "carrier_params": list( - _parameter_names(step["carrier_params"], "/transfer_step/carrier_params") - ), - } - if not normalized["transfer_step"]["carrier_params"]: - _fail("invalid_transfer_step", "/transfer_step/carrier_params", "搬运器参数不能为空") + normalized["transfer_step"] = _transfer_step(value["transfer_step"], version) if len(normalized) == 1: _fail( "empty_action_resource_contract", @@ -215,42 +196,29 @@ def validate_action_resource_contract_schema( if isinstance(tenancy, Mapping): resource_fields.append((str(tenancy["material_param"]), "/device_tenancy/material_param")) for field in ("acquire_device_param", "release_device_param"): - if tenancy.get(field): + if tenancy.get(field) and tenancy[field] != EXECUTING_DEVICE: resource_fields.append((str(tenancy[field]), f"/device_tenancy/{field}")) step = contract.get("transfer_step") if isinstance(step, Mapping): - for field in ("material_param", "owner_param"): - resource_fields.append((str(step[field]), f"/transfer_step/{field}")) + resource_fields.append((str(step["material_param"]), "/transfer_step/material_param")) + if step.get("owner_param"): + resource_fields.append((str(step["owner_param"]), "/transfer_step/owner_param")) for name in step["carrier_params"]: resource_fields.append((str(name), "/transfer_step/carrier_params")) - site_schema = goal_properties.get(step["site_param"]) - if not isinstance(site_schema, Mapping) or site_schema.get("type") != "string": - _fail( - "invalid_site_parameter_type", - "/transfer_step/site_param", - "搬运端点 Site 参数必须是字符串", - ) + if step.get("site_param"): + site_schema = goal_properties.get(step["site_param"]) + if not isinstance(site_schema, Mapping) or "string" not in _types(site_schema): + _fail( + "invalid_site_parameter_type", + "/transfer_step/site_param", + "搬运端点 Site 参数必须是字符串", + ) transfer = contract.get("transfer") if isinstance(transfer, Mapping): - resource_fields.extend( - ( - (str(transfer["material_param"]), "/transfer/material_param"), - *( - ( - ( - str(transfer["source_owner_param"]), - "/transfer/source_owner_param", - ), - ) - if transfer.get("source_owner_param") - else () - ), - ( - str(transfer["target_owner_param"]), - "/transfer/target_owner_param", - ), - ) - ) + resource_fields.append((str(transfer["material_param"]), "/transfer/material_param")) + for field in ("source_owner_param", "target_owner_param", "carrier_device_param"): + if transfer.get(field): + resource_fields.append((str(transfer[field]), f"/transfer/{field}")) for field in ( "source_site_uuid_param", "source_site_name_param", @@ -267,9 +235,7 @@ def validate_action_resource_contract_schema( f"/transfer/{field}", f"动作资源合同引用不存在的参数 {name}", ) - field_type = schema.get("type") - allowed_types = set(field_type) if isinstance(field_type, list) else {field_type} - if "string" not in allowed_types: + if "string" not in _types(schema): _fail( "invalid_site_parameter_type", f"/transfer/{field}", @@ -292,7 +258,15 @@ def validate_action_resource_contract_schema( resource_fields.append((str(name), f"/aliquot/target_material_params/{index}")) device_paths = {f"/required_device_params/{index}" for index, _ in enumerate(contract.get("required_device_params", []))} device_paths.update(f"/resource_params/{index}/param" for index,item in enumerate(resource_params) if item.get("role") in {"device","motion"}) - device_paths.update({"/device_tenancy/acquire_device_param", "/device_tenancy/release_device_param"}) + device_paths.update({ + "/device_tenancy/acquire_device_param", + "/device_tenancy/release_device_param", + "/transfer/carrier_device_param", + "/transfer_step/carrier_params", + "/transfer/source_owner_param", + "/transfer/target_owner_param", + "/transfer_step/owner_param", + }) for name, path in resource_fields: schema = goal_properties.get(name) if not isinstance(schema, Mapping): @@ -301,8 +275,8 @@ def validate_action_resource_contract_schema( path, f"动作资源合同引用不存在的参数 {name}", ) - # 设备身份可以直接用可读 ID;它不是要反序列化的 PLR 物料实例。 - if path in device_paths and schema.get("type") == "string": + # 设备身份可以直接用可读 ID(DeviceSlot);它不是要反序列化的 PLR 物料实例。 + if path in device_paths and "string" in _types(schema): continue if not _is_resource_reference_schema(schema): _fail( @@ -312,6 +286,11 @@ def validate_action_resource_contract_schema( ) +def _types(schema: Mapping[str, Any]) -> set: + kind = schema.get("type") + return set(kind) if isinstance(kind, list) else {kind} + + def _is_resource_reference_schema(value: Mapping[str, Any]) -> bool: """判断动作字段是否是规范 ResourceSlot 引用 Schema。 @@ -323,7 +302,7 @@ def _is_resource_reference_schema(value: Mapping[str, Any]) -> bool: uuid_schema = properties.get("uuid") if isinstance(properties, Mapping) else None required = value.get("required") return ( - value.get("type") == "object" + "object" in _types(value) and isinstance(uuid_schema, Mapping) and uuid_schema.get("type") == "string" and isinstance(required, list) @@ -404,7 +383,7 @@ def _transfer(value: Any) -> dict[str, Any]: if not isinstance(value, Mapping): _fail("invalid_transfer_contract", "/transfer", "transfer 必须是对象") - allowed = set(TRANSFER_CONTRACT_FIELDS) | set(TRANSFER_RESOURCE_ROLE_FIELDS) + allowed = set(TRANSFER_CONTRACT_FIELDS) | set(TRANSFER_RESOURCE_ROLE_FIELDS) | set(TRANSFER_OPTIONAL_FIELDS) if set(value) - allowed: _fail( "unknown_transfer_field", @@ -433,13 +412,13 @@ def _transfer(value: Any) -> dict[str, Any]: "/transfer", "声明来源父资源时必须同时声明来源库位 UUID 或名称参数", ) - if (source_site_uuid_param or source_site_name_param) and not source_owner_param: + if source_site_name_param and not source_owner_param: _fail( "transfer_source_owner_parameter_missing", "/transfer", - "声明来源库位时必须同时声明来源父资源参数", + "按名称声明来源库位时必须同时声明来源父资源参数(按库位 UUID 声明时所属方由库位决定)", ) - target_owner_param = _parameter_name( + target_owner_param = _optional_parameter_name( value.get("target_owner_param"), "/transfer/target_owner_param", ) @@ -457,10 +436,20 @@ def _transfer(value: Any) -> dict[str, Any]: "/transfer", "transfer 至少声明目标库位 UUID 或名称参数", ) + if not target_owner_param and not site_uuid_param: + _fail( + "transfer_target_owner_parameter_missing", + "/transfer", + "没有目标父资源参数时必须按库位 UUID 声明目标(所属方由库位决定)", + ) gripper_role = _parameter_name( value.get("gripper_site_role"), "/transfer/gripper_site_role", ) + carrier_device_param = _optional_parameter_name( + value.get("carrier_device_param"), + "/transfer/carrier_device_param", + ) normalized_transfer = { "material_param": material_param, "source_owner_param": source_owner_param, @@ -471,6 +460,9 @@ def _transfer(value: Any) -> dict[str, Any]: "target_site_name_param": site_name_param, "gripper_site_role": gripper_role, } + if carrier_device_param: + # 省略时是执行设备;只在写了时出现,旧合同的形状不变 + normalized_transfer["carrier_device_param"] = carrier_device_param for field in ("motion_resource_roles", "tool_resource_roles"): if field in value: normalized_transfer[field] = list( @@ -479,6 +471,40 @@ def _transfer(value: Any) -> dict[str, Any]: return normalized_transfer +def _transfer_step(value: Any, version: int) -> dict[str, Any]: + """规范两步搬运(pick / place)的参数映射。 + + ``owner_param`` 为空时所属方由库位 uuid 决定;``site_param`` 为空只允许 pick(从权威当前位置抓取); + ``carrier_params`` 为空时搬运设备是执行设备。 + """ + + fields = {"operation", "material_param", "owner_param", "site_param", "carrier_params"} + if ( + version != 2 + or not isinstance(value, Mapping) + or set(value) != fields + or value.get("operation") not in {"pick", "place"} + ): + _fail( + "invalid_transfer_step", + "/transfer_step", + "transfer_step 需要 v2、pick/place 和完整参数映射", + ) + owner = _optional_parameter_name(value["owner_param"], "/transfer_step/owner_param") + site = _optional_parameter_name(value["site_param"], "/transfer_step/site_param") + if value["operation"] == "place" and not site: + _fail("invalid_transfer_step", "/transfer_step/site_param", "place 必须声明目标库位参数") + if owner and not site: + _fail("invalid_transfer_step", "/transfer_step/site_param", "声明所属物料参数时必须同时声明库位参数") + return { + "operation": value["operation"], + "material_param": _parameter_name(value["material_param"], "/transfer_step/material_param"), + "owner_param": owner, + "site_param": site, + "carrier_params": list(_parameter_names(value["carrier_params"], "/transfer_step/carrier_params")), + } + + def _operate_in_place(value: Any) -> dict[str, str]: """规范“物料必须仍在实际执行设备内”的动作资源语义。""" @@ -643,6 +669,7 @@ def _fail(code: str, path: str, message: str) -> None: __all__ = [ + "EXECUTING_DEVICE", "ActionResourceContractError", "normalize_action_resource_contract", "validate_action_resource_contract_schema", diff --git a/unilabos/registry/action_schema.py b/unilabos/registry/action_schema.py index be4a1e21aa..feaca56ccf 100644 --- a/unilabos/registry/action_schema.py +++ b/unilabos/registry/action_schema.py @@ -5,7 +5,7 @@ - 严格解析器认识的注解(``str`` / ``int`` / ``float`` / ``bool``、``Literal``、``Optional`` 与 ``X | None``、``ResourceSlot`` / ``list[ResourceSlot]``、``list[X]``、``dict[str, JSONValue]``,以及 ``Annotated[..., Field(...)]`` / ``AllowedResourceTemplates``):严格 schema; -- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(material=Material.site(...))`` 声明的 +- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(material=Material.site_picker(...))`` 声明的 库位关系写进该 ``SiteSlot`` 参数的 ``x-unilabos-site-selector`` 扩展(前端库位选择器、预检与派发门禁用); - 没写注解、``Any``、``object``:接受任意 JSON 值(``{}``); - 默认值是 ``None`` 的参数按可空处理(``x: str = None`` 与 ``x: Optional[str] = None`` 相同); @@ -20,7 +20,7 @@ 不认识的字段退回推断);其他注解整体退回推断。 参数注解里已删除的 ``Placeholder(...)`` / ``SiteSelector(...)`` 是注册错误,报错信息给出新写法 -(前端选择器写 ``@action(placeholder_keys=...)``,库位关系写 ``Material.site(...)``)。 +(前端选择器写 ``@action(placeholder_keys=...)``,库位关系写 ``Material.site_picker(...)``)。 ROS 动作类型(``@action(action_type=...)``)不经过这里,照旧按 ROS 消息生成 schema。 """ @@ -82,6 +82,9 @@ f"{_PLACEHOLDER_MODULE}:DeviceSlot": "device reference", _SITE_SLOT: "site reference (ResourceSite uuid)", } +#: 字段 schema 上标出槽位类型的扩展:调度器按它给 DeviceSlot 加设备锁、给 SiteSlot 加库位锁。 +SLOT_KEY = "x-unilabos-slot" +_SLOT_KINDS = {f"{_PLACEHOLDER_MODULE}:DeviceSlot": "device", _SITE_SLOT: "site"} _warned: set[str] = set() _warned_lock = threading.Lock() @@ -258,7 +261,7 @@ def reject_removed_annotations( def _is_site_slot(node: ast.AST, bindings: ModuleBindings) -> bool: - """单个 ``SiteSlot``(可带 ``Optional`` / ``| None`` / ``Annotated``):``Material.site`` 的库位参数只能是它。""" + """单个 ``SiteSlot``(可带 ``Optional`` / ``| None`` / ``Annotated``):``Material.site_picker`` 的库位参数只能是它。""" if bindings.identity(node) == _SITE_SLOT: return True @@ -285,7 +288,7 @@ def _string_slot(node: ast.AST, bindings: ModuleBindings) -> Optional[Dict[str, identity = bindings.identity(node) if identity in _STRING_SLOTS: - return {"type": "string", "description": _STRING_SLOTS[identity]} + return {"type": "string", "description": _STRING_SLOTS[identity], SLOT_KEY: _SLOT_KINDS[identity]} if isinstance(node, ast.Subscript): origin = bindings.identity(node.value) members = _subscript_members(node) @@ -306,6 +309,31 @@ def _string_slot(node: ast.AST, bindings: ModuleBindings) -> Optional[Dict[str, return None +def slot_kind(field: Any) -> str: + """字段 schema 的槽位类型:``"resource"`` / ``"resource_list"`` / ``"device"`` / ``"device_list"`` / ``"site"`` / ``""``。 + + 认 ``ResourceSlot`` 的物料引用形状(``x-unilabos-material-lock`` 或 ``{"uuid"}`` 对象)与 + ``DeviceSlot`` / ``SiteSlot`` 的 ``x-unilabos-slot`` 扩展,可空 / ``anyOf`` 形态同样识别。 + """ + + if not isinstance(field, Mapping): + return "" + marker = field.get(SLOT_KEY) + if marker in {"device", "site"}: + return str(marker) + if "x-unilabos-material-lock" in field: + return "resource" + kinds = field.get("type") + kinds = set(kinds) if isinstance(kinds, list) else {kinds} + if "array" in kinds: + item = slot_kind(field.get("items")) + return f"{item}_list" if item in {"resource", "device"} else "" + members = [item for item in field.get("anyOf") or [] if isinstance(item, Mapping) and item.get("type") != "null"] + if len(members) == 1: + return slot_kind(members[0]) + return "" + + def _with_null(schema: Dict[str, Any]) -> Dict[str, Any]: """让一个字段 schema 也接受 null。""" @@ -463,7 +491,7 @@ def build_action_schema_draft( 由注册表 ``finalize_action_schema`` 补全;``inferred`` / ``result_inferred`` 列出退回推断的参数与 返回字段;``skipped`` 是无法表示、被忽略的参数写法。 - ``site_selectors`` 是 ``Material.site(...)`` 给出的 ``{库位参数名: x-unilabos-site-selector 扩展}``: + ``site_selectors`` 是 ``Material.site_picker(...)`` 给出的 ``{库位参数名: x-unilabos-site-selector 扩展}``: 库位参数必须注解为 ``SiteSlot``,owner / occupant 必须是单个 ``ResourceSlot`` 参数,扩展写进该参数的 schema。动作声明写错(库位关系不对、注解里写了已删除的 ``Placeholder`` / ``SiteSelector``)抛 :class:`ActionSchemaError`。 @@ -555,11 +583,15 @@ def build_action_schema_draft( for name, extension in (site_selectors or {}).items(): if name not in goal: - raise ActionSchemaError(f"动作 {definition}:Material.site 引用了签名里没有的参数 {name}") + raise ActionSchemaError(f"动作 {definition}:Material.site_picker 引用了签名里没有的参数 {name}") if name not in site_slots: - raise ActionSchemaError(f"动作 {definition}:Material.site 的库位参数 {name} 必须注解为 SiteSlot") + raise ActionSchemaError(f"动作 {definition}:Material.site_picker 的库位参数 {name} 必须注解为 SiteSlot") try: - validate_site_selector_relations(strict_descriptors, [(name, extension)]) + validate_site_selector_relations( + strict_descriptors, + [(name, extension)], + device_parameters={key for key, value in goal.items() if slot_kind(value) == "device"}, + ) except SiteSelectorSchemaError as error: raise ActionSchemaError(f"动作 {definition} 参数 {name}:{error.message}") from None field = goal[name] @@ -808,6 +840,8 @@ def _strip_reserved(schema: Dict[str, Any]) -> None: __all__ = [ "INFER_KEY", + "SLOT_KEY", + "slot_kind", "ActionSchemaError", "ModuleBindings", "build_action_schema_draft", diff --git a/unilabos/registry/ast_registry_scanner.py b/unilabos/registry/ast_registry_scanner.py index 0ac0992961..92b715f7a1 100644 --- a/unilabos/registry/ast_registry_scanner.py +++ b/unilabos/registry/ast_registry_scanner.py @@ -36,11 +36,14 @@ build_action_schema_draft, framework_parameter_names, reject_removed_annotations, + slot_kind, ) from unilabos.registry.material_roles import ( + check_material_parameter_types, material_contract, material_roles_from_ast, material_site_selectors, + warn_experimental, ) from unilabos.registry.placeholder_keys import ( check_placeholder_keys, @@ -59,7 +62,7 @@ MAX_SCAN_DEPTH = 10 # 最大目录递归深度 MAX_SCAN_FILES = 1000 # 最大扫描文件数量 -_CACHE_VERSION = 26 # 26:动作上下文参数按类型(ActionContext)排除,不再按名字 action_context +_CACHE_VERSION = 27 # 27:Material 重做(move / pick / place / dispense),DeviceSlot / SiteSlot 字段带 x-unilabos-slot # 允许点号分段(如 liquid_handler.prcxi),与内置 YAML 注册表的命名先例一致; # 点号只用于注册表模板名,设备实例 id(图节点)另有约束。 _DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$") @@ -1123,6 +1126,15 @@ def _extract_class_body( site_selectors=site_selectors, ) canonical_schema = draft["schema"] + if material_value is not None: + # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;实验性声明告警一次 + goal_fields = canonical_schema["properties"]["goal"]["properties"] + check_material_parameter_types( + roles, + lambda name: slot_kind(goal_fields[name]) if name in goal_fields else None, + definition=definition, + ) + warn_experimental(roles, definition) if resource_contract: from unilabos.registry.action_resource_contract import validate_action_resource_contract_schema diff --git a/unilabos/registry/decorators.py b/unilabos/registry/decorators.py index f5c337d66a..ba0df725e5 100644 --- a/unilabos/registry/decorators.py +++ b/unilabos/registry/decorators.py @@ -235,6 +235,72 @@ def _device_handles_to_list( return [h.to_registry_dict() for h in handles] +_SLOT_NAMES = {"ResourceSlot": "resource", "DeviceSlot": "device", "SiteSlot": "site"} + + +def _slot_kind_of_annotation(annotation: Any) -> str: + """运行时注解的槽位类型(与 AST 扫描的 ``action_schema.slot_kind`` 同一口径)。 + + 返回 ``"resource"`` / ``"resource_list"`` / ``"device"`` / ``"device_list"`` / ``"site"`` / ``""``; + 认 ``Optional`` / ``X | None`` / ``Annotated`` / ``list`` 形态,注解是字符串(延迟求值)时按名字识别。 + """ + + import typing + + if isinstance(annotation, str): + text = annotation.replace(" ", "") + for prefix in ("Optional[", "typing.Optional["): + if text.startswith(prefix) and text.endswith("]"): + return _slot_kind_of_annotation(text[len(prefix):-1]) + if text.startswith("Annotated[") and text.endswith("]"): + return _slot_kind_of_annotation(text[len("Annotated["):-1].split(",", 1)[0]) + for suffix in ("|None",): + if text.endswith(suffix): + return _slot_kind_of_annotation(text[: -len(suffix)]) + if text.startswith("None|"): + return _slot_kind_of_annotation(text[len("None|"):]) + for prefix in ("List[", "list[", "typing.List["): + if text.startswith(prefix) and text.endswith("]"): + inner = _slot_kind_of_annotation(text[len(prefix):-1]) + return f"{inner}_list" if inner in {"resource", "device"} else "" + return _SLOT_NAMES.get(text.rsplit(".", 1)[-1], "") + origin = typing.get_origin(annotation) + args = typing.get_args(annotation) + if origin is typing.Annotated and args: + return _slot_kind_of_annotation(args[0]) + if origin in (list, List) and len(args) == 1: + inner = _slot_kind_of_annotation(args[0]) + return f"{inner}_list" if inner in {"resource", "device"} else "" + if args and type(None) in args: + rest = [item for item in args if item is not type(None)] + return _slot_kind_of_annotation(rest[0]) if len(rest) == 1 else "" + if isinstance(annotation, type): + return _SLOT_NAMES.get(annotation.__name__, "") + return "" + + +def _runtime_slot_kinds(func: Callable[..., Any], parameters: Any) -> Dict[str, str]: + """签名里每个参数(不含 self / cls / 可变参数)的槽位类型;用于对照 ``material=`` 引用的参数。""" + + import inspect + import typing + + try: + hints = typing.get_type_hints(func, include_extras=True) + except Exception: # noqa: BLE001 - 延迟注解解析不了时按名字识别 + hints = {} + kinds: Dict[str, str] = {} + for name, parameter in parameters.items(): + if name in {"self", "cls"} or parameter.kind in ( + inspect.Parameter.VAR_POSITIONAL, + inspect.Parameter.VAR_KEYWORD, + ): + continue + annotation = hints.get(name, parameter.annotation) + kinds[name] = "" if annotation is inspect.Parameter.empty else _slot_kind_of_annotation(annotation) + return kinds + + def _action_handles_to_dict( handles: Optional[List[_ActionHandleBase]], ) -> Dict[str, Any]: @@ -451,10 +517,10 @@ def AddProtocol(self): ... parent: 若为 True,当方法参数为空 (*args, **kwargs) 时,通过 MRO 从父类获取真实方法参数 node_type: 动作的节点类型 (NodeType.ILAB / NodeType.MANUAL_CONFIRM)。 不填写时不写入注册表。 - material: 动作的资源语义:``Material.load / unload / in_place / pick / place / transfer / - aliquot / uses / order_sensitive / site`` 的一条,或多条组成的列表(见 - ``unilabos.registry.material_roles``)。字符串都是参数名,注册时对照签名检查。 - ``Material.site`` 声明 ``SiteSlot`` 库位参数属于哪个物料参数、放进去的是哪个物料参数。 + material: 动作的资源语义:物料动作 ``Material.move / pick / place / dispense``,以及实验性的 + ``Material.load / unload / in_place / site_picker / order_sensitive``,一条或多条组成的列表 + (见 ``unilabos.registry.material_roles``)。字符串都是参数名,注册时对照签名检查 + (物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot);实验性声明按定义告警一次。 error_policy: 按异常类名匹配审批选项的策略。结构见 unilabos.registry.action_policy.ErrorPolicy。 timeout: 硬超时(秒,正数)。到期后执行面协作式取消动作,并以 @@ -554,6 +620,13 @@ def wrapper(*args, **kwargs): raise MaterialRoleError( f"{func.__qualname__} 的 material= 引用了签名里没有的参数:{'、'.join(unknown)}" ) + if material is not None: + # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;实验性声明按定义告警一次 + from unilabos.registry.material_roles import check_material_parameter_types, warn_experimental + + slots = _runtime_slot_kinds(func, signature_parameters) + check_material_parameter_types(material, slots.get, definition=definition) + warn_experimental(material, definition) if resource_contract: meta["resource_contract"] = resource_contract if site_selectors: diff --git a/unilabos/registry/material_roles.py b/unilabos/registry/material_roles.py index ce51a4f1ca..595d677923 100644 --- a/unilabos/registry/material_roles.py +++ b/unilabos/registry/material_roles.py @@ -1,22 +1,26 @@ """动作的资源语义:``@action(material=...)`` 唯一的写法。 -一个动作对物料 / 设备的语义(装载托管、原位处理、搬运、分装、顺序敏感……)只用一个字段声明, -值是 ``Material`` 的一个方法调用,或多个调用组成的列表: +``Material`` 声明动作真实的物料动作,值是 ``Material`` 的一个方法调用,或多个调用组成的列表: from unilabos.registry.decorators import action, Material - @action(material=Material.load("sample", device="vessel")) - def load_sample(self, sample: ResourceSlot, vessel: str) -> CustodyResult: ... + @action(material=Material.move("plate", to_site="target_site")) + def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... - @action(material=[Material.in_place("sample"), Material.order_sensitive()]) - def stir(self, sample: ResourceSlot) -> None: ... + @action(material=Material.dispense(from_material="source", to_materials=["target"])) + def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... -字符串都是动作的参数名,注册时对照签名检查。内部规范化成第 2 版资源合同 -(``x-unilabos-action-contract.resource_contract``),调度器照旧按合同执行。 +稳定的物料动作:``move`` / ``pick`` / ``place`` / ``dispense``。不代表物料动作的声明(``load`` / ``unload`` +跨动作设备独占、``in_place`` 原位检查、``site_picker`` 库位选择器提示、``order_sensitive`` 顺序约束)仍写在 +``material=`` 里,但属于实验性功能:注册时按定义告警一次。 -``Material.site(...)`` 声明一个 ``SiteSlot`` 库位参数与物料参数的关系(库位属于哪个物料、放进去的是哪个 -物料、已占用库位的显示 / 可选策略)。它不进资源合同,而是写进该库位参数 schema 的 -``x-unilabos-site-selector`` 扩展,供前端库位选择器、运行预检与派发前的库位门禁使用。 +字符串参数都是动作的参数名,注册时对照签名检查:物料是 ``ResourceSlot``,库位是 ``SiteSlot``(库位 uuid), +设备是 ``DeviceSlot``(省略即执行设备)。内部规范化成第 2 版资源合同 +(``x-unilabos-action-contract.resource_contract``),调度器照旧按合同执行;``site_picker`` 不进资源合同, +写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展。 + +旧写法(``transfer`` / ``aliquot`` / ``site`` / ``uses``,带 ``owner`` / ``site`` / ``carriers`` 的 ``pick`` / ``place``) +直接报错并给出新写法。 本模块只依赖标准库与纯声明的合同规范化:装饰器(导入期)与 AST 扫描(不导入作者模块)共用。 """ @@ -28,6 +32,7 @@ def stir(self, sample: ResourceSlot) -> None: ... from typing import Any, Dict, Iterable, List, Optional, Tuple, Union from unilabos.registry.action_resource_contract import ( + EXECUTING_DEVICE, ActionResourceContractError, normalize_action_resource_contract, ) @@ -39,12 +44,18 @@ def stir(self, sample: ResourceSlot) -> None: ... "in_place": "operate_in_place", "pick": "transfer_step", "place": "transfer_step", - "transfer": "transfer", - "aliquot": "aliquot", + "move": "transfer", + "dispense": "aliquot", "order_sensitive": "order_sensitive", } #: 不进资源合同、写进参数 schema 扩展的语义。 -_SCHEMA_KINDS = frozenset({"site"}) +_SCHEMA_KINDS = frozenset({"site_picker"}) +#: 实验性声明(注册时按定义告警一次)。 +EXPERIMENTAL_KINDS = frozenset({"load", "unload", "in_place", "site_picker", "order_sensitive"}) +#: 搬运设备上夹爪库位的固定角色。 +GRIPPER_ROLE = "gripper" +#: ``site_picker`` 的已占用库位策略 → ``(show_occupied, allow_occupied)``。 +_OCCUPIED = {"hide": (False, False), "show": (True, False), "allow": (True, True)} #: AST 扫描认可的 ``Material`` 来源模块(``module:Material.method``)。 _MATERIAL_MODULES = ("unilabos.registry.decorators", "unilabos.registry.material_roles") @@ -69,6 +80,14 @@ def _name(value: Any, label: str) -> str: return value +def _optional(value: Any, label: str) -> str: + return "" if value is None else _name(value, label) + + +def _legacy(message: str) -> MaterialRoleError: + return MaterialRoleError(f"{message}(Material 辅助 API 已重做,见 docs/developer_guide/action_standard.md「不兼容变更」)") + + @dataclass(frozen=True) class MaterialRole: """``Material.xxx(...)`` 的结果:一条资源语义(不可变,按字段规范化成合同片段)。""" @@ -76,8 +95,15 @@ class MaterialRole: kind: str fields: Tuple[Tuple[str, Any], ...] = () + @property + def experimental(self) -> bool: + return self.kind in EXPERIMENTAL_KINDS + + def values(self) -> Dict[str, Any]: + return dict(self.fields) + def contract_part(self) -> Dict[str, Any]: - values = dict(self.fields) + values = self.values() if self.kind in {"load", "unload"}: return { "device_tenancy": { @@ -90,214 +116,282 @@ def contract_part(self) -> Dict[str, Any]: if self.kind == "in_place": return {"operate_in_place": {"material_param": values["material"]}} if self.kind in {"pick", "place"}: + carrier = values.get("carrier_device") or "" return { "transfer_step": { "operation": self.kind, "material_param": values["material"], - "owner_param": values["owner"], - "site_param": values["site"], - "carrier_params": list(values["carriers"]), + "owner_param": "", + "site_param": values.get("site") or "", + "carrier_params": [carrier] if carrier else [], } } - if self.kind == "transfer": + if self.kind == "move": transfer = { "material_param": values["material"], - "source_owner_param": values.get("source") or "", - "source_site_uuid_param": values.get("source_site") or "", - "source_site_name_param": values.get("source_site_name") or "", - "target_owner_param": values["to"], - "target_site_uuid_param": values.get("site") or "", - "target_site_name_param": values.get("site_name") or "", - "gripper_site_role": values["gripper"], + "source_owner_param": "", + "source_site_uuid_param": values.get("from_site") or "", + "source_site_name_param": "", + "target_owner_param": "", + "target_site_uuid_param": values["to_site"], + "target_site_name_param": "", + "gripper_site_role": GRIPPER_ROLE, } - if values.get("motion"): - transfer["motion_resource_roles"] = list(values["motion"]) - if values.get("tools"): - transfer["tool_resource_roles"] = list(values["tools"]) + if values.get("carrier_device"): + transfer["carrier_device_param"] = values["carrier_device"] return {"transfer": transfer} - if self.kind == "aliquot": + if self.kind == "dispense": return { "aliquot": { - "source_material_param": values["source"], - "target_material_params": list(values["targets"]), + "source_material_param": values["from_material"], + "target_material_params": list(values["to_materials"]), } } if self.kind == "order_sensitive": return {"order_sensitive": True} - if self.kind == "uses": - return {"resource_params": [{"param": name, "role": role} for role, name in values["params"]]} raise MaterialRoleError(f"未知的资源语义 {self.kind}") def site_selector(self) -> Tuple[str, Dict[str, Any]]: - """``Material.site(...)`` → ``(库位参数名, x-unilabos-site-selector 扩展)``。""" + """``Material.site_picker(...)`` → ``(库位参数名, x-unilabos-site-selector 扩展)``。""" - if self.kind != "site": - raise MaterialRoleError(f"Material.{self.kind} 不是库位关系") - values = dict(self.fields) + if self.kind != "site_picker": + raise MaterialRoleError(f"Material.{self.kind} 不是库位选择器提示") + values = self.values() + show, allow = _OCCUPIED[values["occupied"]] return values["site"], { "version": 1, - "owner": values["owner"], - "occupant": values.get("occupant"), - "show_occupied": values["show_occupied"], - "allow_occupied": values["allow_occupied"], + "owner": values.get("of"), + "occupant": values.get("for_material"), + "show_occupied": show, + "allow_occupied": allow, } + def parameter_types(self) -> List[Tuple[str, str, str]]: + """这条语义引用的参数及要求的类型:``[(参数名, "resource" | "site" | "device" | "owner", 说明)]``。 + + ``owner`` 表示 ``ResourceSlot`` 或 ``DeviceSlot`` 都可以(``site_picker`` 的 ``of``)。 + """ + + values = self.values() + label = f"Material.{self.kind}" + items: List[Tuple[str, str, str]] = [] + if self.kind in {"load", "unload", "in_place", "move", "pick", "place"}: + items.append((values["material"], "resource", f"{label} 的物料")) + if self.kind == "move": + items.append((values["to_site"], "site", f"{label} 的 to_site")) + if values.get("from_site"): + items.append((values["from_site"], "site", f"{label} 的 from_site")) + if self.kind in {"pick", "place"} and values.get("site"): + items.append((values["site"], "site", f"{label} 的 {'from_site' if self.kind == 'pick' else 'to_site'}")) + if self.kind in {"move", "pick", "place"} and values.get("carrier_device"): + items.append((values["carrier_device"], "device", f"{label} 的 carrier_device")) + if self.kind in {"load", "unload"}: + for key, keyword in (("acquire", "device"), ("release", "from_device" if self.kind == "load" else "device")): + name = values.get(key) + if name and name != EXECUTING_DEVICE: + items.append((name, "device", f"{label} 的 {keyword}")) + if self.kind == "dispense": + items.append((values["from_material"], "resource", f"{label} 的 from_material")) + items.extend((name, "resource", f"{label} 的 to_materials") for name in values["to_materials"]) + if self.kind == "site_picker": + items.append((values["site"], "site", f"{label} 的库位参数")) + if values.get("of"): + items.append((values["of"], "owner", f"{label} 的 of")) + if values.get("for_material"): + items.append((values["for_material"], "resource", f"{label} 的 for_material")) + return items + class Material: """资源语义的唯一入口:每个方法返回一条语义,``@action(material=...)`` 接收一条或一个列表。""" + # ------------------------------------------------------------------ 物料动作(稳定) + @staticmethod - def load(material: str, *, device: str, from_device: Optional[str] = None) -> MaterialRole: - """把物料装进设备并由任务托管设备,直到对应的 ``unload``(``from_device``:同时从另一台设备转出)。""" + def move( + material: str, + *, + to_site: str, + from_site: Optional[str] = None, + carrier_device: Optional[str] = None, + ) -> MaterialRole: + """一个动作把容器 ``material`` 搬到库位 ``to_site``。 - fields = [("material", _name(material, "Material.load 的物料")), ("acquire", _name(device, "device"))] - if from_device is not None: - fields.append(("release", _name(from_device, "from_device"))) - return MaterialRole("load", tuple(fields)) + ``to_site`` / ``from_site`` 是 ``SiteSlot`` 参数(库位 uuid),所属方(载架或设备根节点)由库位决定; + ``from_site`` 省略时用权威当前位置,给出时必须与权威一致。``carrier_device`` 是 ``DeviceSlot`` 参数, + 省略时就是执行设备;搬运途中物料在该设备角色为 ``gripper`` 的夹爪库位上。 + """ + + fields: List[Tuple[str, Any]] = [ + ("material", _name(material, "Material.move 的物料")), + ("to_site", _name(to_site, "Material.move 的 to_site")), + ] + if from_site is not None: + fields.append(("from_site", _name(from_site, "Material.move 的 from_site"))) + if carrier_device is not None: + fields.append(("carrier_device", _name(carrier_device, "Material.move 的 carrier_device"))) + names = [value for _, value in fields] + if len(set(names)) != len(names): + raise MaterialRoleError("Material.move 的物料、库位与搬运设备必须是不同的参数") + return MaterialRole("move", tuple(fields)) @staticmethod - def unload(material: str, *, device: str) -> MaterialRole: - """把物料从设备取出并结束设备托管。""" + def pick( + material: str, + *, + from_site: Optional[str] = None, + carrier_device: Optional[str] = None, + **legacy: Any, + ) -> MaterialRole: + """两步搬运第一步:从库位 ``from_site``(省略时为权威当前位置)抓到搬运设备的 ``gripper`` 夹爪库位。 - return MaterialRole( - "unload", (("material", _name(material, "Material.unload 的物料")), ("release", _name(device, "device"))) - ) + ``carrier_device`` 是 ``DeviceSlot`` 参数,省略时就是执行设备;抓取成功后任务托管搬运设备,直到 ``place``。 + """ + + if legacy: + raise _legacy( + "Material.pick 不再接受 owner / site / carriers / gripper:写成 " + "Material.pick(\"物料参数\", from_site=\"SiteSlot 库位参数\"(可省略), carrier_device=\"DeviceSlot 设备参数\"(可省略,即执行设备))" + ) + return Material._step("pick", material, from_site, carrier_device) @staticmethod - def in_place(material: str) -> MaterialRole: - """物料必须仍在执行设备内(原位处理)。""" + def place( + material: str, + *, + to_site: Optional[str] = None, + carrier_device: Optional[str] = None, + **legacy: Any, + ) -> MaterialRole: + """两步搬运第二步:从搬运设备的 ``gripper`` 夹爪库位放到库位 ``to_site``,结束对搬运设备的托管。""" - return MaterialRole("in_place", (("material", _name(material, "Material.in_place 的物料")),)) + if legacy or to_site is None: + raise _legacy( + "Material.place 写成 Material.place(\"物料参数\", to_site=\"SiteSlot 库位参数\", " + "carrier_device=\"DeviceSlot 设备参数\"(可省略,即执行设备)),不再接受 owner / site / carriers / gripper" + ) + return Material._step("place", material, to_site, carrier_device) @staticmethod - def pick(material: str, *, owner: str, site: str, carriers: Union[str, Sequence[str]]) -> MaterialRole: - """搬运第一步:从 ``owner`` 的库位 ``site`` 抓到搬运器(``carriers``)上。""" - - return Material._step("pick", material, owner, site, carriers) + def _step(kind: str, material: str, site: Optional[str], carrier_device: Optional[str]) -> MaterialRole: + keyword = "from_site" if kind == "pick" else "to_site" + fields: List[Tuple[str, Any]] = [("material", _name(material, f"Material.{kind} 的物料"))] + if site is not None: + fields.append(("site", _name(site, f"Material.{kind} 的 {keyword}"))) + if carrier_device is not None: + fields.append(("carrier_device", _name(carrier_device, f"Material.{kind} 的 carrier_device"))) + names = [value for _, value in fields] + if len(set(names)) != len(names): + raise MaterialRoleError(f"Material.{kind} 的物料、库位与搬运设备必须是不同的参数") + return MaterialRole(kind, tuple(fields)) @staticmethod - def place(material: str, *, owner: str, site: str, carriers: Union[str, Sequence[str]]) -> MaterialRole: - """搬运第二步:从搬运器(``carriers``)放到 ``owner`` 的库位 ``site``。""" + def dispense(*, from_material: str, to_materials: Union[str, Sequence[str]]) -> MaterialRole: + """按驱动回报的实际量,把内容物从 ``from_material`` 转移到 ``to_materials``(``AliquotReceipt`` 结算)。""" - return Material._step("place", material, owner, site, carriers) + names = _names(to_materials, "Material.dispense 的 to_materials") + if not names: + raise MaterialRoleError("Material.dispense 至少需要一个 to_materials") + source = _name(from_material, "Material.dispense 的 from_material") + targets = tuple(_name(item, "Material.dispense 的 to_materials") for item in names) + if source in targets or len(set(targets)) != len(targets): + raise MaterialRoleError("Material.dispense 的来源与目标必须是不同的参数") + return MaterialRole("dispense", (("from_material", source), ("to_materials", targets))) - @staticmethod - def _step(kind: str, material: str, owner: str, site: str, carriers) -> MaterialRole: - carrier_names = _names(carriers, "carriers") - if not carrier_names: - raise MaterialRoleError(f"Material.{kind} 的 carriers 不能为空") - return MaterialRole( - kind, - ( - ("material", _name(material, f"Material.{kind} 的物料")), - ("owner", _name(owner, "owner")), - ("site", _name(site, "site")), - ("carriers", tuple(_name(item, "carriers") for item in carrier_names)), - ), - ) + # ------------------------------------------------------------------ 实验性声明 @staticmethod - def transfer( - material: str, - *, - to: str, - gripper: str, - site: Optional[str] = None, - site_name: Optional[str] = None, - source: Optional[str] = None, - source_site: Optional[str] = None, - source_site_name: Optional[str] = None, - motion: Union[str, Sequence[str], None] = None, - tools: Union[str, Sequence[str], None] = None, - ) -> MaterialRole: - """一次完成的机械臂搬运:把物料放到 ``to`` 的库位(``site`` 是库位 UUID 参数,``site_name`` 是库位名参数)。 + def load(material: str, *, device: Optional[str] = None, from_device: Optional[str] = None) -> MaterialRole: + """(实验性)把物料装进设备 ``device``(``DeviceSlot`` 参数,省略即执行设备),任务托管设备直到 ``unload``。 - ``gripper`` 是夹爪库位的角色名;``source`` / ``source_site`` / ``source_site_name`` 声明来源; - ``motion`` / ``tools`` 是运动部件与工具的资源角色名。 + ``from_device``:同时从另一台设备(``DeviceSlot`` 参数)转出。 """ - fields: List[Tuple[str, Any]] = [ - ("material", _name(material, "Material.transfer 的物料")), - ("to", _name(to, "to")), - ("gripper", _name(gripper, "gripper")), - ] - for key, value in ( - ("site", site), - ("site_name", site_name), - ("source", source), - ("source_site", source_site), - ("source_site_name", source_site_name), - ): - if value is not None: - fields.append((key, _name(value, key))) - for key, value in (("motion", motion), ("tools", tools)): - names = _names(value, key) - if names: - fields.append((key, tuple(names))) - return MaterialRole("transfer", tuple(fields)) + acquire = _optional(device, "Material.load 的 device") or EXECUTING_DEVICE + fields = [("material", _name(material, "Material.load 的物料")), ("acquire", acquire)] + if from_device is not None: + release = _name(from_device, "Material.load 的 from_device") + if release == acquire: + raise MaterialRoleError("Material.load 的 device 与 from_device 不能是同一个参数") + fields.append(("release", release)) + return MaterialRole("load", tuple(fields)) @staticmethod - def aliquot(*, source: str, targets: Union[str, Sequence[str]]) -> MaterialRole: - """按实测量从 ``source`` 分装到全部 ``targets``。""" + def unload(material: str, *, device: Optional[str] = None) -> MaterialRole: + """(实验性)把物料从设备 ``device``(``DeviceSlot`` 参数,省略即执行设备)取出并结束设备托管。""" - names = _names(targets, "targets") - return MaterialRole( - "aliquot", (("source", _name(source, "source")), ("targets", tuple(_name(n, "targets") for n in names))) - ) + release = _optional(device, "Material.unload 的 device") or EXECUTING_DEVICE + return MaterialRole("unload", (("material", _name(material, "Material.unload 的物料")), ("release", release))) + + @staticmethod + def in_place(material: str) -> MaterialRole: + """(实验性)物料必须仍在执行设备内(原位处理)。""" + + return MaterialRole("in_place", (("material", _name(material, "Material.in_place 的物料")),)) @staticmethod - def site( + def site_picker( site: str, *, - owner: str, - occupant: Optional[str] = None, - show_occupied: bool = True, - allow_occupied: bool = False, + of: Optional[str] = None, + for_material: Optional[str] = None, + occupied: str = "show", ) -> MaterialRole: - """库位参数 ``site``(注解为 ``SiteSlot``)的库位属于物料参数 ``owner``。 + """(实验性)前端库位选择器提示:``SiteSlot`` 参数 ``site`` 列出所属方 ``of`` 的库位。 - ``occupant`` 是要放进这个库位的物料参数(可省略);``show_occupied`` 决定前端是否列出已占用的库位, - ``allow_occupied`` 决定已占用的库位能否选(运行预检与派发前按它核对)。``owner`` / ``occupant`` - 必须是单个 ``ResourceSlot`` 参数。 + ``of`` 是 ``ResourceSlot``(所属物料)或 ``DeviceSlot``(所属设备根节点)参数,省略时是执行设备根节点; + ``for_material`` 是要放进去的物料参数(可省略);``occupied``:``"hide"`` 不列出已占用的库位, + ``"show"`` 列出但不能选,``"allow"`` 列出且能选。 """ - fields: List[Tuple[str, Any]] = [ - ("site", _name(site, "Material.site 的库位参数")), - ("owner", _name(owner, "owner")), - ] - if occupant is not None: - fields.append(("occupant", _name(occupant, "occupant"))) - for key, value in (("show_occupied", show_occupied), ("allow_occupied", allow_occupied)): - if type(value) is not bool: - raise MaterialRoleError(f"Material.site 的 {key} 必须是 True / False") - fields.append((key, value)) - if site in {owner, occupant}: - raise MaterialRoleError("Material.site 不能把库位参数自身作为 owner / occupant") - return MaterialRole("site", tuple(fields)) + fields: List[Tuple[str, Any]] = [("site", _name(site, "Material.site_picker 的库位参数"))] + if of is not None: + fields.append(("of", _name(of, "Material.site_picker 的 of"))) + if for_material is not None: + fields.append(("for_material", _name(for_material, "Material.site_picker 的 for_material"))) + if occupied not in _OCCUPIED: + raise MaterialRoleError('Material.site_picker 的 occupied 只能是 "hide"、"show" 或 "allow"') + fields.append(("occupied", occupied)) + if site in {of, for_material}: + raise MaterialRoleError("Material.site_picker 不能把库位参数自身作为 of / for_material") + return MaterialRole("site_picker", tuple(fields)) @staticmethod def order_sensitive() -> MaterialRole: - """同一资源上的兄弟动作必须显式排序(只约束计划)。""" + """(实验性)同一资源上的兄弟动作必须显式排序(只约束计划)。""" return MaterialRole("order_sensitive") + # ------------------------------------------------------------------ 已删除的写法 + @staticmethod - def uses( - *, - device: Union[str, Sequence[str], None] = None, - tool: Union[str, Sequence[str], None] = None, - motion: Union[str, Sequence[str], None] = None, - site: Union[str, Sequence[str], None] = None, - material: Union[str, Sequence[str], None] = None, - ) -> MaterialRole: - """动作还占用这些资源参数(设备 / 工具 / 运动部件 / 库位 / 物料),调度时一并校验与占用。""" + def transfer(*_args: Any, **_kwargs: Any) -> MaterialRole: + raise _legacy( + "Material.transfer 已删除:写成 Material.move(\"物料参数\", to_site=\"SiteSlot 库位参数\", " + "from_site=\"SiteSlot 库位参数\"(可省略), carrier_device=\"DeviceSlot 设备参数\"(可省略,即执行设备));" + "所属方由库位决定(不写 to / source),库位参数注解为 SiteSlot(值是库位 uuid)," + "搬运设备的夹爪库位角色统一为 gripper(不写 gripper=)" + ) + + @staticmethod + def aliquot(*_args: Any, **_kwargs: Any) -> MaterialRole: + raise _legacy( + "Material.aliquot 已改名:写成 Material.dispense(from_material=\"来源物料参数\", to_materials=[\"目标物料参数\", ...])" + ) + + @staticmethod + def site(*_args: Any, **_kwargs: Any) -> MaterialRole: + raise _legacy( + "Material.site 已改名:写成 Material.site_picker(\"SiteSlot 库位参数\", of=\"所属物料或设备参数\"(可省略,即执行设备), " + "for_material=\"放入物料参数\", occupied=\"hide\" | \"show\" | \"allow\")" + ) - params: List[Tuple[str, str]] = [] - for role, value in (("device", device), ("tool", tool), ("motion", motion), ("site", site), ("material", material)): - params.extend((role, _name(name, role)) for name in _names(value, role)) - if not params: - raise MaterialRoleError("Material.uses 至少声明一个资源参数") - return MaterialRole("uses", (("params", tuple(params)),)) + @staticmethod + def uses(*_args: Any, **_kwargs: Any) -> MaterialRole: + raise _legacy( + "Material.uses 已删除:参数按类型加锁(ResourceSlot 物料锁、DeviceSlot 设备锁、SiteSlot 库位锁)," + "把参数注解成对应类型即可,去掉 Material.uses(...)" + ) def _roles(value: Any) -> List[MaterialRole]: @@ -310,8 +404,35 @@ def _roles(value: Any) -> List[MaterialRole]: return roles +def material_roles(value: Any) -> List[MaterialRole]: + """``material=`` 的值(一条语义或列表)→ 语义列表;``None`` 为空列表。""" + + return [] if value is None else _roles(value) + + +def experimental_kinds(value: Any) -> List[str]: + """``material=`` 里用到的实验性声明(按出现顺序去重)。""" + + return list(dict.fromkeys(role.kind for role in material_roles(value) if role.experimental)) + + +def warn_experimental(value: Any, definition: str) -> None: + """注册时按定义告警一次:用到了实验性声明(装饰器与 AST 扫描共用同一身份,同一定义只告警一次)。""" + + kinds = experimental_kinds(value) + if not kinds: + return + from unilabos.registry.action_schema import warn_once + + warn_once( + definition, + "material= 用到了实验性功能 " + "、".join(f"Material.{kind}" for kind in kinds) + + ":语义与写法以后可能调整", + ) + + def material_contract(value: Any) -> Dict[str, Any]: - """``material=`` 的值(一条语义或列表)→ 规范化的第 2 版资源合同;``None`` 或只有 ``Material.site`` 时返回空字典。""" + """``material=`` 的值(一条语义或列表)→ 规范化的第 2 版资源合同;``None`` 或只有 ``site_picker`` 时返回空字典。""" if value is None: return {} @@ -322,13 +443,12 @@ def material_contract(value: Any) -> Dict[str, Any]: continue part = role.contract_part() for key, item in part.items(): - if key == "resource_params": - raw.setdefault(key, []).extend(item) - continue if key in raw: raise MaterialRoleError(f"Material.{seen[key]} 与 Material.{role.kind} 不能写在同一个动作上") raw[key] = item seen[key] = role.kind + if "transfer" in raw and "transfer_step" in raw: + raise MaterialRoleError(f"Material.{seen['transfer']} 与 Material.{seen['transfer_step']} 不能写在同一个动作上") if len(raw) == 1: return {} try: @@ -338,21 +458,51 @@ def material_contract(value: Any) -> Dict[str, Any]: def material_site_selectors(value: Any) -> Dict[str, Dict[str, Any]]: - """``material=`` 里的 ``Material.site(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" + """``material=`` 里的 ``Material.site_picker(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" if value is None: return {} selectors: Dict[str, Dict[str, Any]] = {} for role in _roles(value): - if role.kind != "site": + if role.kind != "site_picker": continue site, extension = role.site_selector() if site in selectors: - raise MaterialRoleError(f"库位参数 {site} 写了多条 Material.site") + raise MaterialRoleError(f"库位参数 {site} 写了多条 Material.site_picker") selectors[site] = extension return selectors +def material_parameter_types(value: Any) -> List[Tuple[str, str, str]]: + """``material=`` 引用的全部参数与要求的类型(见 :meth:`MaterialRole.parameter_types`)。""" + + items: List[Tuple[str, str, str]] = [] + for role in material_roles(value): + items.extend(role.parameter_types()) + return items + + +def check_material_parameter_types(value: Any, slot_of, *, definition: str) -> None: + """对照签名检查 ``material=`` 引用的参数存在且类型正确。 + + ``slot_of(name)`` 返回参数的槽位类型:``"resource"``(单个 ``ResourceSlot``)、``"resource_list"``、 + ``"site"``、``"device"``、``"device_list"``、``""``(其他类型);参数不存在返回 ``None``。 + """ + + for name, kind, label in material_parameter_types(value): + actual = slot_of(name) + if actual is None: + raise MaterialRoleError(f"{definition}:{label} 引用了签名里没有的参数 {name}") + if kind == "resource" and actual != "resource": + raise MaterialRoleError(f"{definition}:{label} {name} 必须注解为单个 ResourceSlot") + if kind == "site" and actual != "site": + raise MaterialRoleError(f"{definition}:{label} {name} 必须注解为 SiteSlot(值是库位 uuid)") + if kind == "device" and actual != "device": + raise MaterialRoleError(f"{definition}:{label} {name} 必须注解为 DeviceSlot(值是设备 id)") + if kind == "owner" and actual not in {"resource", "device"}: + raise MaterialRoleError(f"{definition}:{label} {name} 必须注解为单个 ResourceSlot 或 DeviceSlot") + + def site_selector_parameter_names(selectors: Mapping[str, Mapping[str, Any]]) -> List[str]: """库位关系引用的全部动作参数名(库位参数、owner、occupant),用于对照签名。""" @@ -365,12 +515,12 @@ def site_selector_parameter_names(selectors: Mapping[str, Mapping[str, Any]]) -> def contract_parameter_names(contract: Mapping[str, Any]) -> List[str]: - """合同引用的全部动作参数名(不含夹爪 / 运动 / 工具角色名),用于对照签名。""" + """合同引用的全部动作参数名(不含夹爪 / 运动 / 工具角色名与执行设备记号),用于对照签名。""" names: List[str] = [] def add(value: Any) -> None: - if isinstance(value, str) and value and value not in names: + if isinstance(value, str) and value and value != EXECUTING_DEVICE and value not in names: names.append(value) tenancy = contract.get("device_tenancy") or {} @@ -391,6 +541,7 @@ def add(value: Any) -> None: "target_owner_param", "target_site_uuid_param", "target_site_name_param", + "carrier_device_param", ): add(transfer.get(key)) aliquot = contract.get("aliquot") or {} @@ -432,12 +583,19 @@ def material_roles_from_ast(value: Any) -> List[MaterialRole]: __all__ = [ + "EXPERIMENTAL_KINDS", + "GRIPPER_ROLE", "Material", "MaterialRole", "MaterialRoleError", + "check_material_parameter_types", "contract_parameter_names", + "experimental_kinds", "material_contract", + "material_parameter_types", + "material_roles", "material_roles_from_ast", "material_site_selectors", "site_selector_parameter_names", + "warn_experimental", ] diff --git a/unilabos/registry/registry.py b/unilabos/registry/registry.py index 3fde0b252d..bf9fe951f8 100644 --- a/unilabos/registry/registry.py +++ b/unilabos/registry/registry.py @@ -207,7 +207,7 @@ def _runtime_type_schema(tp: Any, *, depth: int = 0) -> Dict[str, Any]: if name == "ResourceSlot": return _material_reference_schema() if name in {"DeviceSlot", "SiteSlot"}: - return {"type": "string"} + return {"type": "string", "x-unilabos-slot": "device" if name == "DeviceSlot" else "site"} if issubclass(tp, _enum.Enum): values = [member.value for member in tp] return {"type": "string", "enum": values} if values and all(isinstance(v, str) for v in values) else {} diff --git a/unilabos/registry/site_selector_schema.py b/unilabos/registry/site_selector_schema.py index a972e922b6..62358bbeb9 100644 --- a/unilabos/registry/site_selector_schema.py +++ b/unilabos/registry/site_selector_schema.py @@ -1,6 +1,6 @@ -"""库位关系(``Material.site(...)``)的静态跨字段校验。 +"""库位关系(``Material.site_picker(...)``)的静态跨字段校验。 -库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(material=Material.site(...))``:库位属于 +库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(material=Material.site_picker(...))``:库位属于 哪个物料参数(``owner``)、放进去的是哪个物料参数(``occupant``)、已占用库位的显示 / 可选策略。注册表 把它写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展;本模块在生成 schema 时核对关系指向的参数。 """ @@ -28,14 +28,20 @@ def __init__(self, path: str, message: str) -> None: def validate_site_selector_relations( parameters: Sequence[Mapping[str, Any]], selectors: Sequence[tuple[str, Mapping[str, Any]]], + *, + device_parameters: Any = (), ) -> None: - """验证库位关系的跨字段物料引用。 + """验证库位关系的跨字段引用。 参数说明:``parameters`` 是严格解析出的动作输入(``{"name", "schema"}``);``selectors`` 把库位参数名 - 映射到 ``x-unilabos-site-selector`` 扩展。返回:无。异常:owner / occupant 缺失、引用库位参数自身或没有 - 指向单个物料参数(``ResourceSlot``)时抛出 ``SiteSelectorSchemaError``。 + 映射到 ``x-unilabos-site-selector`` 扩展;``device_parameters`` 是注解为 ``DeviceSlot`` 的参数名 + (``owner`` 可以指向它,表示所属设备的根节点)。``owner`` 为 ``None`` 表示执行设备的根节点。 + 返回:无。异常:引用库位参数自身、``owner`` 不是单个 ``ResourceSlot`` / ``DeviceSlot`` 参数、``occupant`` + 不是单个 ``ResourceSlot`` 参数时抛出 ``SiteSelectorSchemaError``。 """ + device_parameters = set(device_parameters or ()) + # ``parameter_by_name`` 是动作输入字段权威视图,用于拒绝名字猜测与未知引用。 parameter_by_name = { str(parameter.get("name")): (index, parameter) @@ -49,16 +55,20 @@ def validate_site_selector_relations( if referenced_name is None: continue relation_path = f"/parameters/{site_index}/site_selector/{relation_name}" + keyword = "of" if relation_name == "owner" else "for_material" if referenced_name == site_name: raise SiteSelectorSchemaError( relation_path, - "Material.site 不能把库位参数自身作为物料关系", + "Material.site_picker 不能把库位参数自身作为 of / for_material", ) + if relation_name == "owner" and referenced_name in device_parameters: + continue referenced_entry = parameter_by_name.get(referenced_name) if referenced_entry is None: raise SiteSelectorSchemaError( relation_path, - f"Material.site 的 {relation_name}={referenced_name!r} 必须是注解为 ResourceSlot 的参数", + f"Material.site_picker 的 {keyword}={referenced_name!r} 必须是注解为 ResourceSlot" + + (" 或 DeviceSlot" if relation_name == "owner" else "") + " 的参数", ) # ``referenced`` 是 owner/occupant 指向的动作输入合同。 referenced = referenced_entry[1] @@ -66,7 +76,8 @@ def validate_site_selector_relations( if not isinstance(schema, Mapping) or not _is_single_resource_slot(schema): raise SiteSelectorSchemaError( relation_path, - f"Material.site 的 {relation_name}={referenced_name!r} 必须是单个 ResourceSlot 参数", + f"Material.site_picker 的 {keyword}={referenced_name!r} 必须是单个 ResourceSlot" + + (" 或 DeviceSlot" if relation_name == "owner" else "") + " 参数", ) diff --git a/unilabos/registry/site_selector_value_schema.py b/unilabos/registry/site_selector_value_schema.py index cbdd1e1c72..8c207ed7da 100644 --- a/unilabos/registry/site_selector_value_schema.py +++ b/unilabos/registry/site_selector_value_schema.py @@ -97,10 +97,16 @@ def parse_site_selector_extension( _pointer(selector_path, "version"), "库位选择合同版本无效", ) - # ``owner`` 是提供库位集合的物料占位符(ResourceSlot)连接点字段名。 - owner = _required_relation_name( - raw_selector["owner"], - path=_pointer(selector_path, "owner"), + # ``owner`` 是提供库位集合的所属方连接点字段名(ResourceSlot 物料或 DeviceSlot 设备); + # ``None`` 表示执行设备的根节点(``Material.site_picker`` 省略 ``of``)。 + raw_owner = raw_selector["owner"] + owner = ( + None + if raw_owner is None + else _required_relation_name( + raw_owner, + path=_pointer(selector_path, "owner"), + ) ) # ``occupant`` 可选指向准备放入目标库位(Site)的物料字段。 raw_occupant = raw_selector["occupant"] From 33e7d1656ff1abda4c5c7128ac298533f5f04269 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:46:04 +0800 Subject: [PATCH 09/27] feat(scheduler): resolve Material.move / pick / place by site uuid The physical contract now accepts the normalized Material.move / pick / place shapes: - a target or source given as a SiteSlot (site uuid) derives its owner (a carrier or a device root) from the materials authority instead of a separate owner parameter; - move checks a given from_site against the authoritative location, and pick without from_site grabs from the authoritative location; - the carrier is the executing device unless carrier_device names a DeviceSlot, whose device id resolves to that device's material; the material rides on the carrier's "gripper" site. Contracts with explicit ResourceSlot owners keep working. --- tests/server/test_material_actions.py | 232 ++++++++++++++++++ .../server/scheduler/physical_contract.py | 112 +++++++-- 2 files changed, 325 insertions(+), 19 deletions(-) create mode 100644 tests/server/test_material_actions.py diff --git a/tests/server/test_material_actions.py b/tests/server/test_material_actions.py new file mode 100644 index 0000000000..ae071c71a3 --- /dev/null +++ b/tests/server/test_material_actions.py @@ -0,0 +1,232 @@ +"""``Material.move`` / ``pick`` / ``place`` 的调度解析(真实物料权威,不起调度器)。 + +- 所属方由库位 uuid 决定:载架(仓库)或设备根节点; +- 搬运设备省略即执行设备,写了是 ``DeviceSlot``(设备 id 解析成设备物料); +- 两步搬运:pick 后物料在夹爪库位、托管搬运设备;place 后在目标库位、夹爪空出、托管释放。 +""" + +from __future__ import annotations + +import json +from uuid import uuid4 + +import pytest + +from tests.server.test_site_holder_placement import _mutation, _site, _warehouse +from unilabos.client.materials import LocalMaterialsClient +from unilabos.protocol.material_execution import MaterialExecutionPrepare, MaterialExecutionReceipt +from unilabos.protocol.materials import ( + MaterialIdentityWrite, + MaterialNodeCreate, + MaterialTreeCreate, + ResourceTemplateWrite, + SiteCreate, +) +from unilabos.registry.decorators import Material +from unilabos.registry.material_roles import material_contract +from unilabos.server.scheduler.physical_contract import resolve_physical_contract +from unilabos.server.scheduler.resource_wait_policy import ResourceConditionWait +from unilabos.server.services.materials import MaterialsService + +_DEVICE = {"type": "string", "description": "device reference", "x-unilabos-slot": "device"} +_SITE = {"type": "string", "description": "site reference (ResourceSite uuid)", "x-unilabos-slot": "site"} +_MATERIAL = {"type": "object", "properties": {"uuid": {"type": "string"}}, "required": ["uuid"], + "x-unilabos-material-lock": True} + + +@pytest.fixture +def authority(tmp_path): + service = MaterialsService(tmp_path / "materials.db") + service.set_resource_sync_dispatcher(lambda command: {"success": True}) + try: + yield service, LocalMaterialsClient(service) + finally: + service.close() + + +def _device(service, resource_id: str, sites: list[tuple[str, dict]]) -> str: + service.put_template( + _mutation("put_template"), + ResourceTemplateWrite(name=resource_id, display_name=resource_id, resource_type="device", class_name=resource_id), + ) + service.create_tree( + _mutation("create_material_tree"), + MaterialTreeCreate(nodes=[MaterialNodeCreate( + client_ref=resource_id, + identity=MaterialIdentityWrite(resource_id=resource_id, name=resource_id, resource_type="device", + class_name=resource_id, template_name=resource_id), + sites=[SiteCreate(template_name=resource_id, site_index=index, label=label, meta_data=meta) + for index, (label, meta) in enumerate(sites)], + )]), + ) + return service.get_material_by_resource_id(resource_id).material.material_uuid + + +def _schema(material, fields: dict) -> dict: + return { + "properties": {"goal": {"properties": fields}}, + "x-unilabos-action-contract": {"version": 2, "resource_contract": material_contract(material)}, + } + + +def _settle(service, plan) -> None: + ids = set(plan["material_ids"]) + for move in plan["moves"]: + ids.update({move.material_uuid, move.source_owner_uuid, move.target_owner_uuid}) + record = service.executions.prepare(MaterialExecutionPrepare( + job_uuid=str(uuid4()), task_uuid=str(uuid4()), claim_uuid=str(uuid4()), attempt_no=1, + parameter_hash="sha256:test", + fences={json.dumps(["material", item], separators=(",", ":")): 1 for item in ids}, + moves=plan["moves"], reserved_site_uuids=plan["reserved_site_uuids"], + )) + service.executions.settle(MaterialExecutionReceipt( + job_uuid=record["job_uuid"], claim_uuid=record["claim_uuid"], plan_hash=record["plan_hash"], + material_aliquot_receipts=[], material_transfer_receipts=plan["moves"], + )) + + +def _occupant(service, owner_uuid: str, label: str): + return _site(service, owner_uuid, label).occupied_material_uuid + + +def test_move_derives_the_owner_from_the_site_and_carries_with_the_executor(authority) -> None: + service, gateway = authority + source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") + arm = _device(service, "arm", [("grip", {"role": "gripper"})]) + sample = source["A01"].resource.unilabos_uuid + schema = _schema(Material.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + target_site = _site(service, target.unilabos_uuid, "A02").site_uuid + + plan = resolve_physical_contract(schema, {"plate": {"uuid": sample}, "target_site": target_site}, "arm", gateway) + + (move,) = plan["moves"] + assert (move.source_owner_uuid, move.source_site_uuid) == ( + source.unilabos_uuid, _site(service, source.unilabos_uuid, "A01").site_uuid) + assert (move.target_owner_uuid, move.target_site_uuid) == (target.unilabos_uuid, target_site) + # 搬运途中物料在执行设备的 gripper 库位上:动作期间预留它 + assert plan["reserved_site_uuids"] == [_site(service, arm, "grip").site_uuid] + assert "arm" in plan["device_ids"] + _settle(service, plan) + assert _occupant(service, target.unilabos_uuid, "A02") == sample + assert _occupant(service, source.unilabos_uuid, "A01") is None + + +def test_move_checks_a_given_from_site_against_the_authority(authority) -> None: + service, gateway = authority + source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") + _device(service, "arm", [("grip", {"role": "gripper"})]) + sample = source["A01"].resource.unilabos_uuid + schema = _schema( + Material.move("plate", to_site="target_site", from_site="source_site"), + {"plate": _MATERIAL, "target_site": _SITE, "source_site": _SITE}, + ) + values = {"plate": {"uuid": sample}, "target_site": _site(service, target.unilabos_uuid, "A02").site_uuid} + + plan = resolve_physical_contract( + schema, {**values, "source_site": _site(service, source.unilabos_uuid, "A01").site_uuid}, "arm", gateway) + assert plan["moves"][0].source_owner_uuid == source.unilabos_uuid + with pytest.raises(ResourceConditionWait): + resolve_physical_contract( + schema, {**values, "source_site": _site(service, source.unilabos_uuid, "A02").site_uuid}, "arm", gateway) + + +def test_move_onto_a_device_root_site_with_a_device_slot_carrier(authority) -> None: + """目标库位属于设备根节点;搬运设备是 DeviceSlot 参数(设备 id 解析成设备物料),不是执行设备。""" + + service, gateway = authority + source = _warehouse(gateway, "src") + _device(service, "executor", []) + mover = _device(service, "mover", [("hand", {"role": "gripper"})]) + reader = _device(service, "reader", [("S1", {}), ("S2", {})]) + sample = source["A01"].resource.unilabos_uuid + schema = _schema( + Material.move("plate", to_site="target_site", carrier_device="carrier_device"), + {"plate": _MATERIAL, "target_site": _SITE, "carrier_device": _DEVICE}, + ) + target_site = _site(service, reader, "S2").site_uuid + + plan = resolve_physical_contract( + schema, {"plate": {"uuid": sample}, "target_site": target_site, "carrier_device": "mover"}, "executor", gateway) + + (move,) = plan["moves"] + assert (move.target_owner_uuid, move.target_site_uuid) == (reader, target_site) + assert plan["reserved_site_uuids"] == [_site(service, mover, "hand").site_uuid] + assert {"mover", "reader"} <= set(plan["device_ids"]) + _settle(service, plan) + assert _occupant(service, reader, "S2") == sample + + +def test_move_without_a_gripper_site_is_a_contract_error(authority) -> None: + service, gateway = authority + source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") + _device(service, "arm", [("grip", {"role": "robot.gripper"})]) + schema = _schema(Material.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + with pytest.raises(ValueError, match="role=gripper"): + resolve_physical_contract(schema, { + "plate": {"uuid": source["A01"].resource.unilabos_uuid}, + "target_site": _site(service, target.unilabos_uuid, "A02").site_uuid, + }, "arm", gateway) + + +def test_pick_then_place_hold_the_material_on_the_gripper(authority) -> None: + """pick:物料到夹爪库位、托管搬运设备;place:物料到目标库位、夹爪空出、托管释放。""" + + service, gateway = authority + source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") + arm = _device(service, "arm", [("grip", {"role": "gripper"})]) + sample = source["A01"].resource.unilabos_uuid + grip = _site(service, arm, "grip").site_uuid + + pick = _schema(Material.pick("plate"), {"plate": _MATERIAL}) + plan = resolve_physical_contract(pick, {"plate": {"uuid": sample}}, "arm", gateway) + (move,) = plan["moves"] + assert (move.target_owner_uuid, move.target_site_uuid) == (arm, grip) + assert plan["device_tenancy"].acquire_device_id == "arm" + assert plan["device_tenancy"].release_device_id is None + _settle(service, plan) + assert _occupant(service, arm, "grip") == sample + assert _occupant(service, source.unilabos_uuid, "A01") is None + + place = _schema(Material.place("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + target_site = _site(service, target.unilabos_uuid, "A03").site_uuid + plan = resolve_physical_contract(place, {"plate": {"uuid": sample}, "target_site": target_site}, "arm", gateway) + (move,) = plan["moves"] + assert (move.source_owner_uuid, move.source_site_uuid) == (arm, grip) + assert (move.target_owner_uuid, move.target_site_uuid) == (target.unilabos_uuid, target_site) + assert plan["device_tenancy"].release_device_id == "arm" + _settle(service, plan) + assert _occupant(service, target.unilabos_uuid, "A03") == sample + assert _occupant(service, arm, "grip") is None + + +def test_pick_with_a_from_site_that_disagrees_waits(authority) -> None: + service, gateway = authority + source = _warehouse(gateway, "src") + _device(service, "arm", [("grip", {"role": "gripper"})]) + schema = _schema(Material.pick("plate", from_site="from_site"), {"plate": _MATERIAL, "from_site": _SITE}) + values = {"plate": {"uuid": source["A01"].resource.unilabos_uuid}} + resolve_physical_contract(schema, {**values, "from_site": _site(service, source.unilabos_uuid, "A01").site_uuid}, + "arm", gateway) + with pytest.raises(ResourceConditionWait): + resolve_physical_contract( + schema, {**values, "from_site": _site(service, source.unilabos_uuid, "A02").site_uuid}, "arm", gateway) + + +def test_place_with_a_device_slot_carrier_releases_that_device(authority) -> None: + service, gateway = authority + source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") + _device(service, "executor", []) + arm = _device(service, "arm", [("grip", {"role": "gripper"})]) + sample = source["A01"].resource.unilabos_uuid + pick = _schema(Material.pick("plate", carrier_device="arm_device"), {"plate": _MATERIAL, "arm_device": _DEVICE}) + plan = resolve_physical_contract(pick, {"plate": {"uuid": sample}, "arm_device": "arm"}, "executor", gateway) + assert plan["device_tenancy"].acquire_device_id == "arm" + _settle(service, plan) + place = _schema(Material.place("plate", to_site="to_site", carrier_device="arm_device"), + {"plate": _MATERIAL, "to_site": _SITE, "arm_device": _DEVICE}) + plan = resolve_physical_contract(place, { + "plate": {"uuid": sample}, "arm_device": "arm", + "to_site": _site(service, target.unilabos_uuid, "A02").site_uuid, + }, "executor", gateway) + assert plan["device_tenancy"].release_device_id == "arm" + assert plan["moves"][0].source_owner_uuid == arm diff --git a/unilabos/server/scheduler/physical_contract.py b/unilabos/server/scheduler/physical_contract.py index aef7aecb26..79d37c430c 100644 --- a/unilabos/server/scheduler/physical_contract.py +++ b/unilabos/server/scheduler/physical_contract.py @@ -1,4 +1,9 @@ -"""将动作资源合同解析为权威物料、完整库位和托管范围。""" +"""将动作资源合同解析为权威物料、完整库位和托管范围。 + +``Material.move`` / ``pick`` / ``place`` 规范化成 ``transfer`` / ``transfer_step``:目标与来源按库位 uuid 给出时, +所属方(载架或设备根节点)由库位决定;搬运设备参数(``DeviceSlot``,设备 id)解析成该设备的物料,省略时是 +执行设备。旧合同里显式的所属物料参数(ResourceSlot)照旧可用。 +""" from __future__ import annotations @@ -9,6 +14,33 @@ from .resource_wait_policy import ResourceConditionWait +def site_owner_material_uuid(materials: Any, site_uuid: str) -> str | None: + """库位 uuid → 所属物料 uuid(载架或设备根节点);库位不存在(或已删除)时为 ``None``。""" + + reader = getattr(materials, "site_admission_facts", None) + if not callable(reader) or not isinstance(site_uuid, str) or not site_uuid.strip(): + return None + try: + # 物料网关(嵌入 / HTTP)收一个请求体;物料服务本身收关键字参数 + result = reader({"site_uuids": [site_uuid]}) + except TypeError: + result = reader(site_uuids=[site_uuid]) + facts = (result or {}).get("sites", {}).get(site_uuid) or {} + if not facts.get("exists"): + return None + owner = facts.get("owner_material_uuid") + return str(owner) if owner else None + + +def device_material_uuid(materials: Any, device_id: str) -> str: + """设备 id(``DeviceSlot`` 的值)→ 该设备在物料权威里的物料 uuid;不是已登记设备时报错。""" + + aggregate = materials.get_material_by_resource_id(device_id) + if aggregate.material.resource_type != "device" or aggregate.material.resource_id != device_id: + raise ValueError(f"{device_id} 不是已登记的设备") + return aggregate.material.material_uuid + + def resolve_physical_contract( schema: Mapping[str, Any] | None, values: dict[str, Any], device_id: str, materials: Any ) -> dict[str, Any]: @@ -25,6 +57,22 @@ def resource(name): raise ValueError(f"物理参数 {name} 缺少 ResourceSlot 身份") return value["uuid"] + def holder(name): + """搬运设备 / 所属方参数:``DeviceSlot`` 的设备 id 解析成设备物料,旧合同的 ``ResourceSlot`` 照旧。""" + + value = values.get(name) + if isinstance(value, str): + if not value.strip(): + raise ValueError(f"设备参数 {name} 必须给出设备 id") + try: + return device_material_uuid(materials, value) + except ValueError as error: + raise ValueError(f"设备参数 {name}:{error}") from None + return resource(name) + + def executor(): + return materials.get_material_by_resource_id(device_id).material.material_uuid + def aggregate(identity): result = materials.get_material(identity) ids.add(identity) @@ -51,6 +99,17 @@ def site(owner, selected): raise ValueError("库位选择必须唯一且可见") return matches[0] + def site_by_uuid(name): + """库位参数(``SiteSlot``,库位 uuid)→ ``(所属物料, 库位)``;所属方由库位决定。""" + + selected = values.get(name) + if not isinstance(selected, str) or not selected.strip(): + raise ValueError(f"库位参数 {name} 必须给出库位 uuid") + owner = site_owner_material_uuid(materials, selected) + if owner is None: + raise ValueError(f"库位参数 {name} 指向不存在的库位 {selected}") + return owner, site(owner, selected) + def location(identity): parent = aggregate(identity).material.parent_material_uuid if not parent: @@ -76,7 +135,7 @@ def gripper(owners, role, material): (owner, item) for owner in owners for item in aggregate(owner).sites if item.meta_data.get("role") == role ] if len(matches) != 1 or not matches[0][1].visible: - raise ValueError("搬运器必须有唯一可用的夹爪库位角色") + raise ValueError(f"搬运设备必须有唯一可见的夹爪库位(meta_data.role={role})") if matches[0][1].occupied_material_uuid not in (None, material): raise ResourceConditionWait("gripper_site_occupied", "搬运器的夹爪库位正被其他物料占用") reserved_sites.add(matches[0][1].site_uuid) @@ -100,23 +159,30 @@ def gripper(owners, role, material): identity = resource(transfer["material_param"]) source_owner, source_site = location(identity) ids.update(item.material.material_uuid for item in materials.get_tree(identity).nodes) - target_owner = resource(transfer["target_owner_param"]) - target = site( - target_owner, - values.get(transfer.get("target_site_uuid_param")) or values.get(transfer.get("target_site_name_param")), - ) + if transfer.get("target_owner_param"): + target_owner = resource(transfer["target_owner_param"]) + target = site( + target_owner, + values.get(transfer.get("target_site_uuid_param")) or values.get(transfer.get("target_site_name_param")), + ) + else: + target_owner, target = site_by_uuid(transfer["target_site_uuid_param"]) + requested = None if transfer.get("source_owner_param"): requested_owner = resource(transfer["source_owner_param"]) - requested_site = site( + requested = (requested_owner, site( requested_owner, values.get(transfer.get("source_site_uuid_param")) or values.get(transfer.get("source_site_name_param")), - ) - if (requested_owner, requested_site.site_uuid) != (source_owner, source_site): - raise ResourceConditionWait("transfer_source_site_missing", "声明的搬运来源与权威库位不一致", - material_uuid=identity) - executor = materials.get_material_by_resource_id(device_id) - gripper([executor.material.material_uuid], transfer["gripper_site_role"], identity) + ).site_uuid) + elif transfer.get("source_site_uuid_param") and values.get(transfer["source_site_uuid_param"]): + requested_owner, requested_site = site_by_uuid(transfer["source_site_uuid_param"]) + requested = (requested_owner, requested_site.site_uuid) + if requested is not None and requested != (source_owner, source_site): + raise ResourceConditionWait("transfer_source_site_missing", "声明的搬运来源与权威库位不一致", + material_uuid=identity) + carrier = holder(transfer["carrier_device_param"]) if transfer.get("carrier_device_param") else executor() + gripper([carrier], transfer["gripper_site_role"], identity) owner_device(target_owner) moves.append( PhysicalMove( @@ -134,15 +200,22 @@ def gripper(owners, role, material): identity = resource(step["material_param"]) source_owner, source_site = location(identity) ids.update(item.material.material_uuid for item in materials.get_tree(identity).nodes) - end_owner = resource(step["owner_param"]) - end_site = site(end_owner, values.get(step["site_param"])) - carriers = [resource(name) for name in step["carrier_params"]] + end_owner, end_site = None, None + if step.get("owner_param"): + end_owner = resource(step["owner_param"]) + end_site = site(end_owner, values.get(step["site_param"])) + elif step.get("site_param") and values.get(step["site_param"]): + end_owner, end_site = site_by_uuid(step["site_param"]) + elif step["operation"] == "place": + raise ValueError(f"放置动作缺少目标库位参数 {step.get('site_param') or ''}") + carriers = [holder(name) for name in step["carrier_params"]] or [executor()] carrier, grip = gripper(carriers, "gripper", identity) carrier_device = owner_device(carrier) if not carrier_device: raise ValueError("分步搬运的夹爪必须归属于设备,才能跨动作托管") if step["operation"] == "pick": - if (source_owner, source_site) != (end_owner, end_site.site_uuid): + # from_site 省略时从权威当前位置抓取;给出时必须与权威一致 + if end_owner is not None and (source_owner, source_site) != (end_owner, end_site.site_uuid): raise ResourceConditionWait("transfer_source_site_missing", "抓取来源与权威库位不一致", material_uuid=identity) target_owner, target_site = carrier, grip.site_uuid @@ -152,7 +225,8 @@ def gripper(owners, role, material): raise ValueError("放置前样品必须仍托管在指定夹爪") target_owner, target_site = end_owner, end_site.site_uuid tenancy = DeviceTenancyTransition(material_uuid=identity, release_device_id=carrier_device) - owner_device(end_owner) + if end_owner is not None: + owner_device(end_owner) moves.append( PhysicalMove( material_uuid=identity, From 1463a3a7c86131430f877a77ac237434ecd6d0ff Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:46:29 +0800 Subject: [PATCH 10/27] feat(scheduler)!: lock DeviceSlot and SiteSlot parameters by type Parameters are locked by their type instead of Material.uses: - every DeviceSlot / list[DeviceSlot] value must name a registered device and adds a device lock (device_claims); - every SiteSlot value that is a registered site uuid adds a site lock on "owner material + site" (new site_claims on the resource request, part of the interval admission keys); site labels and empty values are not locked. Material.load / unload without a device hold the executing device (the "$executor" marker in the tenancy contract). --- tests/server/test_material_actions.py | 61 +++++++++++++- unilabos/server/scheduler/models.py | 8 ++ unilabos/server/scheduler/tenancy_contract.py | 80 ++++++++++++++++--- .../runtime/workflow/resource_intervals.py | 4 +- 4 files changed, 140 insertions(+), 13 deletions(-) diff --git a/tests/server/test_material_actions.py b/tests/server/test_material_actions.py index ae071c71a3..1247fb0690 100644 --- a/tests/server/test_material_actions.py +++ b/tests/server/test_material_actions.py @@ -1,8 +1,9 @@ -"""``Material.move`` / ``pick`` / ``place`` 的调度解析(真实物料权威,不起调度器)。 +"""``Material.move`` / ``pick`` / ``place`` 的调度解析与按类型加锁(真实物料权威,不起调度器)。 - 所属方由库位 uuid 决定:载架(仓库)或设备根节点; - 搬运设备省略即执行设备,写了是 ``DeviceSlot``(设备 id 解析成设备物料); -- 两步搬运:pick 后物料在夹爪库位、托管搬运设备;place 后在目标库位、夹爪空出、托管释放。 +- 两步搬运:pick 后物料在夹爪库位、托管搬运设备;place 后在目标库位、夹爪空出、托管释放; +- ``DeviceSlot`` 参数加设备锁,``SiteSlot`` 参数加库位锁,``load`` 省略设备即执行设备。 """ from __future__ import annotations @@ -12,7 +13,7 @@ import pytest -from tests.server.test_site_holder_placement import _mutation, _site, _warehouse +from tests.server.test_site_holder_placement import _bottle, _mutation, _site, _warehouse from unilabos.client.materials import LocalMaterialsClient from unilabos.protocol.material_execution import MaterialExecutionPrepare, MaterialExecutionReceipt from unilabos.protocol.materials import ( @@ -24,9 +25,14 @@ ) from unilabos.registry.decorators import Material from unilabos.registry.material_roles import material_contract +from unilabos.resources import materials +from unilabos.server.scheduler.models import SchedulerResourceRequest from unilabos.server.scheduler.physical_contract import resolve_physical_contract +from unilabos.server.scheduler.resource_keys import device_lock_key, site_lock_key from unilabos.server.scheduler.resource_wait_policy import ResourceConditionWait +from unilabos.server.scheduler.tenancy_contract import resolve_tenancy_contract from unilabos.server.services.materials import MaterialsService +from unilabos.server.services.runtime.workflow.resource_intervals import physical_keys _DEVICE = {"type": "string", "description": "device reference", "x-unilabos-slot": "device"} _SITE = {"type": "string", "description": "site reference (ResourceSite uuid)", "x-unilabos-slot": "site"} @@ -230,3 +236,52 @@ def test_place_with_a_device_slot_carrier_releases_that_device(authority) -> Non }, "executor", gateway) assert plan["device_tenancy"].release_device_id == "arm" assert plan["moves"][0].source_owner_uuid == arm + + +def test_parameters_are_locked_by_type(authority) -> None: + """DeviceSlot(含列表)加设备锁、SiteSlot 加库位锁;空值与不是库位 uuid 的值不加锁。""" + + service, gateway = authority + warehouse = _warehouse(gateway, "wh") + _device(service, "executor", []) + _device(service, "probe_a", []) + _device(service, "probe_b", []) + site = _site(service, warehouse.unilabos_uuid, "A02").site_uuid + schema = {"properties": {"goal": {"properties": { + "probe": _DEVICE, "probes": {"type": "array", "items": _DEVICE}, "spare": _DEVICE, + "slot": _SITE, "label_slot": _SITE, "name": {"type": "string"}, + }}}, "x-unilabos-action-contract": {"version": 2}} + values = {"probe": "probe_a", "probes": ["probe_b"], "spare": "", "slot": site, "label_slot": "A01", "name": "x"} + + tenancy = resolve_tenancy_contract(schema, values, "executor", gateway) + + assert tenancy["device_claims"] == ["probe_a", "probe_b"] + (claim,) = tenancy["site_claims"] + assert (claim.owner_material_uuid, claim.site_uuid) == (warehouse.unilabos_uuid, site) + request = SchedulerResourceRequest(request_uuid="r", owner_uuid="job", task_uuid="task", **tenancy) + assert physical_keys(request) == { + device_lock_key("probe_a"), device_lock_key("probe_b"), site_lock_key(warehouse.unilabos_uuid, site), + } + with pytest.raises(Exception): + resolve_tenancy_contract(schema, {**values, "probe": "no_such_device"}, "executor", gateway) + assert resolve_tenancy_contract(schema, {"name": "x"}, "executor", gateway) == {} + + +def test_load_without_a_device_holds_the_executing_device(authority) -> None: + service, gateway = authority + vial = materials.create(_bottle("vial"), gateway=gateway) + _device(service, "reactor", []) + _device(service, "shelf", []) + load = _schema(Material.load("sample"), {"sample": _MATERIAL}) + tenancy = resolve_tenancy_contract(load, {"sample": {"uuid": vial.unilabos_uuid}}, "reactor", gateway) + assert tenancy["device_tenancy"].acquire_device_id == "reactor" + assert tenancy["device_tenancy"].release_device_id is None + unload = _schema(Material.unload("sample"), {"sample": _MATERIAL}) + tenancy = resolve_tenancy_contract(unload, {"sample": {"uuid": vial.unilabos_uuid}}, "reactor", gateway) + assert tenancy["device_tenancy"].release_device_id == "reactor" + moved = _schema(Material.load("sample", from_device="from_device"), {"sample": _MATERIAL, "from_device": _DEVICE}) + tenancy = resolve_tenancy_contract( + moved, {"sample": {"uuid": vial.unilabos_uuid}, "from_device": "shelf"}, "reactor", gateway) + assert (tenancy["device_tenancy"].acquire_device_id, tenancy["device_tenancy"].release_device_id) == ( + "reactor", "shelf") + assert set(tenancy["device_claims"]) == {"reactor", "shelf"} diff --git a/unilabos/server/scheduler/models.py b/unilabos/server/scheduler/models.py index 64b9f18160..2f83854ea4 100644 --- a/unilabos/server/scheduler/models.py +++ b/unilabos/server/scheduler/models.py @@ -32,6 +32,13 @@ class MaterialLockClaim(ServerObject): material_uuid: NonEmptyStr +class SiteLockClaim(ServerObject): + """一个库位(``SiteSlot`` 参数按类型加的库位锁):所属物料 + 库位,锁键见 ``resource_keys.site_lock_key``。""" + + owner_material_uuid: NonEmptyStr + site_uuid: NonEmptyStr + + class ResourceLockIdentifier(ServerObject): """资源管理器内部和快照使用的规范锁身份。""" @@ -87,6 +94,7 @@ class SchedulerResourceRequest(ServerObject): always_free: bool = False interval_admission: bool = False device_claims: list[NonEmptyStr] = Field(default_factory=list) + site_claims: list[SiteLockClaim] = Field(default_factory=list) device_tenancy: DeviceTenancyTransition | None = None operate_in_place: DeviceTenancyRequirement | None = None action_lock_claims: list[ActionLockClaim] = Field(default_factory=list) diff --git a/unilabos/server/scheduler/tenancy_contract.py b/unilabos/server/scheduler/tenancy_contract.py index d395a5a248..48d7f7645b 100644 --- a/unilabos/server/scheduler/tenancy_contract.py +++ b/unilabos/server/scheduler/tenancy_contract.py @@ -1,5 +1,47 @@ -"""从冻结的动作合同和实际参数解析托管;设备使用物料权威的可读 resource_id。""" -from unilabos.server.scheduler.models import DeviceTenancyTransition, DeviceTenancyRequirement +"""从冻结的动作合同和实际参数解析托管与按类型的设备 / 库位锁;设备使用物料权威的可读 resource_id。 + +- 设备托管(``Material.load`` / ``unload``,实验性):设备参数是 ``DeviceSlot``,省略时(合同里的 + ``EXECUTING_DEVICE`` 记号)是执行设备; +- 按类型加锁:``DeviceSlot`` / ``list[DeviceSlot]`` 参数加设备锁(``device_claims``),``SiteSlot`` 参数加库位锁 + (``site_claims``,按「所属物料 + 库位」);字段由注册表标出 ``x-unilabos-slot``。空值不加锁,库位参数的值不是 + 已登记的库位 uuid(例如库位名)时不加库位锁。 +""" +from unilabos.registry.action_resource_contract import EXECUTING_DEVICE +from unilabos.server.scheduler.models import DeviceTenancyTransition, DeviceTenancyRequirement, SiteLockClaim + + +def slot_parameters(schema: dict | None, kind: str) -> list[str]: + """schema 里注解为 ``DeviceSlot``(``kind="device"``,含列表)或 ``SiteSlot``(``kind="site"``)的参数名。""" + + from unilabos.registry.action_schema import slot_kind + + fields = (((schema or {}).get("properties") or {}).get("goal") or {}).get("properties") or {} + return [name for name, field in fields.items() if slot_kind(field) in {kind, f"{kind}_list"}] + + +def _slot_values(value) -> list[str]: + if isinstance(value, str): + return [value] if value.strip() else [] + if isinstance(value, list): + return [item for item in value if isinstance(item, str) and item.strip()] + return [] + + +def resolve_site_claims(schema: dict | None, values: dict, materials) -> list[SiteLockClaim]: + """``SiteSlot`` 参数 → 库位锁(所属物料 + 库位);值不是已登记的库位 uuid 时不加锁。""" + + names = slot_parameters(schema, "site") + if not names or materials is None: + return [] + from .physical_contract import site_owner_material_uuid + + claims: dict[tuple[str, str], SiteLockClaim] = {} + for name in names: + for site_uuid in _slot_values(values.get(name)): + owner = site_owner_material_uuid(materials, site_uuid) + if owner: + claims[(owner, site_uuid)] = SiteLockClaim(owner_material_uuid=owner, site_uuid=site_uuid) + return [claims[key] for key in sorted(claims)] def resolve_tenancy_contract(schema: dict | None, values: dict, device_id: str, materials) -> dict: @@ -10,7 +52,10 @@ def resolve_tenancy_contract(schema: dict | None, values: dict, device_id: str, devices.update(item["param"] for item in contract.get("resource_params", []) if item["role"] in {"device","motion"}) if transition: devices.update(transition[name] for name in ("acquire_device_param","release_device_param") if transition.get(name)) - if not (transition or in_place or devices): + # 按类型加锁:DeviceSlot 参数(含列表)一律加设备锁,空值不加 + typed_devices = [name for name in slot_parameters(schema, "device") if _slot_values(values.get(name))] + site_claims = resolve_site_claims(schema, values, materials) + if not (transition or in_place or devices or typed_devices or site_claims): return {} def identity(name): @@ -19,16 +64,22 @@ def identity(name): raise ValueError(f"资源参数 {name} 缺少物料身份") return value["uuid"] + def registered(name, value): + if not value.strip() or value != value.strip(): + raise ValueError(f"设备参数 {name} 必须给出非空 ID") + aggregate = materials.get_material_by_resource_id(value) + if aggregate.material.resource_id != value: + raise ValueError(f"设备参数 {name} 的身份映射不一致") + return aggregate + def device(name): + if name == EXECUTING_DEVICE: + return device_id if materials is None: raise ValueError("设备托管需要物料权威解析设备身份") value = values.get(name) if isinstance(value, str): - if not value.strip() or value != value.strip(): - raise ValueError(f"设备参数 {name} 必须给出非空 ID") - aggregate = materials.get_material_by_resource_id(value) - if aggregate.material.resource_id != value: - raise ValueError(f"设备参数 {name} 的身份映射不一致") + aggregate = registered(name, value) else: aggregate = materials.get_material(identity(name)) if aggregate.material.resource_type != "device" or not aggregate.material.resource_id: @@ -36,7 +87,18 @@ def device(name): return aggregate.material.resource_id ids = {name: device(name) for name in devices} - result = {"device_claims": sorted(set(ids.values()))} + claimed = set(ids.values()) + for name in typed_devices: + if materials is None: + raise ValueError("设备参数需要物料权威解析设备身份") + for value in _slot_values(values.get(name)): + aggregate = registered(name, value) + if aggregate.material.resource_type != "device": + raise ValueError(f"设备参数 {name} 必须指向已登记设备") + claimed.add(value) + result = {"device_claims": sorted(claimed)} + if site_claims: + result["site_claims"] = site_claims if transition: result["device_tenancy"] = DeviceTenancyTransition(material_uuid=identity(transition["material_param"]), acquire_device_id=ids.get(transition.get("acquire_device_param")), diff --git a/unilabos/server/services/runtime/workflow/resource_intervals.py b/unilabos/server/services/runtime/workflow/resource_intervals.py index d58781f782..6123194f61 100644 --- a/unilabos/server/services/runtime/workflow/resource_intervals.py +++ b/unilabos/server/services/runtime/workflow/resource_intervals.py @@ -7,7 +7,7 @@ from unilabos.protocol.utils.json_codec import encode_json, decode_json_bytes from unilabos.server.scheduler.models import SchedulerResourceRequest -from unilabos.server.scheduler.resource_keys import device_lock_key, material_lock_key +from unilabos.server.scheduler.resource_keys import device_lock_key, material_lock_key, site_lock_key from unilabos.server.scheduler.resource_plan import deserialize_resource_plan, validate_station_resource_plans from .errors import StoreConflict from .device_tenancy import DeviceTenancies @@ -37,6 +37,8 @@ def physical_keys(request: SchedulerResourceRequest) -> set[str]: if request.current_action and not request.always_free: keys.add(device_lock_key(request.current_action.device_id)) keys.update(device_lock_key(value) for value in request.device_claims) + # SiteSlot 参数按类型加的库位锁(所属物料 + 库位) + keys.update(site_lock_key(item.owner_material_uuid, item.site_uuid) for item in request.site_claims) if request.device_tenancy: transition = request.device_tenancy keys.update(device_lock_key(value) for value in (transition.acquire_device_id, transition.release_device_id) if value) From 9af7599744f4f99dfe2bc5dc0e778181d25e1ec8 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:47:19 +0800 Subject: [PATCH 11/27] feat(workflow): check DeviceSlot values and device-owned site pickers validate_resource_values (run preflight, scheduler dispatch and the Host gate) now: - checks every DeviceSlot / list[DeviceSlot] value names a registered, usable device whenever a materials authority is available; - takes the executing device id, so a Material.site_picker without `of` checks the selected site against the executing device's root, and an `of` that is a DeviceSlot checks it against that device's root. --- tests/server/test_material_actions.py | 42 +++++++++++++++ unilabos/client/host/execution.py | 2 +- unilabos/server/scheduler/service.py | 2 +- .../runtime/workflow/run_preflight.py | 51 ++++++++++++++----- 4 files changed, 83 insertions(+), 14 deletions(-) diff --git a/tests/server/test_material_actions.py b/tests/server/test_material_actions.py index 1247fb0690..dcad982be9 100644 --- a/tests/server/test_material_actions.py +++ b/tests/server/test_material_actions.py @@ -285,3 +285,45 @@ def test_load_without_a_device_holds_the_executing_device(authority) -> None: assert (tenancy["device_tenancy"].acquire_device_id, tenancy["device_tenancy"].release_device_id) == ( "reactor", "shelf") assert set(tenancy["device_claims"]) == {"reactor", "shelf"} + + +def test_site_picker_owned_by_a_device_is_checked_against_the_device_root(authority) -> None: + """site_picker 省略 of 时库位属于执行设备根节点,of 是 DeviceSlot 时属于该设备;DeviceSlot 值必须是已登记设备。""" + + from unilabos.registry.material_roles import material_site_selectors + from unilabos.server.services.runtime.workflow.run_preflight import ( + ResourceUnavailableError, + validate_resource_values, + ) + + service, gateway = authority + warehouse = _warehouse(gateway, "wh") + reader = _device(service, "reader", [("S1", {}), ("S2", {})]) + other = _device(service, "other", [("T1", {})]) + vial = materials.create(_bottle("vial"), gateway=gateway) + + def schema(picker, fields): + site_field = {**_SITE, "x-unilabos-site-selector": material_site_selectors(picker)["site"]} + return {"properties": {"goal": {"properties": {**fields, "site": site_field}}}, + "x-unilabos-action-contract": {"version": 2}} + + own = schema(Material.site_picker("site", for_material="sample"), {"sample": _MATERIAL}) + values = {"sample": {"uuid": vial.unilabos_uuid}} + validate_resource_values(own, {**values, "site": _site(service, reader, "S1").site_uuid}, gateway, device_id="reader") + with pytest.raises(ValueError, match="不属于所选容器"): + validate_resource_values(own, {**values, "site": _site(service, other, "T1").site_uuid}, gateway, + device_id="reader") + with pytest.raises(ValueError, match="不属于所选容器"): + validate_resource_values(own, {**values, "site": _site(service, warehouse.unilabos_uuid, "A02").site_uuid}, + gateway, device_id="reader") + + of_device = schema(Material.site_picker("site", of="target_device", for_material="sample"), + {"sample": _MATERIAL, "target_device": _DEVICE}) + validate_resource_values(of_device, {**values, "target_device": "other", + "site": _site(service, other, "T1").site_uuid}, gateway, device_id="reader") + with pytest.raises(ValueError, match="不属于所选容器"): + validate_resource_values(of_device, {**values, "target_device": "other", + "site": _site(service, reader, "S2").site_uuid}, gateway, device_id="reader") + with pytest.raises((ValueError, ResourceUnavailableError)): + validate_resource_values(of_device, {**values, "target_device": "nowhere", + "site": _site(service, other, "T1").site_uuid}, gateway, device_id="reader") diff --git a/unilabos/client/host/execution.py b/unilabos/client/host/execution.py index 2055dce970..4ddee1bcac 100644 --- a/unilabos/client/host/execution.py +++ b/unilabos/client/host/execution.py @@ -2035,7 +2035,7 @@ def _start_goal(self, job: JobInfo) -> None: from unilabos.server.services.runtime.workflow.run_preflight import validate_resource_values gateway = self._inventory_authority.gateway if self._inventory_authority is not None else None - validate_resource_values(schema, job.action_args, gateway) + validate_resource_values(schema, job.action_args, gateway, device_id=job.device_id) except ValueError as error: self._reject_job(job, str(error), "TypedActionValueError") return diff --git a/unilabos/server/scheduler/service.py b/unilabos/server/scheduler/service.py index e39efb3dca..7dad5377fc 100644 --- a/unilabos/server/scheduler/service.py +++ b/unilabos/server/scheduler/service.py @@ -1590,7 +1590,7 @@ def _resolve_resource_contracts( if spec.get("param_schema"): from unilabos.server.services.runtime.workflow.run_preflight import validate_resource_values - validate_resource_values(spec["param_schema"], args, self.materials_gateway) + validate_resource_values(spec["param_schema"], args, self.materials_gateway, device_id=node.device_id) from .physical_contract import resolve_physical_contract physical = resolve_physical_contract(spec.get("param_schema"), args, node.device_id, self.materials_gateway) material_uuids.update(physical.get("material_ids", [])) diff --git a/unilabos/server/services/runtime/workflow/run_preflight.py b/unilabos/server/services/runtime/workflow/run_preflight.py index 0c55640388..a7909327ef 100644 --- a/unilabos/server/services/runtime/workflow/run_preflight.py +++ b/unilabos/server/services/runtime/workflow/run_preflight.py @@ -229,7 +229,7 @@ def check(kind: str, status: str, code: str, message: str, *, node=None, details if schema and "x-unilabos-action-contract" in schema: try: values = validate_action_values(schema, node["param"], deferred=pending, managed_resources=True) - validate_resource_values(schema, values, materials, deferred=pending) + validate_resource_values(schema, values, materials, deferred=pending, device_id=device or None) check("action_contract", "passed", "action_contract_ready", "静态动作参数符合合同", node=node) except ResourceUnavailableError as error: check("resources", "blocked", "resource_unavailable", str(error), node=node) @@ -283,9 +283,14 @@ def finalize(report: dict[str, Any]) -> dict[str, Any]: def validate_resource_values( schema: Mapping[str, Any], values: Mapping[str, Any], materials: Any, - *, deferred: Sequence[str] = (), + *, deferred: Sequence[str] = (), device_id: str | None = None, ) -> None: - """校验已知物料身份及库位参数(Material.site 声明的库位关系)的归属/占用;预检与派发共用。""" + """校验已知物料身份、设备参数及库位参数(Material.site_picker 声明的库位关系)的归属/占用;预检与派发共用。 + + ``device_id`` 是执行设备:``site_picker`` 省略 ``of`` 时库位属于它的根节点(不给时跳过这条核对)。 + """ + from unilabos.registry.action_resource_contract import EXECUTING_DEVICE + from unilabos.server.scheduler.tenancy_contract import slot_parameters fields = schema.get("properties", {}).get("goal", {}).get("properties", {}) def material(identity: str | None, name: str) -> Any: @@ -315,21 +320,34 @@ def resources(field: Mapping[str, Any], value: Any) -> list[str]: device_parameters.update(item["param"] for item in contract.get("resource_params", []) if item["role"] in {"device","motion"}) tenancy = contract.get("device_tenancy") or {} device_parameters.update(tenancy[field] for field in ("acquire_device_param","release_device_param") if tenancy.get(field)) - for name in device_parameters: - if name in deferred or name not in values or not isinstance(values[name], str): - continue + device_parameters.discard(EXECUTING_DEVICE) + # 按类型:DeviceSlot 参数(含列表)都要指向已登记设备(派发时按它加设备锁);没有物料权威时(如 Host 本地)不核对 + if materials is not None: + device_parameters.update(slot_parameters(schema, "device")) + + def device_aggregate(name: str, value: str) -> Any: if materials is None: raise ResourceUnavailableError("物料权威尚未接入,无法校验设备 ID") try: - aggregate = materials.get_material_by_resource_id(values[name]) + aggregate = materials.get_material_by_resource_id(value) except (RuntimeError, OSError) as error: if getattr(error,"code",None) == "not_found": - raise ValueError(f"设备参数 {name} 指向不存在的设备 {values[name]}") from None + raise ValueError(f"设备参数 {name} 指向不存在的设备 {value}") from None raise ResourceUnavailableError(f"无法读取设备参数 {name}:{error}") from error - if aggregate.material.resource_type != "device" or aggregate.material.resource_id != values[name]: + if aggregate.material.resource_type != "device" or aggregate.material.resource_id != value: raise ValueError(f"设备参数 {name} 不是有效的设备 ID") - if aggregate.material.lifecycle_status in {"quarantined","consumed","disposed","deleted","retired"}: - raise ResourceUnavailableError(f"设备参数 {name} 当前不可用") + return aggregate + + for name in device_parameters: + if name in deferred or name not in values: + continue + raw = values[name] + for value in ([raw] if isinstance(raw, str) else raw if isinstance(raw, list) else []): + if not isinstance(value, str) or not value.strip(): + continue + aggregate = device_aggregate(name, value) + if aggregate.material.lifecycle_status in {"quarantined","consumed","disposed","deleted","retired"}: + raise ResourceUnavailableError(f"设备参数 {name} 当前不可用") for name, field in fields.items(): if name in deferred or name not in values: continue @@ -356,7 +374,16 @@ def resources(field: Mapping[str, Any], value: Any) -> list[str]: if selector and values[name] is not None: if selector["owner"] in deferred or selector.get("occupant") in deferred: continue - owner = (values.get(selector["owner"]) or {}).get("uuid") + owner_value = values.get(selector["owner"]) if selector.get("owner") else device_id + if isinstance(owner_value, str): + # 所属方是设备(DeviceSlot 参数,或省略 of 时的执行设备):库位属于设备根节点 + if not owner_value.strip(): + continue + owner = device_aggregate(selector.get("owner") or name, owner_value).material.material_uuid + else: + owner = (owner_value or {}).get("uuid") + if not owner: + continue occupant = values.get(selector.get("occupant"), {}) or {} aggregate = material(owner, name) site = next((site for site in aggregate.sites if site.site_uuid == values[name]), None) From 2d88a9c897fd32cdaa1e44cbf571ff32137db011 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:47:20 +0800 Subject: [PATCH 12/27] docs(workflow): refer to Material.site_picker in site selection messages --- unilabos/server/api/envelope.py | 2 +- unilabos/server/services/runtime/workflow/service.py | 2 +- .../server/services/runtime/workflow/site_selections.py | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/unilabos/server/api/envelope.py b/unilabos/server/api/envelope.py index d73351e7d4..5e2b8e11e8 100644 --- a/unilabos/server/api/envelope.py +++ b/unilabos/server/api/envelope.py @@ -330,7 +330,7 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "material_site_invalid", # 工作流物料输入直接给的物料不是 @workflow(allowed_templates=...) 允许的模板(细节在 error.details) "material_template_mismatch", - # 库位参数按所属物料选择的写法不对(没有 Material.site 关系、放入物料不确定……,细节在 error.details) + # 库位参数按所属物料选择的写法不对(没有 Material.site_picker 关系、放入物料不确定……,细节在 error.details) "site_selection_invalid", }) diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 2ddd9f2565..1b9aab8df4 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -1534,7 +1534,7 @@ def build_plan(graph: Dict[str, Any]) -> Any: # 按库位绑定的物料参数解析成占用物料,计划、attempt 参数与任务输入一起冻结 self._bind_material_sites(plan, jobs, resolved["input"], site_facts, input_contract=declared_input_contract(graph["workflow"])) - # 按所属物料选择的库位参数在任务准入时由调度器选定;写法不对(没有 Material.site 关系、放入物料不确定、 + # 按所属物料选择的库位参数在任务准入时由调度器选定;写法不对(没有 Material.site_picker 关系、放入物料不确定、 # 与所属物料参数不一致)建任务时就拒绝 self._check_site_selections(plan) try: diff --git a/unilabos/server/services/runtime/workflow/site_selections.py b/unilabos/server/services/runtime/workflow/site_selections.py index 5b7ad583c3..92fbb02de9 100644 --- a/unilabos/server/services/runtime/workflow/site_selections.py +++ b/unilabos/server/services/runtime/workflow/site_selections.py @@ -1,9 +1,9 @@ """库位参数按所属物料选择:``{"owner_uuid": ...}`` 在任务准入时选定一个库位、经入口预留占住并冻结进任务。 -``SiteSlot`` 参数(带 ``Material.site("site", owner=..., occupant=...)`` 关系)可以给 +``SiteSlot`` 参数(带 ``Material.site_picker("site", of=..., for_material=...)`` 关系)可以给 ``{"owner_uuid": "<所属物料 uuid>"}`` 而不是库位 uuid,工作流入口参数(``SiteSlot``)也可以。规则: -- 候选是所属物料下接受放入物料(``Material.site`` 的 ``occupant`` 参数,按库位绑定的已先解析)的库位: +- 候选是所属物料下接受放入物料(``Material.site_picker`` 的 ``for_material`` 参数,按库位绑定的已先解析)的库位: 库位的接收规则(模板白名单与允许的资源类别)要接受它;按库位序号选第一个空着、没有被别的任务预留的; - 调度器在任务准入时(``BackendScheduler._admit_fresh_task``)用物料权威的入口预留占住选中的库位 (``owner_material_uuid`` 写法,预留随任务:``backend_task_uuid`` = 任务 uuid),再把库位 uuid 冻结进计划节点参数、 @@ -126,12 +126,12 @@ def owner_site_requests(plan: Mapping[str, Any]) -> list[SiteSelectionRequest]: selector = (fields.get(name) or {}).get("x-unilabos-site-selector") if not isinstance(selector, Mapping): raise SiteSelectionError( - NO_SITE_RELATION, f"{where} 按所属物料 {owner} 选库位:动作没有用 Material.site 声明这个库位参数的关系," + NO_SITE_RELATION, f"{where} 按所属物料 {owner} 选库位:动作没有用 Material.site_picker 声明这个库位参数的关系," "选不出接受放入物料的库位;请给库位 uuid", parameter=name, owner_uuid=owner, node_uuid=node_uuid) occupant_param = selector.get("occupant") if not occupant_param: raise SiteSelectionError( - OCCUPANT_UNDECLARED, f"{where} 按所属物料 {owner} 选库位:Material.site 没有声明 occupant(放进去的物料)," + OCCUPANT_UNDECLARED, f"{where} 按所属物料 {owner} 选库位:Material.site_picker 没有声明 for_material(放进去的物料)," "无法按库位的接收规则挑选", parameter=name, owner_uuid=owner, node_uuid=node_uuid) upstream = _upstream_parameters(plan, node_uuid) occupant = None if occupant_param in upstream else _material_uuid(param.get(occupant_param)) From 3ea1e2e6891ba4c2855f222acf1ab9268ea89cd4 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:48:50 +0800 Subject: [PATCH 13/27] docs: migrate guides and skills to the redesigned Material API --- .cursor/skills/add-device/SKILL.md | 14 ++++-- .cursor/skills/create-device-package/SKILL.md | 47 +++++++++++++------ AGENTS.md | 2 +- .../scheduling_and_execution.md | 2 +- docs/developer_guide/v1_file_index/rest.md | 6 +-- .../v1_file_index/scheduler.md | 2 +- tests/server/test_site_selection_by_owner.py | 2 +- 7 files changed, 49 insertions(+), 26 deletions(-) diff --git a/.cursor/skills/add-device/SKILL.md b/.cursor/skills/add-device/SKILL.md index 1ec1d58b25..1e80b68a58 100644 --- a/.cursor/skills/add-device/SKILL.md +++ b/.cursor/skills/add-device/SKILL.md @@ -159,17 +159,21 @@ from unilabos.registry.decorators import action auto_prefix=True, # 强制使用 auto- 前缀 parent=True, # 从父类 MRO 获取参数签名 ) -@action(material=Material.load("sample", device="vessel")) # 资源语义:一个字段,见下 +@action(material=Material.move("plate", to_site="target_site")) # 资源语义:一个字段,见下 ``` JSON 动作(不写 `action_type`)的参数与返回值只有一个标准:注册表按签名生成 schema,调度端与 Host 调用前按它校验参数, 调用后按返回注解校验返回值。写了类型的参数严格校验;没写类型或 `Any` 接受任意 JSON 值;没有默认值的参数必填。 -资源语义用 `material=Material.load / unload / in_place / pick / place / transfer / aliquot / uses / order_sensitive / site(...)`, -多个写成列表;库位参数注解为 `SiteSlot`,它属于哪个物料参数写 `Material.site("site", owner="carrier", occupant="sample")`。 +资源语义用 `material=`,声明动作真实的物料动作 `Material.move / pick / place / dispense(...)`,多个写成列表; +不代表物料动作的 `Material.load / unload / in_place / site_picker / order_sensitive(...)` 也写在这里,但属于实验性(注册时告警一次)。 +字符串都是参数名:物料 `ResourceSlot`、库位 `SiteSlot`(库位 uuid,所属方由库位决定)、设备 `DeviceSlot`(省略即执行设备)。 +库位选择器列出哪个所属方的库位写 `Material.site_picker("site", of="carrier", for_material="sample")`。 +`DeviceSlot` 参数加设备锁、`SiteSlot` 参数加库位锁,不需要额外声明。 前端选择器:物料 `ResourceSlot`、设备 `DeviceSlot`、库位 `SiteSlot` 自动推出,其他(节点、人工确认指派人、扣减……)或想换一种 显示时写 `@action(placeholder_keys={"参数名": PLACEHOLDER_...})`,两者取并集、同一参数以手写为准,只改显示不改类型。 -`contract=`、`resource_contract=`、JSON 动作的 `goal=` / `result=`,以及注解里的 `Placeholder(...)` / `SiteSelector(...)` 已删除, -写了报错。完整规则见 `docs/developer_guide/action_standard.md`。 +`contract=`、`resource_contract=`、JSON 动作的 `goal=` / `result=`,注解里的 `Placeholder(...)` / `SiteSelector(...)`, +以及 `Material.transfer / aliquot / site / uses` 和带 `owner` / `site` / `carriers` 的 `Material.pick / place` 已删除, +写了报错并给出新写法。完整规则见 `docs/developer_guide/action_standard.md`。 **自动识别规则:** - 带 `@action` 的公开方法 → 注册为动作(方法名即动作名) diff --git a/.cursor/skills/create-device-package/SKILL.md b/.cursor/skills/create-device-package/SKILL.md index 6f37b4f171..9e7d3b260c 100644 --- a/.cursor/skills/create-device-package/SKILL.md +++ b/.cursor/skills/create-device-package/SKILL.md @@ -117,13 +117,14 @@ class : - `always_free=True`:动作不占用设备 busy 队列,适合 `get_status`、`query_*`、`ping`、连接测试等轻量查询动作;会在 `action_value_mappings..always_free` 中写入 `true`。 - `feedback_interval`:动作反馈发布间隔,单位秒;AST 扫描默认补 `1.0`,长任务可调大,例如 `5.0`、`30.0`。 - `goal_default`:编辑器里的初始参数值,叠加在签名默认值上;它不让参数变成可选,没有签名默认值的参数仍然必填。 -- `material`:资源语义(装载托管、原位处理、搬运、分装、顺序敏感、库位关系),一个字段,值是 `Material` 的一个方法或列表,见下文「资源语义」。 +- `material`:资源语义(搬运、两步搬运、分装;实验性的装载托管、原位处理、库位选择器提示、顺序敏感),一个字段,值是 `Material` 的一个方法或列表,见下文「资源语义」。 - `placeholder_keys`:前端选择器 `{参数名: PLACEHOLDER_...}`。物料 `ResourceSlot`、设备 `DeviceSlot`、库位 `SiteSlot` 由类型自动推出; 节点、人工确认指派人、扣减等没有专门类型的选择器,或想把某个参数换一种显示,就在这里手写。两者取并集,同一参数以手写为准; 只改前端显示,参数类型与校验不变(兼容规则:手写成 `unilabos_resources` 的参数也加物料锁)。键必须是参数名。 - `handles`:动作级输入/输出端口,使用 `ActionInputHandle`、`ActionOutputHandle`;不写时按 schema 生成。 - 已删除、写了会报错的写法:`contract=`、`resource_contract=`、JSON 动作的 `goal=` / `result=` 重命名(参数名就是字段名), - 以及注解里的 `Placeholder(...)`(改成 `placeholder_keys=`)与 `SiteSelector(...)`(改成 `SiteSlot` + `Material.site(...)`)。 + 注解里的 `Placeholder(...)`(改成 `placeholder_keys=`)与 `SiteSelector(...)`(改成 `SiteSlot` + `Material.site_picker(...)`), + 以及 `Material.transfer / aliquot / site / uses`、带 `owner` / `site` / `carriers` 的 `Material.pick / place`(新写法见下文「资源语义」)。 参数与返回值只有一个标准,注册表按签名生成 schema,调度端与 Host 调用前校验参数,调用后按返回注解校验返回值: @@ -147,29 +148,47 @@ class : ```python from unilabos.registry.decorators import Material, action -from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="装载样品", material=Material.load("sample", device="vessel")) -def load_sample(self, sample: ResourceSlot, vessel: str) -> LoadResult: ... +@action(display_name="搬运板", material=Material.move("plate", to_site="target_site")) +def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... + +@action(display_name="抓取", material=Material.pick("plate")) +def pick_plate(self, plate: ResourceSlot) -> dict: ... + +@action(display_name="放下", material=Material.place("plate", to_site="target_site")) +def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... @action(display_name="原位搅拌", material=[Material.in_place("sample"), Material.order_sensitive()]) def stir(self, sample: ResourceSlot, rpm: int = 300) -> None: ... ``` +物料动作(稳定): + +| 写法 | 含义 | +| --- | --- | +| `Material.move("plate", to_site="site", from_site=None, carrier_device=None)` | 一个动作把容器搬到 `to_site`;所属方由库位决定,搬运途中在搬运设备的 `gripper` 夹爪库位上 | +| `Material.pick("plate", from_site=None, carrier_device=None)` | 两步搬运第一步:抓到搬运设备的夹爪库位,任务托管搬运设备 | +| `Material.place("plate", to_site="site", carrier_device=None)` | 两步搬运第二步:从夹爪库位放到 `to_site`,结束托管 | +| `Material.dispense(from_material="source", to_materials=["target", ...])` | 按实测量在容器之间转移内容物 | + +实验性(注册时告警一次): + | 写法 | 含义 | | --- | --- | -| `Material.load("sample", device="vessel")` / `Material.unload(...)` | 装进 / 取出设备,期间任务托管设备 | -| `Material.load("sample", device="b", from_device="a")` | 设备间转移 | +| `Material.load("sample", device=None, from_device=None)` / `Material.unload("sample", device=None)` | 装进 / 取出设备,期间任务托管设备;`device` 省略即执行设备,`from_device` 表示设备间转移 | | `Material.in_place("sample")` | 物料必须仍在执行设备内 | -| `Material.pick(...)` / `Material.place("sample", owner=, site=, carriers=[...])` | 两步搬运 | -| `Material.transfer("plate", to=, site=, gripper=, ...)` | 一次完成的机械臂搬运 | -| `Material.aliquot(source=, targets=[...])` | 按实测量分装 | -| `Material.uses(device=[...], tool=[...], motion=[...], site=[...], material=[...])` | 额外占用的资源参数 | +| `Material.site_picker("site", of=None, for_material=None, occupied="show")` | 库位选择器提示:`site` 列出 `of`(省略即执行设备根节点)的库位,放进去的是 `for_material`;`occupied` 取 `"hide"` / `"show"` / `"allow"` | | `Material.order_sensitive()` | 同一资源上的兄弟动作必须显式排序 | -| `Material.site("site", owner="carrier", occupant="sample", show_occupied=True, allow_occupied=False)` | 库位参数 `site`(`SiteSlot`)属于 `carrier`,放进去的是 `sample`;已占用库位是否列出 / 能否选 | -字符串都是参数名,注册时对照签名检查;物料参数必须是 `ResourceSlot`,设备参数可以是 `ResourceSlot` 或设备 ID 字符串; -`Material.site` 的库位参数必须是 `SiteSlot`,`owner` / `occupant` 必须是单个 `ResourceSlot`。 +字符串都是参数名,注册时对照签名检查:物料(`material`、`from_material`、`to_materials`、`for_material`)必须是单个 `ResourceSlot`; +库位(`to_site`、`from_site`、`site_picker` 的库位参数)必须是 `SiteSlot`(值是库位 uuid);设备(`carrier_device`、`device`、 +`from_device`)必须是 `DeviceSlot`(值是设备 id),省略就是执行设备;`site_picker` 的 `of` 是 `ResourceSlot` 或 `DeviceSlot`。 +搬运设备的夹爪库位 `meta_data.role` 统一为 `gripper`(有且只有一个)。参数按类型加锁:`ResourceSlot` 物料锁、`DeviceSlot` 设备锁、 +`SiteSlot` 库位锁。 + +用 `Material.move / pick / place` 声明了的搬运由核心按回执结算物料位置,驱动不要再对同一物料调用 `materials.transfer` / +`materials.assign`;`materials.*` 只用于没有声明的运行时变化(新建、写内容物、删除、启动对齐等)。 ### 3.2 `@topic_config` 规则 diff --git a/AGENTS.md b/AGENTS.md index f4635f868d..8f9bc6eac4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ pytest tests/resources/test_resourcetreeset_groups.py::test_name # single test ### Core Layers -**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one decorator field, `@action(material=Material.load(...) | [...])` (`registry/material_roles.py`); a site parameter is annotated `SiteSlot` and its relation to the material parameters is `Material.site(...)`, written into that field's `x-unilabos-site-selector` extension. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. +**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one decorator field, `@action(material=Material.move(...) | [...])` (`registry/material_roles.py`): the stable material actions are `Material.move` / `pick` / `place` / `dispense` (sites are `SiteSlot` uuids whose owner the scheduler derives from the site, carriers are `DeviceSlot` parameters defaulting to the executing device and its `gripper` site); `load` / `unload` / `in_place` / `site_picker` / `order_sensitive` stay in `material=` but are experimental (warned once per definition). A site parameter is annotated `SiteSlot`; `Material.site_picker(...)` writes the selector hint into that field's `x-unilabos-site-selector` extension. `Material.transfer` / `aliquot` / `site` / `uses` and `pick` / `place` with `owner` / `site` / `carriers` are rejected with the new spelling. Parameters are locked by type: `ResourceSlot` material locks, `DeviceSlot` device locks, `SiteSlot` site locks. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. **Resource Tracking** (`unilabos/resources/resource_tracker.py`): Pydantic-based `ResourceDict` → `ResourceDictInstance` → `ResourceTreeSet` hierarchy. `ResourceTreeSet` is the canonical in-memory representation of all devices and resources, used throughout the system, and it owns every resource conversion: flat dicts (`from_raw_dict_list`, `dump`/`load`) and PLR (`from_plr_resources`, `to_plr_resources`). PLR drafts from a registry resource class come from `resources/materials.py:instantiate_registry_resource`. There is no separate graph I/O module: device graphs are node-link JSON only (GraphML is not supported) and are turned into runtime structures by the Graph Authority (`server/services/materials/graph.py:load_graph_payload`). diff --git a/docs/developer_guide/scheduling_and_execution.md b/docs/developer_guide/scheduling_and_execution.md index d1fa7c357f..91ccbcfc55 100644 --- a/docs/developer_guide/scheduling_and_execution.md +++ b/docs/developer_guide/scheduling_and_execution.md @@ -319,7 +319,7 @@ attempt 和新 `job_uuid`(与 4.1 本机调度器的 retry 语义相同,只 一个 Job 不会只持有部分锁;等待顺序由持久准入决定(5.0)。 **临时资源条件只排队、不失败**(V1 `resource_wait_policy`,`scheduler/resource_wait_policy.py`):解析动作参数与 -物理合同时(`Material.site` 声明的目标库位被占、搬运来源暂时不在库位、夹爪库位有物),或物料权威准备物理动作时 +物理合同时(`Material.site_picker` 关系的库位被占、搬运来源暂时不在库位、夹爪库位有物),或物料权威准备物理动作时 (`prepare_material_execution` 发现目标库位刚被占、另一作业的物理动作尚未结算),attempt 不记 `dispatch_not_sent`, 而是撤回已取得的 Claim、区间准入与内存锁,回到等待集合,下一次资源变化(任一作业释放资源、5 秒兜底重算)时 按首次排队先后重试;排队原因写在 attempt 的 `control_data.wait_reason`(`{code, message, waiting_since}`,作业 diff --git a/docs/developer_guide/v1_file_index/rest.md b/docs/developer_guide/v1_file_index/rest.md index 12ba74db97..884ddf3623 100644 --- a/docs/developer_guide/v1_file_index/rest.md +++ b/docs/developer_guide/v1_file_index/rest.md @@ -117,9 +117,9 @@ | unilabos/registry/action_resource_contract.py | 643 | PORTED | `registry/action_resource_contract.py` | 已在调度器托管下启用(A03) | | unilabos/registry/action_result_schema.py | 376 | PORTED | `registry/action_result_schema.py` | 逐字相同 | | unilabos/registry/action_template_projection.py | 492 | PORTED | `registry/action_template_projection.py` | 逐字相同;`node_templates.py` 调它的 `compile_action_template_handles` | -| unilabos/registry/annotation_rendering.py | 190 | PORTED | `registry/annotation_rendering.py` | 去掉 `SiteSelector(...)` 的回写(库位关系改为 `Material.site`),其余相同 | +| unilabos/registry/annotation_rendering.py | 190 | PORTED | `registry/annotation_rendering.py` | 去掉 `SiteSelector(...)` 的回写(库位关系改为 `Material.site_picker`),其余相同 | | unilabos/registry/annotation_schema.py | 760 | PORTED | `registry/annotation_schema.py` | 逐字相同 | -| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(material=Material.site(...))`,导入时报错并给出新写法),其余相同 | +| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(material=Material.site_picker(...))`,导入时报错并给出新写法),其余相同 | | unilabos/registry/ast_registry_scanner.py | 1311 | PORTED | `registry/ast_registry_scanner.py`(文件级缓存、`_collect_literal_constants`、`available_sites` 常量解析) | 跟随装饰器差异:不再提取 `metadata`、`displayname`、`ExecutorKind`、`exception_handling`、`action_name`(见 decorators);与 V1 一样对每个 JSON 动作做 AST 解析(统一 schema 草稿,不认识的注解退回签名推断) | | unilabos/registry/decorators.py | 882 | PARTIAL | `registry/decorators.py`(`device` / `action` / `resource` / `topic_config` / `always_free` / `not_action`) | V1 作者接口里有六个参数统一分支运行时装饰器不接受,驱动传了会在导入时 TypeError:`@action(action_name=…)`(对外动作名与方法名不同;AST 注册路径 `registry.py:1060` 却仍按它登记公开名、不记方法名,派发按公开名找方法,见 base_device_node 行)、`exception_handling=False`(异常不进人工决策)、`executor_kind`、`default_on_user_timeout`、`displayname`;`@device(metadata=…)`(供应商 / 规格等扩展元数据)。`legacy_action` / `contract=` 已删除(所有 JSON 动作同一标准,写了报错);资源语义用 `material=Material.xxx(...)`。`display_name` 只认新拼写是统一分支文档里的明确决定。统一分支另加了 `material`、`supported_backends`、`SiteSlot`;曾加的 `materials_need_lock` / `materials_free` 已按负责人 2026-11-17 决定移除(每个物料入参默认加共享资源锁),旧驱动传了照常加载、忽略并告警 | | unilabos/registry/in_memory_template_projection_store.py | 348 | DROPPED | 第 4 条 | V1 给不开 SQLite 的纯 Authoring Web 进程用的进程内模板代际存储。统一分支只把模板投影写进 runtime.db(`services/runtime/workflow/node_templates.py`) | @@ -131,7 +131,7 @@ | unilabos/registry/placeholder_type.py | 59 | PORTED | `registry/placeholder_type.py` | 统一分支另加 `SiteSlot` / `PLACEHOLDER_SITES`,`ResourceSlotRawInput` 也接受 str | | unilabos/registry/registry.py | 2783 | PORTED | `registry/registry.py:Registry` | 去掉了 `publish_package_snapshot` / `resolve_definition` / `package_snapshot`(第 1 条)和 `_apply_action_execution_metadata`(见 decorators)。旧锁字段处理与预计时长默认值由 `material_locks` 和 A01 的 `action_duration` 承担 | | unilabos/registry/runtime_device_catalog.py | 217 | PARTIAL | 设备身份:Registry Authority 条目(`services/runtime/registry.py`)+ `services/runtime/devices.py`(`/devices`,动作模板 UUID 用 `template_identity`) | V1 在内存里为包内每个设备建模板目录:用确定性的 `device_template_uuid`,并在 `GET /resource-templates`(`resource_type` 为空或 device)里列出。统一分支只在设备进图建实例时懒创建设备模板(`materials/core.py` 约 2302 行,`uuid4()` 随机 UUID),没进图的包设备不出现在 `/resource-templates`。影响:前端从模板列表放置设备,或跨实例 / Backend 按设备模板 UUID 对账时对不上 | -| unilabos/registry/site_selector_schema.py | 251 | PORTED | `registry/site_selector_schema.py`(+ `site_selector_value_schema.py`) | 只保留 owner / occupant 关系校验(供 `Material.site` 用);注解解析与回写随 `SiteSelector` 删除,生成的 `x-unilabos-site-selector` 扩展不变 | +| unilabos/registry/site_selector_schema.py | 251 | PORTED | `registry/site_selector_schema.py`(+ `site_selector_value_schema.py`) | 只保留 owner / occupant 关系校验(供 `Material.site_picker` 用);注解解析与回写随 `SiteSelector` 删除,生成的 `x-unilabos-site-selector` 扩展不变 | | unilabos/registry/template_delta.py | 431 | PORTED | `server/services/runtime/registry.py:RegistryService.report_entries`(条目级不可变版本;每批统计新增 / 更新 / 挂起 / 移除 / 复活 / 不变 / 自动接受;新增 / 变化 / 消失先挂起,单机部署或驱动包版本升高时自动接受;软移除可 restore)+ `node_templates.py`(不再生效的模板软删除) | 做法是 dev 的条目版本,不是 V1 的投影成员 manifest,行为等价;接受规则是 dev 自己的(V1 每个进程本地加载注册表,没有这一步) | | unilabos/registry/template_identity.py | 146 | PORTED | `registry/template_identity.py` | 逐字相同;`node_templates.py`、`devices.py` 在用 | | unilabos/registry/template_projection.py | 1215 | PORTED | `server/services/runtime/workflow/node_templates.py:NodeTemplateCatalog.sync_registry_templates` / `project_registry_templates` | 注册表动作投影进 runtime.db 的 `workflow_node_template` / `workflow_handle_template`(`authority_id=registry-template-projection`,V1 的确定性 UUID,指纹不变不重算)。结构节点模板(dev 的 condition / loop / group / material_io)总挂在 host_node 资源模板下投影,不依赖 host_node 条目是否已上报。资源模板「源码别名 → UUID」映射只服务 V1 的创作内核,随第 7 条一起去掉 | diff --git a/docs/developer_guide/v1_file_index/scheduler.md b/docs/developer_guide/v1_file_index/scheduler.md index 9c9c8ec976..699e910ca5 100644 --- a/docs/developer_guide/v1_file_index/scheduler.md +++ b/docs/developer_guide/v1_file_index/scheduler.md @@ -85,7 +85,7 @@ DROPPED 的依据分布:#4 / D05(可替换引擎宿主、插件传输与协 | `unilabos/app/scheduler/inventory/schemas.py` | 804 | PORTED | 命令载荷校验在 `inventory_commands.py` 各处理器 + `unilabos/protocol/materials.py`(`InventoryMutation`、`InventoryLotRead`、`InventoryStocktake` 等);读 DTO 见 `server/api/materials/inventory.py` | 差异:V1 命令边界是 `extra="forbid"` + strict int/float,统一分支在处理器内宽松取值,未知字段不报错;`inventory.reconcile_count` 的 `mount_uuid` / `evidence_job_uuid`(可信计数测量证据)被忽略,按人工盘点 `stocktake_inventory_lot` 执行——对应 I03 开放项(按测量作业证据自动盘点未实现)。云端响应 / 回调 DTO(`CloudResponse`、`CloudInventoryCommandResult*`)不需要,V1 产品没接云 | | `unilabos/app/scheduler/inventory/service.py` | 2825 | PORTED | `server/services/materials/core.py:MaterialsService`(`put_template/delete_template`、`inbound_inventory_lot`、`reserve_inventory` / `reserve_task_inventory`、`consume/release/quarantine_inventory_reservation`、`correct_inventory_lot`、`move_material`)+ `services/materials/inventory_commands.py`(V1 全部命令类型:`inventory.inbound` kind=instance、`material.deploy/move/detach/set_parent/consume/mark_used/discard/adjust`、`material.content.set/clear`);工站异常人工修正 `services/runtime/station_handling.py` | 对账表 I01 / I02;`api_v1_route_map.md` p7-c / p7-d。`admit_material_sources` / `resolve_shared_workflow_materials`(物料来源准入、共享来源)属 #6,dev 仅保留 `source.bind/release` 命令(`contents.py:bind_material_source`),调度器不调用;`describe_wait_resources` → 任务 `wait_reason` / `resource_waiters.py` | | `unilabos/app/scheduler/inventory/settled_quantity.py` | 78 | PARTIAL | 分装结算 `materials/execution.py:MaterialExecutions._aliquot`;分装消耗读模型 `materials/consumption.py:_aliquot_facts`(`/inventory-consumptions` 列出已结算分装,`tests/server/test_inventory_seam_v1.py::test_settled_aliquot_is_a_consumption_of_the_source_contents`);批次实际量结算与人工核对去重 `execution.py:apply_actual_lot_quantity`(effect `physical.inventory:`) | V1 用已提交的分装来源台账作为该作业 `current_substance` 预留的实际扣量,防止通用消费再扣一次。统一分支内容物预留在动作开始按计划量扣(`core.py` 预留 consume → `contents.finish_content_reservation`),分装回执又按实际量扣来源(`_aliquot`),两处之间没找到去重(grep `aliquot` 于 contents / core / scheduler / server/inventory 无交叉)。影响:同一节点既声明分装来源的 content 需求又是 aliquot 动作时会重复扣量;不声明则分装来源不受多任务数量预留保护(需实测确认) | -| `unilabos/app/scheduler/inventory/site_selection.py` | 237 | PARTIAL | 精确库位引用:`runtime/workflow/site_bindings.py:SiteBindingIndex.resolve` / `resolve_workflow_sites`(图保存 `site_binding_mode=resolve` 时按 owner 范围把 label 冻结为 site_uuid,UUID 失效不按标签回退);派发时 `physical_contract.py:site()`(uuid / label / index 唯一可见)、`run_preflight.py:validate_resource_values`(`Material.site` 库位关系的归属 / 占用) | 缺命名库位组:V1 `site_group("组键", exact=...)` 读 Site `meta_data.unilab.site_groups`,任务创建时冻结有序候选 + 部署指纹(`sha256`),所属物料未定时记 `deferred_site_group` 到派发再解析,并按 `sort_order` 取第一个可放的空位;统一分支 grep `site_groups/group_key/target_site_group/deferred_site` 均无,编译器也无 `site_group()`。影响:V1 依赖“放到这组孔里任一空位”的转运工作流无法表达,只能写死具体库位 | +| `unilabos/app/scheduler/inventory/site_selection.py` | 237 | PARTIAL | 精确库位引用:`runtime/workflow/site_bindings.py:SiteBindingIndex.resolve` / `resolve_workflow_sites`(图保存 `site_binding_mode=resolve` 时按 owner 范围把 label 冻结为 site_uuid,UUID 失效不按标签回退);派发时 `physical_contract.py:site()`(uuid / label / index 唯一可见)、`run_preflight.py:validate_resource_values`(`Material.site_picker` 库位关系的归属 / 占用) | 缺命名库位组:V1 `site_group("组键", exact=...)` 读 Site `meta_data.unilab.site_groups`,任务创建时冻结有序候选 + 部署指纹(`sha256`),所属物料未定时记 `deferred_site_group` 到派发再解析,并按 `sort_order` 取第一个可放的空位;统一分支 grep `site_groups/group_key/target_site_group/deferred_site` 均无,编译器也无 `site_group()`。影响:V1 依赖“放到这组孔里任一空位”的转运工作流无法表达,只能写死具体库位 | | `unilabos/app/scheduler/inventory/source_selection.py` | 122 | DROPPED | 已定 #6 / 对账表 I02(material_source 物料来源准入不做);统一分支的近似是 `InventoryRequirement` kind=`material` 按 `template_uuid` + `parent_material_uuid`(仅直接父)或 `site_uuid` 选料(`materials/core.py:_select_inventory_material`) | `search_descendants`(沿各层 Site 实际占位遍历挂载物料子树选料)没有对应;`claimed_by_other_task`(被他任务占用 → 等待而非缺料)在统一分支变成缺料失败,见 domain.py 行 | | `unilabos/app/scheduler/inventory/station_resource.py` | 1241 | PARTIAL | 转运 / 原位 / 分装资源事实与结算:`scheduler/physical_contract.py:resolve_physical_contract`、`tenancy_contract.py`、`materials/execution.py:prepare/settle`、`physical_recovery.py`;异常处置库存:`services/runtime/station_handling.py`(inventory、inventory-corrections)、`api/runtime/stations.py`(resource-usage);Permit 系列见 dispatch_admission 行;`is_device_material` → `resource_type == "device"` | 缺 `resolve_named_site_group` 与 `resolve_target_site` 的“候选组 + 当前不可用集合 → 选一个能接收该模板物料的空位”(`allowed_resource_template_uuids` 也参与);统一分支目标库位必须由参数唯一给定。与 site_selection.py 同一缺口 | | `unilabos/app/scheduler/inventory/stocktake.py` | 68 | PARTIAL | `materials/core.py:stocktake_inventory_lot`(人工计数盘点:操作人、理由、期望版本,预留 / 隔离 / 已登记实物差异拒绝);`inventory.reconcile_count` 命令映射到它(`inventory_commands.py:_reconcile_count`) | 对账表 I03“部分”属实。缺测量证据盘点:V1 `reconcile_count` 要求 `evidence_job_uuid`(成功的测量作业)与 `mount_uuid`(批次必须归属被测容器)、容器正被物理动作占用时拒绝,并由工作流原生命令 `read_count` → 测量 → `reconcile_count` 冻结测量前版本;统一分支命令丢弃这些字段,按人工盘点处理。影响:设备计数测量后无法自动修正库存 | diff --git a/tests/server/test_site_selection_by_owner.py b/tests/server/test_site_selection_by_owner.py index 9eeb7a1686..f7c3ad6b25 100644 --- a/tests/server/test_site_selection_by_owner.py +++ b/tests/server/test_site_selection_by_owner.py @@ -1,6 +1,6 @@ """库位参数按所属物料选择:``{"owner_uuid": ...}`` 在任务准入时选定、经入口预留占住并冻结进任务。 -候选是所属物料下接受放入物料(``Material.site`` 的 occupant)的库位(模板白名单 / 允许的资源类别),按库位序号选第一个 +候选是所属物料下接受放入物料(``Material.site_picker`` 的 for_material)的库位(模板白名单 / 允许的资源类别),按库位序号选第一个 空着且没被预留的;没有接受的库位是预检错误(``reason=no_acceptable_site``),接受的都被占着时任务排队 (``wait_reason.code=site_group_unavailable``)。精确库位 uuid 照旧。 """ From 9080f5fd861acc081d862358985be91ae958a3de Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:56:55 +0800 Subject: [PATCH 14/27] feat(scheduler): settle declared moves from the frozen plan without driver receipts A succeeded action whose Material.move / pick / place was frozen before dispatch now settles at the frozen source and target when the driver result carries no material_transfer_receipts; receipts that are given must still match the frozen plan exactly. Manual settlement after a terminal task and dispense (actual amounts) still require receipts. --- docs/developer_guide/action_standard.md | 6 +++-- tests/server/test_material_actions.py | 24 +++++++++++++++++++ .../server/scheduler/physical_recovery.py | 22 +++++++++++++---- 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 2816137457..034789981a 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -163,8 +163,10 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl 规则: -- 用 `Material.move` / `pick` / `place` 声明了的搬运,物料位置由核心按搬运回执结算;驱动**不能**再对同一件物料调用 - `materials.transfer` / `materials.assign`(会重复写位置,与核心的结算冲突)。驱动只负责物理动作并按需返回回执。 +- 用 `Material.move` / `pick` / `place` 声明了的搬运,物料位置由核心结算;驱动**不能**再对同一件物料调用 + `materials.transfer` / `materials.assign`(会重复写位置,与核心的结算冲突)。驱动只负责物理动作:动作成功而结果里 + 没有 `material_transfer_receipts` 时,核心按派发前冻结的来源 / 目标结算;驱动给了搬运回执,就必须与冻结计划完全一致 + (否则结算被拒绝,转人工核实)。人工补记结算(任务终止后)仍要逐条给出实际位置。 - `dispense` 声明了的内容物转移由核心按 `AliquotReceipt` 结算;驱动不再对同一来源 / 目标手动写内容物。 - `materials.*` 只用于**没有声明**的运行时变化:新建物料(`create`)、写内容物(`apply_substances`,用于没有 `dispense` 的动作)、 删除(`remove`)、启动时对齐(`ensure`)、查询(`get` / `search` / `resolve` / `snapshot`)等。 diff --git a/tests/server/test_material_actions.py b/tests/server/test_material_actions.py index dcad982be9..a4a617518d 100644 --- a/tests/server/test_material_actions.py +++ b/tests/server/test_material_actions.py @@ -327,3 +327,27 @@ def schema(picker, fields): with pytest.raises((ValueError, ResourceUnavailableError)): validate_resource_values(of_device, {**values, "target_device": "nowhere", "site": _site(service, other, "T1").site_uuid}, gateway, device_id="reader") + + +def test_a_declared_move_settles_from_the_frozen_plan_without_a_driver_receipt() -> None: + """动作成功:没回报搬运回执时按冻结计划结算;回报了就必须一致。人工补记与分装照旧要求回执。""" + + from unilabos.server.scheduler.physical_recovery import PhysicalRecovery + + move = {"material_uuid": "m", "source_owner_uuid": "a", "source_site_uuid": "a1", + "target_owner_uuid": "b", "target_site_uuid": "b1"} + record = {"job_uuid": "job", "claim_uuid": "claim", "plan_hash": "sha256:x", "request": {"moves": [move]}} + + for result in (None, {}, {"success": True}): + receipt = PhysicalRecovery._receipt(record, result, planned_moves=True) + assert [item.model_dump() for item in receipt.material_transfer_receipts] == [move] + other = {"material_uuid": "m", "target_owner_uuid": "c", "target_site_uuid": "c1"} + receipt = PhysicalRecovery._receipt(record, {"material_transfer_receipts": [other]}, planned_moves=True) + assert receipt.material_transfer_receipts[0].target_site_uuid == "c1" # 不一致由物料权威结算时拒绝 + assert PhysicalRecovery._receipt(record, {}).material_transfer_receipts == [] + with pytest.raises(ValueError, match="具名回执"): + PhysicalRecovery._receipt(record, "done") + assert PhysicalRecovery._receipt(record, "done", planned_moves=True).material_transfer_receipts[0].target_site_uuid == "b1" + aliquot = {**record, "request": {"moves": [], "aliquot": {"source_material_uuid": "s", "target_material_uuids": ["t"]}}} + with pytest.raises(ValueError, match="具名回执"): + PhysicalRecovery._receipt(aliquot, "done", planned_moves=True) diff --git a/unilabos/server/scheduler/physical_recovery.py b/unilabos/server/scheduler/physical_recovery.py index dccbc229bd..73aaae4a7c 100644 --- a/unilabos/server/scheduler/physical_recovery.py +++ b/unilabos/server/scheduler/physical_recovery.py @@ -102,7 +102,7 @@ def settle(self, job_uuid, *, job_status, return_info, error_info, resolution): } self._save(job_uuid, outcome) try: - receipt = self._receipt(record, return_info.get("return_value")) + receipt = self._receipt(record, return_info.get("return_value"), planned_moves=True) self.gateway.settle_material_execution(receipt) outcome["settled"] = True self._save(job_uuid, outcome) @@ -112,15 +112,27 @@ def settle(self, job_uuid, *, job_status, return_info, error_info, resolution): raise PhysicalSettlementPending(f"设备结果已保存,物理结算待核实:{error}") from error @staticmethod - def _receipt(record, value): - physical = bool(record["request"].get("moves") or record["request"].get("aliquot")) + def _receipt(record, value, *, planned_moves=False): + """设备结果 → 结算回执。 + + ``planned_moves``:动作成功时,声明的搬运(``Material.move`` / ``pick`` / ``place``)由核心按冻结计划结算—— + 结果里没有 ``material_transfer_receipts`` 就用冻结的搬运;给了就必须与冻结计划完全一致。人工补记结算不按计划补。 + 分装(``Material.dispense``)的实际量只能由驱动回报,始终要求 ``material_aliquot_receipts``。 + """ + + request = record["request"] value = value or {} if not isinstance(value, dict): - if physical: + if request.get("aliquot") or (request.get("moves") and not planned_moves): raise ValueError("物理动作结果必须包含具名回执") value = {} + if planned_moves and "material_transfer_receipts" not in value: + value = {**value, "material_transfer_receipts": [ + {key: item[key] for key in ("material_uuid", "target_owner_uuid", "target_site_uuid")} + for item in request.get("moves", []) + ]} moves = [] - expected = {item["material_uuid"]: item for item in record["request"].get("moves", [])} + expected = {item["material_uuid"]: item for item in request.get("moves", [])} for item in value.get("material_transfer_receipts", []): if not isinstance(item, dict): raise ValueError("搬运回执必须是对象") From d4065ac2ad70ffa03254d4859b683e38b8e30cd2 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:39:40 +0800 Subject: [PATCH 15/27] feat(scheduler): resolve a SiteSlot label under its site_picker owner Site uuids are issued by the materials authority when a tree is created, so a workflow cannot hard-code the uuid of a station position. A SiteSlot parameter with a Material.site_picker(of=...) relation may now carry a Site label (or index) of that owner: run preflight and dispatch match it uniquely under the owner (a ResourceSlot, a DeviceSlot root or the executing device root) and use the resolved Site for the ownership / occupancy check, the site lock and the Material.move / place target and from_site. A label without a site_picker relation still fails before dispatch and takes no site lock. --- docs/developer_guide/action_standard.md | 7 ++- tests/server/test_material_actions.py | 30 +++++++++++ .../server/scheduler/physical_contract.py | 54 +++++++++++++++++-- unilabos/server/scheduler/tenancy_contract.py | 27 +++++++--- .../runtime/workflow/run_preflight.py | 7 ++- 5 files changed, 111 insertions(+), 14 deletions(-) diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 034789981a..af74e66613 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -196,7 +196,7 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl | --- | --- | | `ResourceSlot` / `list[ResourceSlot]`(以及选择器为 `unilabos_resources` 的参数) | 物料锁(现状) | | `DeviceSlot` / `list[DeviceSlot]` | 设备锁:值是设备 id,派发前核对它是已登记的设备,与该设备上正在执行的动作互斥 | -| `SiteSlot` | 库位锁:值是库位 uuid,按「所属物料 + 库位」加锁;值不是已登记的库位 uuid(例如库位名)时不加锁 | +| `SiteSlot` | 库位锁:值是库位 uuid,按「所属物料 + 库位」加锁;值是 `Material.site_picker` 所属方下的库位名时按解析出的库位加锁;两者都解析不出时不加锁 | 空值(`None` / `""` / `[]`)不加锁。`always_free` 只免除执行设备自身的动作锁,按类型加的设备锁 / 库位锁照旧。 @@ -225,6 +225,11 @@ def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = No "show_occupied": ..., "allow_occupied": ...}`;`of` 省略时 `owner` 为 `null`(执行设备根节点),`of` 是 `DeviceSlot` 参数时它的值是设备 id。 - 只写 `SiteSlot`、不写 `Material.site_picker` 的参数照旧是库位选择器,只是没有这层关系的核对。 +- **工作流里写死的工位**:库位 uuid 由物料权威在建树时发号,同一个设备图在不同部署里的库位 uuid 不同,工作流源码 + 不能写死库位 uuid。带 `Material.site_picker(of=...)` 关系的库位参数可以改给所属方下的**库位名**(或序号),例如 + `{"target_owner": {"uuid": <载架 uuid>}, "target_site": "position_x15_y01"}`:运行预检与派发前在 `of` 所属方下唯一 + 匹配,解析出的库位用于归属 / 占用核对、库位锁和 `Material.move` / `place` 的目标(`from_site` 同样)。所属方下匹配不到 + 或不唯一时报错;没有 `site_picker` 关系的库位名无从解析,派发前报错。 #### 按所属物料选库位:`{"owner_uuid": ...}` diff --git a/tests/server/test_material_actions.py b/tests/server/test_material_actions.py index a4a617518d..52f42ab2e4 100644 --- a/tests/server/test_material_actions.py +++ b/tests/server/test_material_actions.py @@ -351,3 +351,33 @@ def test_a_declared_move_settles_from_the_frozen_plan_without_a_driver_receipt() aliquot = {**record, "request": {"moves": [], "aliquot": {"source_material_uuid": "s", "target_material_uuids": ["t"]}}} with pytest.raises(ValueError, match="具名回执"): PhysicalRecovery._receipt(aliquot, "done", planned_moves=True) + + +def test_a_site_label_resolves_under_the_site_picker_owner(authority) -> None: + """库位 uuid 由物料权威发号,工作流只能写死库位名:带 site_picker(of=...) 关系时在所属方下解析、加锁、搬运。""" + + from unilabos.registry.material_roles import material_site_selectors + from unilabos.server.services.runtime.workflow.run_preflight import validate_resource_values + + service, gateway = authority + source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") + _device(service, "arm", [("grip", {"role": "gripper"})]) + sample = source["A01"].resource.unilabos_uuid + declared = [Material.move("plate", to_site="target_site"), + Material.site_picker("target_site", of="target", for_material="plate")] + site_field = {**_SITE, "x-unilabos-site-selector": material_site_selectors(declared)["target_site"]} + schema = _schema(declared, {"plate": _MATERIAL, "target": _MATERIAL, "target_site": site_field}) + values = {"plate": {"uuid": sample}, "target": {"uuid": target.unilabos_uuid}, "target_site": "A03"} + target_site = _site(service, target.unilabos_uuid, "A03").site_uuid + + validate_resource_values(schema, values, gateway, device_id="arm") + plan = resolve_physical_contract(schema, values, "arm", gateway) + assert (plan["moves"][0].target_owner_uuid, plan["moves"][0].target_site_uuid) == (target.unilabos_uuid, target_site) + (claim,) = resolve_tenancy_contract(schema, values, "arm", gateway)["site_claims"] + assert (claim.owner_material_uuid, claim.site_uuid) == (target.unilabos_uuid, target_site) + # 没有 site_picker 关系的库位名无从解析:派发前报错,也不加库位锁 + bare = _schema(Material.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + with pytest.raises(ValueError, match="site_picker"): + resolve_physical_contract(bare, {"plate": {"uuid": sample}, "target_site": "A03"}, "arm", gateway) + assert "site_claims" not in resolve_tenancy_contract(bare, {"plate": {"uuid": sample}, "target_site": "A03"}, + "arm", gateway) diff --git a/unilabos/server/scheduler/physical_contract.py b/unilabos/server/scheduler/physical_contract.py index 79d37c430c..24123cb9a0 100644 --- a/unilabos/server/scheduler/physical_contract.py +++ b/unilabos/server/scheduler/physical_contract.py @@ -1,8 +1,9 @@ """将动作资源合同解析为权威物料、完整库位和托管范围。 ``Material.move`` / ``pick`` / ``place`` 规范化成 ``transfer`` / ``transfer_step``:目标与来源按库位 uuid 给出时, -所属方(载架或设备根节点)由库位决定;搬运设备参数(``DeviceSlot``,设备 id)解析成该设备的物料,省略时是 -执行设备。旧合同里显式的所属物料参数(ResourceSlot)照旧可用。 +所属方(载架或设备根节点)由库位决定;库位参数带 ``Material.site_picker(of=...)`` 关系时,值也可以是所属方下的 +库位名(工作流里写死的工位;库位 uuid 由物料权威建树时发号,不能写死)。搬运设备参数(``DeviceSlot``,设备 id) +解析成该设备的物料,省略时是执行设备。旧合同里显式的所属物料参数(ResourceSlot)照旧可用。 """ from __future__ import annotations @@ -41,6 +42,46 @@ def device_material_uuid(materials: Any, device_id: str) -> str: return aggregate.material.material_uuid +def site_picker_owner( + schema: Mapping[str, Any] | None, values: Mapping[str, Any], name: str, materials: Any, device_id: str | None, +) -> str | None: + """库位参数 ``name`` 的 ``Material.site_picker`` 所属方 → 所属物料 uuid;没有这层关系或所属方未给时为 ``None``。 + + ``of`` 是 ``ResourceSlot`` 时取它的物料 uuid,是 ``DeviceSlot`` 时取设备根节点,省略时是执行设备根节点。 + """ + + fields = (((schema or {}).get("properties") or {}).get("goal") or {}).get("properties") or {} + selector = (fields.get(name) or {}).get("x-unilabos-site-selector") + if not isinstance(selector, Mapping): + return None + of = selector.get("owner") + value = values.get(of) if of else device_id + if isinstance(value, str) and value.strip(): + return device_material_uuid(materials, value) + if isinstance(value, Mapping) and isinstance(value.get("uuid"), str) and value["uuid"].strip(): + return value["uuid"] + return None + + +def site_by_label( + schema: Mapping[str, Any] | None, values: Mapping[str, Any], name: str, materials: Any, device_id: str | None, +) -> tuple[str, str] | None: + """库位参数的值不是已登记的库位 uuid 时(工作流里写死的库位名或序号):在 ``Material.site_picker`` 的所属方下 + 唯一匹配,返回 ``(所属物料 uuid, 库位 uuid)``;没有 site_picker 关系或匹配不唯一时为 ``None``。""" + + selected = values.get(name) + if not isinstance(selected, str) or not selected.strip(): + return None + owner = site_picker_owner(schema, values, name, materials, device_id) + if not owner: + return None + matches = [ + item for item in materials.get_material(owner).sites + if selected in (item.site_uuid, item.label, str(item.site_index)) + ] + return (owner, matches[0].site_uuid) if len(matches) == 1 else None + + def resolve_physical_contract( schema: Mapping[str, Any] | None, values: dict[str, Any], device_id: str, materials: Any ) -> dict[str, Any]: @@ -100,14 +141,19 @@ def site(owner, selected): return matches[0] def site_by_uuid(name): - """库位参数(``SiteSlot``,库位 uuid)→ ``(所属物料, 库位)``;所属方由库位决定。""" + """库位参数(``SiteSlot``)→ ``(所属物料, 库位)``:库位 uuid 的所属方由库位决定; + 带 ``Material.site_picker`` 关系时也可以是所属方下的库位名。""" selected = values.get(name) if not isinstance(selected, str) or not selected.strip(): raise ValueError(f"库位参数 {name} 必须给出库位 uuid") owner = site_owner_material_uuid(materials, selected) if owner is None: - raise ValueError(f"库位参数 {name} 指向不存在的库位 {selected}") + found = site_by_label(schema, values, name, materials, device_id) + if found is None: + raise ValueError(f"库位参数 {name} 指向不存在的库位 {selected}" + "(不是库位 uuid,也不是 Material.site_picker 所属方下唯一的库位名)") + owner, selected = found return owner, site(owner, selected) def location(identity): diff --git a/unilabos/server/scheduler/tenancy_contract.py b/unilabos/server/scheduler/tenancy_contract.py index 48d7f7645b..0723e60e8b 100644 --- a/unilabos/server/scheduler/tenancy_contract.py +++ b/unilabos/server/scheduler/tenancy_contract.py @@ -3,8 +3,8 @@ - 设备托管(``Material.load`` / ``unload``,实验性):设备参数是 ``DeviceSlot``,省略时(合同里的 ``EXECUTING_DEVICE`` 记号)是执行设备; - 按类型加锁:``DeviceSlot`` / ``list[DeviceSlot]`` 参数加设备锁(``device_claims``),``SiteSlot`` 参数加库位锁 - (``site_claims``,按「所属物料 + 库位」);字段由注册表标出 ``x-unilabos-slot``。空值不加锁,库位参数的值不是 - 已登记的库位 uuid(例如库位名)时不加库位锁。 + (``site_claims``,按「所属物料 + 库位」);字段由注册表标出 ``x-unilabos-slot``。空值不加锁;库位参数的值是 + ``Material.site_picker`` 所属方下的库位名时按解析出的库位加锁,解析不出时不加库位锁。 """ from unilabos.registry.action_resource_contract import EXECUTING_DEVICE from unilabos.server.scheduler.models import DeviceTenancyTransition, DeviceTenancyRequirement, SiteLockClaim @@ -27,20 +27,31 @@ def _slot_values(value) -> list[str]: return [] -def resolve_site_claims(schema: dict | None, values: dict, materials) -> list[SiteLockClaim]: - """``SiteSlot`` 参数 → 库位锁(所属物料 + 库位);值不是已登记的库位 uuid 时不加锁。""" +def resolve_site_claims(schema: dict | None, values: dict, materials, device_id: str | None = None) -> list[SiteLockClaim]: + """``SiteSlot`` 参数 → 库位锁(所属物料 + 库位)。 + + 值是库位 uuid 时所属方由库位决定;是 ``Material.site_picker`` 所属方下的库位名时按解析出的库位加锁; + 两者都解析不出时不加锁(派发前的物料 / 物理合同会报错)。 + """ names = slot_parameters(schema, "site") if not names or materials is None: return [] - from .physical_contract import site_owner_material_uuid + from .physical_contract import site_by_label, site_owner_material_uuid claims: dict[tuple[str, str], SiteLockClaim] = {} for name in names: for site_uuid in _slot_values(values.get(name)): owner = site_owner_material_uuid(materials, site_uuid) - if owner: - claims[(owner, site_uuid)] = SiteLockClaim(owner_material_uuid=owner, site_uuid=site_uuid) + if owner is None: + try: + found = site_by_label(schema, values, name, materials, device_id) + except (ValueError, RuntimeError, OSError): + found = None + if found is None: + continue + owner, site_uuid = found + claims[(owner, site_uuid)] = SiteLockClaim(owner_material_uuid=owner, site_uuid=site_uuid) return [claims[key] for key in sorted(claims)] @@ -54,7 +65,7 @@ def resolve_tenancy_contract(schema: dict | None, values: dict, device_id: str, devices.update(transition[name] for name in ("acquire_device_param","release_device_param") if transition.get(name)) # 按类型加锁:DeviceSlot 参数(含列表)一律加设备锁,空值不加 typed_devices = [name for name in slot_parameters(schema, "device") if _slot_values(values.get(name))] - site_claims = resolve_site_claims(schema, values, materials) + site_claims = resolve_site_claims(schema, values, materials, device_id) if not (transition or in_place or devices or typed_devices or site_claims): return {} diff --git a/unilabos/server/services/runtime/workflow/run_preflight.py b/unilabos/server/services/runtime/workflow/run_preflight.py index a7909327ef..3f2a239ea9 100644 --- a/unilabos/server/services/runtime/workflow/run_preflight.py +++ b/unilabos/server/services/runtime/workflow/run_preflight.py @@ -386,7 +386,12 @@ def device_aggregate(name: str, value: str) -> Any: continue occupant = values.get(selector.get("occupant"), {}) or {} aggregate = material(owner, name) - site = next((site for site in aggregate.sites if site.site_uuid == values[name]), None) + # 库位 uuid;或所属方下唯一的库位名 / 序号(工作流里写死的工位,派发前解析成库位 uuid) + matches = [site for site in aggregate.sites if site.site_uuid == values[name]] or [ + site for site in aggregate.sites + if isinstance(values[name], str) + and values[name] in (getattr(site, "label", None), str(getattr(site, "site_index", None)))] + site = matches[0] if len(matches) == 1 else None if site is None: raise ValueError(f"库位参数 {name} 不属于所选容器或已失效") if not selector["allow_occupied"] and site.occupied_material_uuid not in {None, occupant.get("uuid")}: From d732992e1d51e99baca62797a99e5aab2dafc5c5 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:45:13 +0800 Subject: [PATCH 16/27] feat(registry): let a site_picker SiteSlot carry a Site label A SiteSlot parameter with a Material.site_picker relation no longer gets format: uuid in its goal schema, so a workflow can pass the Site label of the picker's owner (resolved before dispatch); a Site uuid and the {"owner_uuid": ...} selection keep working. The x-unilabos-site-selector extension is unchanged; the AST cache version is bumped. --- docs/developer_guide/action_standard.md | 4 ++-- tests/registry/test_backend_metadata.py | 2 +- tests/registry/test_site_selector_contract.py | 4 ++-- unilabos/registry/action_schema.py | 2 +- unilabos/registry/ast_registry_scanner.py | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index af74e66613..4fce40153d 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -17,7 +17,7 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) | `Annotated[X, Field(ge=, le=, min_length=, max_length=, title=, description=)]` | 带范围与说明 | 严格 | | `ResourceSlot` / `list[ResourceSlot]` | 物料引用 `{"uuid": ...}`(或按库位绑定的 `{"site_uuid": ...}`,准入时解析),加物料锁 | 严格;Host 解析成物料实例 | | `DeviceSlot` / `SiteSlot` | 设备 ID / 库位 UUID 字符串(字段带 `x-unilabos-slot: "device"` / `"site"`),加设备锁 / 库位锁 | 严格 | -| `SiteSlot` 且写了 `material=Material.site_picker("site", of=...)` | 库位 UUID(或按所属物料选择的 `{"owner_uuid": ...}`,准入时选定),带库位关系(`x-unilabos-site-selector`) | 严格;预检与派发前核对库位归属与占用 | +| `SiteSlot` 且写了 `material=Material.site_picker("site", of=...)` | 库位 UUID、所属方下的库位名(工作流里写死的工位,派发前解析成库位 uuid),或按所属物料选择的 `{"owner_uuid": ...}`(准入时选定);带库位关系(`x-unilabos-site-selector`),不限定 uuid 格式 | 严格;预检与派发前核对库位归属与占用 | | `dict`、`Dict[str, Any]`、`Mapping` | 任意 JSON 对象 | 只校验是对象 | | 没写注解、`Any`、`object` | 任意 JSON 值(`{}`) | 不限值 | | 严格解析器不认识的注解(`Union[int, str]`、`List[Optional[float]]`、枚举、PLR / pydantic 类型……) | 退回注册表原来的签名类型推断 | 按推断结果;推断不出的部分接受任意值 | @@ -106,7 +106,7 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 | 角色 | 参数类型 | 值 | | --- | --- | --- | | 物料(`material`、`from_material`、`to_materials`、`for_material`) | `ResourceSlot`(`to_materials` 可以是多个参数) | 物料引用;`ResourceSlot` 不能指向设备 | -| 库位(`to_site`、`from_site`、`site_picker` 的库位参数) | `SiteSlot` | 库位 uuid | +| 库位(`to_site`、`from_site`、`site_picker` 的库位参数) | `SiteSlot` | 库位 uuid(带 `site_picker(of=...)` 关系时也可以是所属方下的库位名) | | 设备(`carrier_device`、`device`、`from_device`) | `DeviceSlot` | 设备 id;省略就是**执行设备** | ```python diff --git a/tests/registry/test_backend_metadata.py b/tests/registry/test_backend_metadata.py index 996b11f2bc..d6e43202bd 100644 --- a/tests/registry/test_backend_metadata.py +++ b/tests/registry/test_backend_metadata.py @@ -267,7 +267,7 @@ def test_ast_cache_rejects_previous_metadata_version(tmp_path) -> None: cache = load_scan_cache(cache_path) - assert _CACHE_VERSION == 27 + assert _CACHE_VERSION == 28 assert cache == {"version": _CACHE_VERSION, "files": {}} diff --git a/tests/registry/test_site_selector_contract.py b/tests/registry/test_site_selector_contract.py index 3ba4ed100c..e7b566abf8 100644 --- a/tests/registry/test_site_selector_contract.py +++ b/tests/registry/test_site_selector_contract.py @@ -24,11 +24,11 @@ from unilabos.registry.material_roles import MaterialRoleError, material_contract, material_site_selectors from unilabos.registry.registry import Registry -#: 原 ``Annotated[str | None, SiteSelector(owner="warehouse", occupant="resource")] = None`` 生成的字段扩展。 +#: 原 ``Annotated[str | None, SiteSelector(owner="warehouse", occupant="resource")] = None`` 生成的字段扩展 +#: (不再限定 uuid 格式:值也可以是所属方下的库位名)。 _SITE_SELECTOR_FIELD = { "type": ["string", "null"], "default": None, - "format": "uuid", "x-unilabos-editor-control": "site_selector", "x-unilabos-site-selector": { "version": 1, diff --git a/unilabos/registry/action_schema.py b/unilabos/registry/action_schema.py index feaca56ccf..ab4cf574bd 100644 --- a/unilabos/registry/action_schema.py +++ b/unilabos/registry/action_schema.py @@ -595,7 +595,7 @@ def build_action_schema_draft( except SiteSelectorSchemaError as error: raise ActionSchemaError(f"动作 {definition} 参数 {name}:{error.message}") from None field = goal[name] - field["format"] = "uuid" + # 不限定 uuid 格式:值是库位 uuid,或所属方下的库位名(工作流里写死的工位,派发前在所属方下解析) field["x-unilabos-editor-control"] = "site_selector" field["x-unilabos-site-selector"] = dict(extension) diff --git a/unilabos/registry/ast_registry_scanner.py b/unilabos/registry/ast_registry_scanner.py index 92b715f7a1..3392bba8d0 100644 --- a/unilabos/registry/ast_registry_scanner.py +++ b/unilabos/registry/ast_registry_scanner.py @@ -62,7 +62,7 @@ MAX_SCAN_DEPTH = 10 # 最大目录递归深度 MAX_SCAN_FILES = 1000 # 最大扫描文件数量 -_CACHE_VERSION = 27 # 27:Material 重做(move / pick / place / dispense),DeviceSlot / SiteSlot 字段带 x-unilabos-slot +_CACHE_VERSION = 28 # 28:Material.site_picker 的库位参数不再限定 uuid 格式(也可以给所属方下的库位名) # 允许点号分段(如 liquid_handler.prcxi),与内置 YAML 注册表的命名先例一致; # 点号只用于注册表模板名,设备实例 id(图节点)另有约束。 _DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$") From 3e680d24b82ba956b017e03e180bc4ab382b053e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:57:24 +0800 Subject: [PATCH 17/27] docs(action-standard): list the gripper role, receipt and site label changes --- docs/developer_guide/action_standard.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 4fce40153d..9ea5e997f6 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -325,7 +325,9 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | `Material.load("sample", device="vessel")`(`vessel` 是 `str` / `ResourceSlot`) | `vessel` 注解为 `DeviceSlot`;装进执行设备本身时省略 `device=` | 行为上的变化:`DeviceSlot` / `SiteSlot` 参数现在默认加设备锁 / 库位锁;`load` / `unload` / `in_place` / `site_picker` / -`order_sensitive` 注册时告警一次「实验性功能」。 +`order_sensitive` 注册时告警一次「实验性功能」;搬运设备的夹爪库位角色统一为 `gripper`,已部署的物料权威里旧角色名 +(如 `robot.gripper`)不会随设备声明自动更新,需要重建或改写这些库位的 `meta_data.role`;声明的搬运在动作成功后可以不交 +搬运回执(核心按冻结计划结算);`site_picker` 的库位参数不再限定 uuid 格式(也可以给所属方下的库位名)。 行为上的变化: From 5888d56578800e911f3b1e77546240495cd5a8dc Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:05:29 +0800 Subject: [PATCH 18/27] feat(registry)!: rename @action(material=) to materials= and mark it experimental materials= takes the same value as before (one Material.xxx(...) call or a list). The whole field is experimental: any use warns once per definition, listing the declarations used, including move / pick / place / dispense. The old material= fails in the decorator and in the AST scan with a hint to materials=. AST scan cache version 29. --- .../registry/test_action_resource_contract.py | 64 +++++++++++--- tests/registry/test_site_selector_contract.py | 8 +- unilabos/registry/action_options.py | 17 ++-- unilabos/registry/action_schema.py | 2 +- unilabos/registry/ast_registry_scanner.py | 12 +-- unilabos/registry/decorators.py | 37 +++++---- unilabos/registry/material_roles.py | 83 +++++++++---------- unilabos/registry/site_selector_schema.py | 2 +- 8 files changed, 133 insertions(+), 92 deletions(-) diff --git a/tests/registry/test_action_resource_contract.py b/tests/registry/test_action_resource_contract.py index 505c44df50..966ad1b07f 100644 --- a/tests/registry/test_action_resource_contract.py +++ b/tests/registry/test_action_resource_contract.py @@ -1,4 +1,4 @@ -"""动作资源语义:``@action(material=Material.xxx(...))`` 从装饰器 / AST 到注册表 Schema 的行为合同。""" +"""动作资源语义:``@action(materials=Material.xxx(...))`` 从装饰器 / AST 到注册表 Schema 的行为合同。""" from __future__ import annotations @@ -33,7 +33,7 @@ class Result(TypedDict): @device(id="robot", category=["test"]) class Robot: - @action(material={material}) + @action(materials={material}) def move({signature}) -> Result: """执行一次物料动作。""" raise NotImplementedError @@ -236,30 +236,72 @@ def test_slot_parameters_carry_their_kind_in_the_schema(tmp_path: Path) -> None: assert "x-unilabos-slot" not in goal["label"] -def test_experimental_roles_warn_once_per_definition(tmp_path: Path, caplog) -> None: +def test_materials_field_warns_experimental_once_per_definition(tmp_path: Path, caplog) -> None: + """整个 materials= 字段是实验性功能:写了就按定义告警一次(列出用到的声明),重复扫描不再告警。""" + caplog.set_level(logging.WARNING) material = '[Material.load("material", device="vessel_device"), Material.order_sensitive()]' _scan_action(tmp_path, material) _scan_action(tmp_path, material) warnings = [record.getMessage() for record in caplog.records if "实验性功能" in record.getMessage()] assert len(warnings) == 1 + assert "materials= 是实验性功能" in warnings[0] assert "Material.load" in warnings[0] and "Material.order_sensitive" in warnings[0] - caplog.clear() - _scan_action(tmp_path, 'Material.move("material", to_site="target_site")', signature=_SIGNATURE + ", extra: str = ''") - assert not [record for record in caplog.records if "实验性功能" in record.getMessage()] + + +def test_material_actions_alone_also_warn_experimental(tmp_path: Path, caplog) -> None: + """move / pick / place / dispense 不再单独算稳定:只写一条 Material.move 也告警一次。""" + + caplog.set_level(logging.WARNING) + # 独立的模块名:告警按「定义 + 原因」进程内去重,不能与其他用例扫描过的 robot.Robot.move 同一身份 + path = tmp_path / "move_only_experimental.py" + path.write_text(_source('Material.move("material", to_site="target_site")'), encoding="utf-8") + _parse_file(path, tmp_path) + _parse_file(path, tmp_path) + warnings = [record.getMessage() for record in caplog.records if "实验性功能" in record.getMessage()] + assert len(warnings) == 1 + assert "move_only_experimental.Robot.move" in warnings[0] + assert "materials= 是实验性功能(Material.move)" in warnings[0] def test_experimental_warning_from_the_decorator(caplog) -> None: - from unilabos.registry.placeholder_type import ResourceSlot + from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot caplog.set_level(logging.WARNING) class Driver: - @action(material=Material.in_place("sample")) + @action(materials=Material.in_place("sample")) def stir_experimental(self, sample: ResourceSlot) -> None: pass - assert any("实验性功能 Material.in_place" in record.getMessage() for record in caplog.records) + @action(materials=Material.move("plate", to_site="target_site")) + def move_experimental(self, plate: ResourceSlot, target_site: SiteSlot) -> None: + pass + + messages = [record.getMessage() for record in caplog.records] + assert any("materials= 是实验性功能(Material.in_place)" in message for message in messages) + assert any("move_experimental" in message and "materials= 是实验性功能(Material.move)" in message for message in messages) + + +def test_old_material_field_name_fails_with_the_new_name(tmp_path: Path) -> None: + """改名前的 material= 在装饰器与 AST 扫描里都直接报错,提示改成 materials=(值不变)。""" + + source = ''' +from unilabos.registry.decorators import Material, action, device +from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot + +@device(id="old_material_field", category=["test"]) +class Driver: + @action(material=Material.move("plate", to_site="target_site")) + def run(self, plate: ResourceSlot, target_site: SiteSlot) -> None: + pass +''' + path = tmp_path / "old_material_field.py" + path.write_text(source, encoding="utf-8") + with pytest.raises(RemovedActionOptionError, match="material=.*字段改名为 materials="): + _parse_file(path, tmp_path) + with pytest.raises(RemovedActionOptionError, match="material=.*字段改名为 materials="): + _import(tmp_path, source, name="old_material_field_runtime") @pytest.mark.parametrize( @@ -295,5 +337,5 @@ def send(self, cmd: str) -> None: pass assert send._action_registry_meta["goal"] == {"command": "cmd"} - with pytest.raises(ValueError, match="material="): - action(action_type="unilabos_msgs.action:SendCmd", material=Material.in_place("cmd"))(send) + with pytest.raises(ValueError, match="materials= 只用于 JSON 动作"): + action(action_type="unilabos_msgs.action:SendCmd", materials=Material.in_place("cmd"))(send) diff --git a/tests/registry/test_site_selector_contract.py b/tests/registry/test_site_selector_contract.py index e7b566abf8..ffaeb73315 100644 --- a/tests/registry/test_site_selector_contract.py +++ b/tests/registry/test_site_selector_contract.py @@ -1,4 +1,4 @@ -"""库位参数(``SiteSlot``)与物料参数的关系:``@action(material=Material.site_picker(...))``。 +"""库位参数(``SiteSlot``)与物料参数的关系:``@action(materials=Material.site_picker(...))``。 ``SiteSelector`` 已与 ``SiteSlot`` 合一:库位参数只有一个类型 ``SiteSlot``,库位属于哪个物料参数、放进去的是 哪个物料参数、已占用库位的显示 / 可选策略写在 ``Material.site_picker``。生成的 ``x-unilabos-site-selector`` 扩展与 @@ -50,7 +50,7 @@ def _source(material: str, signature: str, *, header: str = "") -> str: @device(id="site_driver", category=["test"]) class Driver: - @action(material={material}) + @action(materials={material}) def action(self, {signature}) -> None: pass ''' @@ -105,7 +105,7 @@ def test_action_site_parameter_compiles_complete_relation_metadata(tmp_path: Pat def test_decorator_records_the_same_relation(tmp_path: Path) -> None: from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot - @action(material=Material.site_picker("site", of="warehouse")) + @action(materials=Material.site_picker("site", of="warehouse")) def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass @@ -114,7 +114,7 @@ def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: } with pytest.raises(MaterialRoleError, match="missing"): - @action(material=Material.site_picker("site", of="missing")) + @action(materials=Material.site_picker("site", of="missing")) def bad(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass diff --git a/unilabos/registry/action_options.py b/unilabos/registry/action_options.py index f2e8f21e67..c63ee15c87 100644 --- a/unilabos/registry/action_options.py +++ b/unilabos/registry/action_options.py @@ -3,12 +3,13 @@ 这些写法不再接受,写了就报错并指出新写法(见 ``docs/developer_guide/action_standard.md`` 的「不兼容变更」): - ``contract=``:所有 JSON 动作统一按签名生成并校验 schema,没有 opt-in 开关; -- ``resource_contract={...}``:资源语义改用 ``material=Material.xxx(...)``; +- ``resource_contract={...}``:资源语义改用 ``materials=Material.xxx(...)``; +- ``material=``:字段改名为 ``materials=``,值不变(一条 ``Material.xxx(...)`` 或它们组成的列表); - JSON 动作的 ``goal=`` / ``result=`` 重命名:字段名就是参数名 / 返回 TypedDict 的字段名 (ROS 动作类型的 ``goal`` / ``result`` 字段映射照旧); - 参数注解里的 ``Placeholder(...)``:前端选择器写在 ``@action(placeholder_keys={...})``; - 参数注解里的 ``SiteSelector(...)``:库位参数注解为 ``SiteSlot``,库位选择器提示写成 - ``material=Material.site_picker(...)``; + ``materials=Material.site_picker(...)``; - 按名字注入的动作上下文(参数叫 ``action_context`` 却没有 ``ActionContext`` 注解):框架按类型注入, 注解为 ``Optional[ActionContext]``(见 :mod:`unilabos.registry.action_context`)。 @@ -26,9 +27,13 @@ REMOVED_ACTION_OPTIONS: Dict[str, str] = { "contract": "所有 JSON 动作统一按签名生成并校验 schema,去掉 contract= 即可", "resource_contract": ( - "资源语义改用 material=Material.xxx(...),例如 material=Material.move(\"plate\", to_site=\"target_site\")、" - "material=Material.dispense(from_material=\"source\", to_materials=[\"target\"])、" - "material=[Material.in_place(\"sample\"), Material.order_sensitive()]" + "资源语义改用 materials=Material.xxx(...),例如 materials=Material.move(\"plate\", to_site=\"target_site\")、" + "materials=Material.dispense(from_material=\"source\", to_materials=[\"target\"])、" + "materials=[Material.in_place(\"sample\"), Material.order_sensitive()]" + ), + "material": ( + "字段改名为 materials=,值不变:把 material=Material.xxx(...) 写成 materials=Material.xxx(...)" + "(多条照旧写成列表);materials= 是实验性功能" ), } #: 只对 JSON 动作(没写 action_type)删除的选项 → 新写法。 @@ -44,7 +49,7 @@ "参数类型照常写,去掉 Annotated[..., Placeholder(...)] 外壳" ), "SiteSelector": ( - "库位参数注解为 SiteSlot,库位选择器提示写成 @action(material=Material.site_picker(\"库位参数\", " + "库位参数注解为 SiteSlot,库位选择器提示写成 @action(materials=Material.site_picker(\"库位参数\", " "of=\"拥有库位的物料或设备参数\", for_material=\"放进去的物料参数\", occupied=\"show\"))" ), } diff --git a/unilabos/registry/action_schema.py b/unilabos/registry/action_schema.py index ab4cf574bd..947852b108 100644 --- a/unilabos/registry/action_schema.py +++ b/unilabos/registry/action_schema.py @@ -5,7 +5,7 @@ - 严格解析器认识的注解(``str`` / ``int`` / ``float`` / ``bool``、``Literal``、``Optional`` 与 ``X | None``、``ResourceSlot`` / ``list[ResourceSlot]``、``list[X]``、``dict[str, JSONValue]``,以及 ``Annotated[..., Field(...)]`` / ``AllowedResourceTemplates``):严格 schema; -- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(material=Material.site_picker(...))`` 声明的 +- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(materials=Material.site_picker(...))`` 声明的 库位关系写进该 ``SiteSlot`` 参数的 ``x-unilabos-site-selector`` 扩展(前端库位选择器、预检与派发门禁用); - 没写注解、``Any``、``object``:接受任意 JSON 值(``{}``); - 默认值是 ``None`` 的参数按可空处理(``x: str = None`` 与 ``x: Optional[str] = None`` 相同); diff --git a/unilabos/registry/ast_registry_scanner.py b/unilabos/registry/ast_registry_scanner.py index 3392bba8d0..de1d90fe03 100644 --- a/unilabos/registry/ast_registry_scanner.py +++ b/unilabos/registry/ast_registry_scanner.py @@ -62,7 +62,7 @@ MAX_SCAN_DEPTH = 10 # 最大目录递归深度 MAX_SCAN_FILES = 1000 # 最大扫描文件数量 -_CACHE_VERSION = 28 # 28:Material.site_picker 的库位参数不再限定 uuid 格式(也可以给所属方下的库位名) +_CACHE_VERSION = 29 # 29:@action(material=) 改名为 materials=(旧名报错);整个字段告警「实验性功能」 # 允许点号分段(如 liquid_handler.prcxi),与内置 YAML 注册表的命名先例一致; # 点号只用于注册表模板名,设备实例 id(图节点)另有约束。 _DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$") @@ -1093,8 +1093,8 @@ def _extract_class_body( for name in REMOVED_MATERIAL_LOCK_OPTIONS: action_args.pop(name, None) json_action = not action_args.get("action_type") - # 已删除的写法(contract= / resource_contract= / JSON 动作的 goal= 与 result=,以及注解里的 - # Placeholder / SiteSelector)与装饰器同一套报错:整个文件记为扫描错误,错误信息指出新写法。 + # 已删除的写法(contract= / resource_contract= / 改名前的 material= / JSON 动作的 goal= 与 result=, + # 以及注解里的 Placeholder / SiteSelector)与装饰器同一套报错:整个文件记为扫描错误,错误信息指出新写法。 check_action_options(action_args, json_action=json_action, definition=definition) # 框架注入的参数(sample_uuids、按类型识别的 ActionContext)不属于动作接口; # 叫 action_context 却没有 ActionContext 注解的旧写法在这里报错 @@ -1109,10 +1109,10 @@ def _extract_class_body( draft: Dict[str, Any] = {} resource_contract: Dict[str, Any] = {} site_selectors: Dict[str, Any] = {} - material_value = action_args.pop("material", None) + material_value = action_args.pop("materials", None) if material_value is not None: if not json_action: - raise ValueError(f"{definition}:material= 只用于 JSON 动作(不写 action_type)") + raise ValueError(f"{definition}:materials= 只用于 JSON 动作(不写 action_type)") roles = material_roles_from_ast(material_value) resource_contract = material_contract(roles) site_selectors = material_site_selectors(roles) @@ -1127,7 +1127,7 @@ def _extract_class_body( ) canonical_schema = draft["schema"] if material_value is not None: - # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;实验性声明告警一次 + # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;materials= 是实验性功能,告警一次 goal_fields = canonical_schema["properties"]["goal"]["properties"] check_material_parameter_types( roles, diff --git a/unilabos/registry/decorators.py b/unilabos/registry/decorators.py index ba0df725e5..cd2dbf4888 100644 --- a/unilabos/registry/decorators.py +++ b/unilabos/registry/decorators.py @@ -40,8 +40,8 @@ def close(self): def set_valve_position(self, position): ... - # 资源语义:一个字段,Material 的一条或多条 - @action(material=Material.in_place("vessel")) + # 资源语义(实验性):一个字段,Material 的一条或多条 + @action(materials=Material.in_place("vessel")) def flush(self, vessel: ResourceSlot) -> None: ... @@ -280,7 +280,7 @@ def _slot_kind_of_annotation(annotation: Any) -> str: def _runtime_slot_kinds(func: Callable[..., Any], parameters: Any) -> Dict[str, str]: - """签名里每个参数(不含 self / cls / 可变参数)的槽位类型;用于对照 ``material=`` 引用的参数。""" + """签名里每个参数(不含 self / cls / 可变参数)的槽位类型;用于对照 ``materials=`` 引用的参数。""" import inspect import typing @@ -475,7 +475,7 @@ def action( execution_timeout: Optional[Union[float, str]] = None, estimate_duration_fixed: Any = _ESTIMATE_UNSET, estimate_duration_express: str = "", - material: Any = None, + materials: Any = None, **removed_options: Any, ): """ @@ -517,10 +517,11 @@ def AddProtocol(self): ... parent: 若为 True,当方法参数为空 (*args, **kwargs) 时,通过 MRO 从父类获取真实方法参数 node_type: 动作的节点类型 (NodeType.ILAB / NodeType.MANUAL_CONFIRM)。 不填写时不写入注册表。 - material: 动作的资源语义:物料动作 ``Material.move / pick / place / dispense``,以及实验性的 - ``Material.load / unload / in_place / site_picker / order_sensitive``,一条或多条组成的列表 - (见 ``unilabos.registry.material_roles``)。字符串都是参数名,注册时对照签名检查 - (物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot);实验性声明按定义告警一次。 + materials: (实验性)动作的资源语义:物料动作 ``Material.move / pick / place / dispense``,以及 + ``Material.load / unload / in_place / site_picker / order_sensitive``,一条或多条组成的列表 + (见 ``unilabos.registry.material_roles``)。字符串都是参数名,注册时对照签名检查 + (物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot);写了就按定义告警一次「实验性功能」。 + 旧字段名 ``material=`` 直接报错并提示改成 ``materials=``。 error_policy: 按异常类名匹配审批选项的策略。结构见 unilabos.registry.action_policy.ErrorPolicy。 timeout: 硬超时(秒,正数)。到期后执行面协作式取消动作,并以 @@ -536,7 +537,7 @@ def AddProtocol(self): ... 同一语法("cycles * 2",也认 V1 的 "{cycles} * 2");派发时 按真实 action_args 求值,失败时退回兜底。 详见 unilabos.registry.action_duration。 - removed_options: 已删除的 ``contract`` / ``resource_contract`` 直接报错并指出新写法 + removed_options: 已删除的 ``contract`` / ``resource_contract`` / ``material`` 直接报错并指出新写法 (``unilabos.registry.action_options``)。已移除的 ``materials_need_lock`` / ``materials_free`` 照常加载:值被忽略,按定义告警一次。物料锁不再按动作改写: 每个物料入参(ResourceSlot / List[ResourceSlot],或 placeholder_keys 标为 @@ -561,13 +562,13 @@ def decorator(func: F) -> F: ) resource_contract: Dict[str, Any] = {} site_selectors: Dict[str, Any] = {} - if material is not None: + if materials is not None: from unilabos.registry.material_roles import material_contract, material_site_selectors if not json_action: - raise ValueError(f"{definition}:material= 只用于 JSON 动作(不写 action_type)") - resource_contract = material_contract(material) - site_selectors = material_site_selectors(material) + raise ValueError(f"{definition}:materials= 只用于 JSON 动作(不写 action_type)") + resource_contract = material_contract(materials) + site_selectors = material_site_selectors(materials) if _inspect.iscoroutinefunction(func): @wraps(func) @@ -618,15 +619,15 @@ def wrapper(*args, **kwargs): unknown = [name for name in dict.fromkeys(referenced) if name not in signature_parameters] if unknown: raise MaterialRoleError( - f"{func.__qualname__} 的 material= 引用了签名里没有的参数:{'、'.join(unknown)}" + f"{func.__qualname__} 的 materials= 引用了签名里没有的参数:{'、'.join(unknown)}" ) - if material is not None: - # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;实验性声明按定义告警一次 + if materials is not None: + # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;materials= 是实验性功能,按定义告警一次 from unilabos.registry.material_roles import check_material_parameter_types, warn_experimental slots = _runtime_slot_kinds(func, signature_parameters) - check_material_parameter_types(material, slots.get, definition=definition) - warn_experimental(material, definition) + check_material_parameter_types(materials, slots.get, definition=definition) + warn_experimental(materials, definition) if resource_contract: meta["resource_contract"] = resource_contract if site_selectors: diff --git a/unilabos/registry/material_roles.py b/unilabos/registry/material_roles.py index 595d677923..8d291f8db2 100644 --- a/unilabos/registry/material_roles.py +++ b/unilabos/registry/material_roles.py @@ -1,26 +1,26 @@ -"""动作的资源语义:``@action(material=...)`` 唯一的写法。 +"""动作的资源语义:``@action(materials=...)`` 唯一的写法(实验性)。 -``Material`` 声明动作真实的物料动作,值是 ``Material`` 的一个方法调用,或多个调用组成的列表: +``materials=`` 的值是 ``Material`` 的一个方法调用,或多个调用组成的列表: from unilabos.registry.decorators import action, Material - @action(material=Material.move("plate", to_site="target_site")) + @action(materials=Material.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... - @action(material=Material.dispense(from_material="source", to_materials=["target"])) + @action(materials=Material.dispense(from_material="source", to_materials=["target"])) def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... -稳定的物料动作:``move`` / ``pick`` / ``place`` / ``dispense``。不代表物料动作的声明(``load`` / ``unload`` -跨动作设备独占、``in_place`` 原位检查、``site_picker`` 库位选择器提示、``order_sensitive`` 顺序约束)仍写在 -``material=`` 里,但属于实验性功能:注册时按定义告警一次。 +物料动作:``move`` / ``pick`` / ``place`` / ``dispense``。不代表物料动作的声明:``load`` / ``unload`` 跨动作 +设备独占、``in_place`` 原位检查、``site_picker`` 库位选择器提示、``order_sensitive`` 顺序约束。整个 +``materials=`` 字段都是实验性功能:写了就按定义告警一次,语义与写法以后可能调整。 字符串参数都是动作的参数名,注册时对照签名检查:物料是 ``ResourceSlot``,库位是 ``SiteSlot``(库位 uuid), 设备是 ``DeviceSlot``(省略即执行设备)。内部规范化成第 2 版资源合同 (``x-unilabos-action-contract.resource_contract``),调度器照旧按合同执行;``site_picker`` 不进资源合同, 写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展。 -旧写法(``transfer`` / ``aliquot`` / ``site`` / ``uses``,带 ``owner`` / ``site`` / ``carriers`` 的 ``pick`` / ``place``) -直接报错并给出新写法。 +旧写法(字段名 ``material=``,``transfer`` / ``aliquot`` / ``site`` / ``uses``,带 ``owner`` / ``site`` / +``carriers`` 的 ``pick`` / ``place``)直接报错并给出新写法。 本模块只依赖标准库与纯声明的合同规范化:装饰器(导入期)与 AST 扫描(不导入作者模块)共用。 """ @@ -50,8 +50,6 @@ def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> } #: 不进资源合同、写进参数 schema 扩展的语义。 _SCHEMA_KINDS = frozenset({"site_picker"}) -#: 实验性声明(注册时按定义告警一次)。 -EXPERIMENTAL_KINDS = frozenset({"load", "unload", "in_place", "site_picker", "order_sensitive"}) #: 搬运设备上夹爪库位的固定角色。 GRIPPER_ROLE = "gripper" #: ``site_picker`` 的已占用库位策略 → ``(show_occupied, allow_occupied)``。 @@ -61,7 +59,7 @@ def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> class MaterialRoleError(ValueError): - """``material=`` 写法不对:注册失败并指出正确写法。""" + """``materials=`` 写法不对:注册失败并指出正确写法。""" def _names(value: Union[str, Sequence[str], None], label: str) -> List[str]: @@ -95,10 +93,6 @@ class MaterialRole: kind: str fields: Tuple[Tuple[str, Any], ...] = () - @property - def experimental(self) -> bool: - return self.kind in EXPERIMENTAL_KINDS - def values(self) -> Dict[str, Any]: return dict(self.fields) @@ -203,9 +197,9 @@ def parameter_types(self) -> List[Tuple[str, str, str]]: class Material: - """资源语义的唯一入口:每个方法返回一条语义,``@action(material=...)`` 接收一条或一个列表。""" + """资源语义的唯一入口:每个方法返回一条语义,``@action(materials=...)`` 接收一条或一个列表(实验性)。""" - # ------------------------------------------------------------------ 物料动作(稳定) + # ------------------------------------------------------------------ 物料动作 @staticmethod def move( @@ -298,11 +292,11 @@ def dispense(*, from_material: str, to_materials: Union[str, Sequence[str]]) -> raise MaterialRoleError("Material.dispense 的来源与目标必须是不同的参数") return MaterialRole("dispense", (("from_material", source), ("to_materials", targets))) - # ------------------------------------------------------------------ 实验性声明 + # ------------------------------------------------------------------ 不代表物料动作的声明 @staticmethod def load(material: str, *, device: Optional[str] = None, from_device: Optional[str] = None) -> MaterialRole: - """(实验性)把物料装进设备 ``device``(``DeviceSlot`` 参数,省略即执行设备),任务托管设备直到 ``unload``。 + """把物料装进设备 ``device``(``DeviceSlot`` 参数,省略即执行设备),任务托管设备直到 ``unload``。 ``from_device``:同时从另一台设备(``DeviceSlot`` 参数)转出。 """ @@ -318,14 +312,14 @@ def load(material: str, *, device: Optional[str] = None, from_device: Optional[s @staticmethod def unload(material: str, *, device: Optional[str] = None) -> MaterialRole: - """(实验性)把物料从设备 ``device``(``DeviceSlot`` 参数,省略即执行设备)取出并结束设备托管。""" + """把物料从设备 ``device``(``DeviceSlot`` 参数,省略即执行设备)取出并结束设备托管。""" release = _optional(device, "Material.unload 的 device") or EXECUTING_DEVICE return MaterialRole("unload", (("material", _name(material, "Material.unload 的物料")), ("release", release))) @staticmethod def in_place(material: str) -> MaterialRole: - """(实验性)物料必须仍在执行设备内(原位处理)。""" + """物料必须仍在执行设备内(原位处理)。""" return MaterialRole("in_place", (("material", _name(material, "Material.in_place 的物料")),)) @@ -337,7 +331,7 @@ def site_picker( for_material: Optional[str] = None, occupied: str = "show", ) -> MaterialRole: - """(实验性)前端库位选择器提示:``SiteSlot`` 参数 ``site`` 列出所属方 ``of`` 的库位。 + """前端库位选择器提示:``SiteSlot`` 参数 ``site`` 列出所属方 ``of`` 的库位。 ``of`` 是 ``ResourceSlot``(所属物料)或 ``DeviceSlot``(所属设备根节点)参数,省略时是执行设备根节点; ``for_material`` 是要放进去的物料参数(可省略);``occupied``:``"hide"`` 不列出已占用的库位, @@ -358,7 +352,7 @@ def site_picker( @staticmethod def order_sensitive() -> MaterialRole: - """(实验性)同一资源上的兄弟动作必须显式排序(只约束计划)。""" + """同一资源上的兄弟动作必须显式排序(只约束计划)。""" return MaterialRole("order_sensitive") @@ -398,41 +392,41 @@ def _roles(value: Any) -> List[MaterialRole]: roles = list(value) if isinstance(value, (list, tuple)) else [value] for role in roles: if not isinstance(role, MaterialRole): - raise MaterialRoleError("material= 只接受 Material.xxx(...) 或它们组成的列表") + raise MaterialRoleError("materials= 只接受 Material.xxx(...) 或它们组成的列表") if not roles: - raise MaterialRoleError("material= 至少写一条 Material.xxx(...)") + raise MaterialRoleError("materials= 至少写一条 Material.xxx(...)") return roles def material_roles(value: Any) -> List[MaterialRole]: - """``material=`` 的值(一条语义或列表)→ 语义列表;``None`` 为空列表。""" + """``materials=`` 的值(一条语义或列表)→ 语义列表;``None`` 为空列表。""" return [] if value is None else _roles(value) -def experimental_kinds(value: Any) -> List[str]: - """``material=`` 里用到的实验性声明(按出现顺序去重)。""" +def material_kinds(value: Any) -> List[str]: + """``materials=`` 里用到的声明种类(按出现顺序去重)。""" - return list(dict.fromkeys(role.kind for role in material_roles(value) if role.experimental)) + return list(dict.fromkeys(role.kind for role in material_roles(value))) def warn_experimental(value: Any, definition: str) -> None: - """注册时按定义告警一次:用到了实验性声明(装饰器与 AST 扫描共用同一身份,同一定义只告警一次)。""" + """注册时按定义告警一次:整个 ``materials=`` 字段是实验性功能(装饰器与 AST 扫描共用同一身份)。""" - kinds = experimental_kinds(value) + kinds = material_kinds(value) if not kinds: return from unilabos.registry.action_schema import warn_once warn_once( definition, - "material= 用到了实验性功能 " + "、".join(f"Material.{kind}" for kind in kinds) - + ":语义与写法以后可能调整", + "materials= 是实验性功能(" + "、".join(f"Material.{kind}" for kind in kinds) + + "):语义与写法以后可能调整", ) def material_contract(value: Any) -> Dict[str, Any]: - """``material=`` 的值(一条语义或列表)→ 规范化的第 2 版资源合同;``None`` 或只有 ``site_picker`` 时返回空字典。""" + """``materials=`` 的值(一条语义或列表)→ 规范化的第 2 版资源合同;``None`` 或只有 ``site_picker`` 时返回空字典。""" if value is None: return {} @@ -454,11 +448,11 @@ def material_contract(value: Any) -> Dict[str, Any]: try: return normalize_action_resource_contract(raw) except ActionResourceContractError as error: - raise MaterialRoleError(f"material= 写法无效:{error.message}") from None + raise MaterialRoleError(f"materials= 写法无效:{error.message}") from None def material_site_selectors(value: Any) -> Dict[str, Dict[str, Any]]: - """``material=`` 里的 ``Material.site_picker(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" + """``materials=`` 里的 ``Material.site_picker(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" if value is None: return {} @@ -474,7 +468,7 @@ def material_site_selectors(value: Any) -> Dict[str, Dict[str, Any]]: def material_parameter_types(value: Any) -> List[Tuple[str, str, str]]: - """``material=`` 引用的全部参数与要求的类型(见 :meth:`MaterialRole.parameter_types`)。""" + """``materials=`` 引用的全部参数与要求的类型(见 :meth:`MaterialRole.parameter_types`)。""" items: List[Tuple[str, str, str]] = [] for role in material_roles(value): @@ -483,7 +477,7 @@ def material_parameter_types(value: Any) -> List[Tuple[str, str, str]]: def check_material_parameter_types(value: Any, slot_of, *, definition: str) -> None: - """对照签名检查 ``material=`` 引用的参数存在且类型正确。 + """对照签名检查 ``materials=`` 引用的参数存在且类型正确。 ``slot_of(name)`` 返回参数的槽位类型:``"resource"``(单个 ``ResourceSlot``)、``"resource_list"``、 ``"site"``、``"device"``、``"device_list"``、``""``(其他类型);参数不存在返回 ``None``。 @@ -556,20 +550,20 @@ def add(value: Any) -> None: def material_roles_from_ast(value: Any) -> List[MaterialRole]: - """AST 扫描提取的 ``material=`` 值(``{"_call": ..., "_pos_0": ...}`` 或其列表)→ 语义列表。""" + """AST 扫描提取的 ``materials=`` 值(``{"_call": ..., "_pos_0": ...}`` 或其列表)→ 语义列表。""" items = value if isinstance(value, list) else [value] roles: List[MaterialRole] = [] for item in items: if not isinstance(item, Mapping) or "_call" not in item: - raise MaterialRoleError("material= 只接受 Material.xxx(...) 或它们组成的列表(参数须是字面量)") + raise MaterialRoleError("materials= 只接受 Material.xxx(...) 或它们组成的列表(参数须是字面量)") call = str(item["_call"]) prefix, _, method = call.rpartition(".") module, _, owner = prefix.rpartition(":") if owner != "Material" and prefix != "Material": - raise MaterialRoleError(f"material= 只接受 Material.xxx(...),不认识 {call}") + raise MaterialRoleError(f"materials= 只接受 Material.xxx(...),不认识 {call}") if module and module not in _MATERIAL_MODULES: - raise MaterialRoleError(f"material= 的 Material 必须从 unilabos.registry.decorators 导入,不认识 {call}") + raise MaterialRoleError(f"materials= 的 Material 必须从 unilabos.registry.decorators 导入,不认识 {call}") factory = getattr(Material, method, None) if not method.startswith("_") else None if factory is None: raise MaterialRoleError(f"Material 没有 {method}(...)") @@ -583,15 +577,14 @@ def material_roles_from_ast(value: Any) -> List[MaterialRole]: __all__ = [ - "EXPERIMENTAL_KINDS", "GRIPPER_ROLE", "Material", "MaterialRole", "MaterialRoleError", "check_material_parameter_types", "contract_parameter_names", - "experimental_kinds", "material_contract", + "material_kinds", "material_parameter_types", "material_roles", "material_roles_from_ast", diff --git a/unilabos/registry/site_selector_schema.py b/unilabos/registry/site_selector_schema.py index 62358bbeb9..1634db231e 100644 --- a/unilabos/registry/site_selector_schema.py +++ b/unilabos/registry/site_selector_schema.py @@ -1,6 +1,6 @@ """库位关系(``Material.site_picker(...)``)的静态跨字段校验。 -库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(material=Material.site_picker(...))``:库位属于 +库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(materials=Material.site_picker(...))``:库位属于 哪个物料参数(``owner``)、放进去的是哪个物料参数(``occupant``)、已占用库位的显示 / 可选策略。注册表 把它写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展;本模块在生成 schema 时核对关系指向的参数。 """ From 2774daf9fdcd0467d7379ff52e4c8fcc9687b465 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:08:02 +0800 Subject: [PATCH 19/27] docs: describe @action(materials=) as one experimental field The guides, skills and AGENTS.md now use materials=, drop the stable / experimental split inside the field, and list the old material= in the breaking-changes table. --- .cursor/skills/add-device/SKILL.md | 7 ++-- .cursor/skills/create-device-package/SKILL.md | 18 ++++---- AGENTS.md | 2 +- docs/developer_guide/action_standard.md | 41 ++++++++++--------- docs/developer_guide/add_device.md | 2 +- docs/developer_guide/v1_file_index/rest.md | 4 +- .../v1_inventory_preflight_contracts.md | 2 +- .../workflow_resource_custody.md | 4 +- .../workflow_static_conditions.md | 2 +- 9 files changed, 43 insertions(+), 39 deletions(-) diff --git a/.cursor/skills/add-device/SKILL.md b/.cursor/skills/add-device/SKILL.md index 1e80b68a58..02f7213842 100644 --- a/.cursor/skills/add-device/SKILL.md +++ b/.cursor/skills/add-device/SKILL.md @@ -159,13 +159,14 @@ from unilabos.registry.decorators import action auto_prefix=True, # 强制使用 auto- 前缀 parent=True, # 从父类 MRO 获取参数签名 ) -@action(material=Material.move("plate", to_site="target_site")) # 资源语义:一个字段,见下 +@action(materials=Material.move("plate", to_site="target_site")) # 资源语义(实验性):一个字段,见下 ``` JSON 动作(不写 `action_type`)的参数与返回值只有一个标准:注册表按签名生成 schema,调度端与 Host 调用前按它校验参数, 调用后按返回注解校验返回值。写了类型的参数严格校验;没写类型或 `Any` 接受任意 JSON 值;没有默认值的参数必填。 -资源语义用 `material=`,声明动作真实的物料动作 `Material.move / pick / place / dispense(...)`,多个写成列表; -不代表物料动作的 `Material.load / unload / in_place / site_picker / order_sensitive(...)` 也写在这里,但属于实验性(注册时告警一次)。 +资源语义用 `materials=`,声明动作真实的物料动作 `Material.move / pick / place / dispense(...)`,多个写成列表; +不代表物料动作的 `Material.load / unload / in_place / site_picker / order_sensitive(...)` 也写在这里。整个 `materials=` 字段是实验性功能 +(写了就按定义告警一次);改名前的 `material=` 注册时报错。 字符串都是参数名:物料 `ResourceSlot`、库位 `SiteSlot`(库位 uuid,所属方由库位决定)、设备 `DeviceSlot`(省略即执行设备)。 库位选择器列出哪个所属方的库位写 `Material.site_picker("site", of="carrier", for_material="sample")`。 `DeviceSlot` 参数加设备锁、`SiteSlot` 参数加库位锁,不需要额外声明。 diff --git a/.cursor/skills/create-device-package/SKILL.md b/.cursor/skills/create-device-package/SKILL.md index 9e7d3b260c..78166a9d8a 100644 --- a/.cursor/skills/create-device-package/SKILL.md +++ b/.cursor/skills/create-device-package/SKILL.md @@ -117,12 +117,12 @@ class : - `always_free=True`:动作不占用设备 busy 队列,适合 `get_status`、`query_*`、`ping`、连接测试等轻量查询动作;会在 `action_value_mappings..always_free` 中写入 `true`。 - `feedback_interval`:动作反馈发布间隔,单位秒;AST 扫描默认补 `1.0`,长任务可调大,例如 `5.0`、`30.0`。 - `goal_default`:编辑器里的初始参数值,叠加在签名默认值上;它不让参数变成可选,没有签名默认值的参数仍然必填。 -- `material`:资源语义(搬运、两步搬运、分装;实验性的装载托管、原位处理、库位选择器提示、顺序敏感),一个字段,值是 `Material` 的一个方法或列表,见下文「资源语义」。 +- `materials`(实验性,写了就按定义告警一次):资源语义(搬运、两步搬运、分装;以及装载托管、原位处理、库位选择器提示、顺序敏感),一个字段,值是 `Material` 的一个方法或列表,见下文「资源语义」。 - `placeholder_keys`:前端选择器 `{参数名: PLACEHOLDER_...}`。物料 `ResourceSlot`、设备 `DeviceSlot`、库位 `SiteSlot` 由类型自动推出; 节点、人工确认指派人、扣减等没有专门类型的选择器,或想把某个参数换一种显示,就在这里手写。两者取并集,同一参数以手写为准; 只改前端显示,参数类型与校验不变(兼容规则:手写成 `unilabos_resources` 的参数也加物料锁)。键必须是参数名。 - `handles`:动作级输入/输出端口,使用 `ActionInputHandle`、`ActionOutputHandle`;不写时按 schema 生成。 -- 已删除、写了会报错的写法:`contract=`、`resource_contract=`、JSON 动作的 `goal=` / `result=` 重命名(参数名就是字段名), +- 已删除、写了会报错的写法:`contract=`、`resource_contract=`、改名前的 `material=`(改成 `materials=`,值不变)、JSON 动作的 `goal=` / `result=` 重命名(参数名就是字段名), 注解里的 `Placeholder(...)`(改成 `placeholder_keys=`)与 `SiteSelector(...)`(改成 `SiteSlot` + `Material.site_picker(...)`), 以及 `Material.transfer / aliquot / site / uses`、带 `owner` / `site` / `carriers` 的 `Material.pick / place`(新写法见下文「资源语义」)。 @@ -144,26 +144,26 @@ class : 旧的 `@always_free` 仍可被 AST 扫描识别,但新设备包优先使用 `@action(always_free=True)`,把动作元数据集中在一个装饰器里。 -#### 资源语义:`material=` +#### 资源语义:`materials=`(实验性) ```python from unilabos.registry.decorators import Material, action from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="搬运板", material=Material.move("plate", to_site="target_site")) +@action(display_name="搬运板", materials=Material.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="抓取", material=Material.pick("plate")) +@action(display_name="抓取", materials=Material.pick("plate")) def pick_plate(self, plate: ResourceSlot) -> dict: ... -@action(display_name="放下", material=Material.place("plate", to_site="target_site")) +@action(display_name="放下", materials=Material.place("plate", to_site="target_site")) def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="原位搅拌", material=[Material.in_place("sample"), Material.order_sensitive()]) +@action(display_name="原位搅拌", materials=[Material.in_place("sample"), Material.order_sensitive()]) def stir(self, sample: ResourceSlot, rpm: int = 300) -> None: ... ``` -物料动作(稳定): +物料动作: | 写法 | 含义 | | --- | --- | @@ -172,7 +172,7 @@ def stir(self, sample: ResourceSlot, rpm: int = 300) -> None: ... | `Material.place("plate", to_site="site", carrier_device=None)` | 两步搬运第二步:从夹爪库位放到 `to_site`,结束托管 | | `Material.dispense(from_material="source", to_materials=["target", ...])` | 按实测量在容器之间转移内容物 | -实验性(注册时告警一次): +不代表物料动作的声明: | 写法 | 含义 | | --- | --- | diff --git a/AGENTS.md b/AGENTS.md index 8f9bc6eac4..4a15670713 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ pytest tests/resources/test_resourcetreeset_groups.py::test_name # single test ### Core Layers -**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one decorator field, `@action(material=Material.move(...) | [...])` (`registry/material_roles.py`): the stable material actions are `Material.move` / `pick` / `place` / `dispense` (sites are `SiteSlot` uuids whose owner the scheduler derives from the site, carriers are `DeviceSlot` parameters defaulting to the executing device and its `gripper` site); `load` / `unload` / `in_place` / `site_picker` / `order_sensitive` stay in `material=` but are experimental (warned once per definition). A site parameter is annotated `SiteSlot`; `Material.site_picker(...)` writes the selector hint into that field's `x-unilabos-site-selector` extension. `Material.transfer` / `aliquot` / `site` / `uses` and `pick` / `place` with `owner` / `site` / `carriers` are rejected with the new spelling. Parameters are locked by type: `ResourceSlot` material locks, `DeviceSlot` device locks, `SiteSlot` site locks. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. +**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one experimental decorator field, `@action(materials=Material.move(...) | [...])` (`registry/material_roles.py`; any use warns once per definition, the old field name `material=` is rejected with the new spelling): the material actions are `Material.move` / `pick` / `place` / `dispense` (sites are `SiteSlot` uuids whose owner the scheduler derives from the site, carriers are `DeviceSlot` parameters defaulting to the executing device and its `gripper` site); `load` / `unload` / `in_place` / `site_picker` / `order_sensitive` are the declarations that are not material actions. A site parameter is annotated `SiteSlot`; `Material.site_picker(...)` writes the selector hint into that field's `x-unilabos-site-selector` extension. `Material.transfer` / `aliquot` / `site` / `uses` and `pick` / `place` with `owner` / `site` / `carriers` are rejected with the new spelling. Parameters are locked by type: `ResourceSlot` material locks, `DeviceSlot` device locks, `SiteSlot` site locks. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, the old `material=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. **Resource Tracking** (`unilabos/resources/resource_tracker.py`): Pydantic-based `ResourceDict` → `ResourceDictInstance` → `ResourceTreeSet` hierarchy. `ResourceTreeSet` is the canonical in-memory representation of all devices and resources, used throughout the system, and it owns every resource conversion: flat dicts (`from_raw_dict_list`, `dump`/`load`) and PLR (`from_plr_resources`, `to_plr_resources`). PLR drafts from a registry resource class come from `resources/materials.py:instantiate_registry_resource`. There is no separate graph I/O module: device graphs are node-link JSON only (GraphML is not supported) and are turned into runtime structures by the Graph Authority (`server/services/materials/graph.py:load_graph_payload`). diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 9ea5e997f6..0ed8f8c3b1 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -17,7 +17,7 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) | `Annotated[X, Field(ge=, le=, min_length=, max_length=, title=, description=)]` | 带范围与说明 | 严格 | | `ResourceSlot` / `list[ResourceSlot]` | 物料引用 `{"uuid": ...}`(或按库位绑定的 `{"site_uuid": ...}`,准入时解析),加物料锁 | 严格;Host 解析成物料实例 | | `DeviceSlot` / `SiteSlot` | 设备 ID / 库位 UUID 字符串(字段带 `x-unilabos-slot: "device"` / `"site"`),加设备锁 / 库位锁 | 严格 | -| `SiteSlot` 且写了 `material=Material.site_picker("site", of=...)` | 库位 UUID、所属方下的库位名(工作流里写死的工位,派发前解析成库位 uuid),或按所属物料选择的 `{"owner_uuid": ...}`(准入时选定);带库位关系(`x-unilabos-site-selector`),不限定 uuid 格式 | 严格;预检与派发前核对库位归属与占用 | +| `SiteSlot` 且写了 `materials=Material.site_picker("site", of=...)` | 库位 UUID、所属方下的库位名(工作流里写死的工位,派发前解析成库位 uuid),或按所属物料选择的 `{"owner_uuid": ...}`(准入时选定);带库位关系(`x-unilabos-site-selector`),不限定 uuid 格式 | 严格;预检与派发前核对库位归属与占用 | | `dict`、`Dict[str, Any]`、`Mapping` | 任意 JSON 对象 | 只校验是对象 | | 没写注解、`Any`、`object` | 任意 JSON 值(`{}`) | 不限值 | | 严格解析器不认识的注解(`Union[int, str]`、`List[Optional[float]]`、枚举、PLR / pydantic 类型……) | 退回注册表原来的签名类型推断 | 按推断结果;推断不出的部分接受任意值 | @@ -93,12 +93,14 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 手写 YAML 注册表里的 JSON 动作要跑一次 `unilab --complete_registry`,才会按同一标准重新生成 schema; 没有这个扩展的 schema(ROS 动作类型,或还没补全的手写 YAML)不做上面的校验。 -## 资源语义:`material=` +## 资源语义:`materials=`(实验性) + +**整个 `materials=` 字段都是实验性功能**:写了就在注册时按定义告警一次「materials= 是实验性功能(用到的声明):语义与写法 +以后可能调整」,装饰器(导入时)与注册表 AST 扫描共用同一身份,同一定义只告警一次。 `Material` 声明的是动作**真实的物料动作**:搬运一件容器、两步搬运、在容器之间转移内容物。调度器在派发前按它解析 来源、目标与搬运设备,动作成功后由核心一次结算物料位置 / 内容物(`PhysicalMove` / 搬运回执、`AliquotReceipt`)。 -不代表物料动作的声明(跨动作的设备独占、原位检查、库位选择器提示、顺序约束)仍然写在 `material=` 里,但属于 -**实验性**功能:注册时按定义告警一次「实验性功能」,语义与写法以后可能调整。 +不代表物料动作的声明(跨动作的设备独占、原位检查、库位选择器提示、顺序约束)也写在 `materials=` 里。 一个动作的语义只用 `@action` 的这一个字段声明,值是 `Material` 的一个方法调用,多个语义写成列表。 字符串参数都是动作的参数名,注册时对照签名检查参数存在、类型正确: @@ -113,20 +115,20 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 from unilabos.registry.decorators import Material, action from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="搬运板", material=Material.move("plate", to_site="target_site")) +@action(display_name="搬运板", materials=Material.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="抓取", material=Material.pick("plate")) +@action(display_name="抓取", materials=Material.pick("plate")) def pick_plate(self, plate: ResourceSlot) -> dict: ... -@action(display_name="放下", material=Material.place("plate", to_site="target_site")) +@action(display_name="放下", materials=Material.place("plate", to_site="target_site")) def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="移液", material=Material.dispense(from_material="source", to_materials=["target"])) +@action(display_name="移液", materials=Material.dispense(from_material="source", to_materials=["target"])) def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... ``` -### 物料动作(稳定) +### 物料动作 | 写法 | 含义 | 内部合同字段 | | --- | --- | --- | @@ -148,7 +150,7 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl - **分装 / 移液**:`dispense` 的来源与每个目标都是 `ResourceSlot`;驱动按实际量回报 `AliquotReceipt`,核心按回执结算内容物。 语义与以前的 `Material.aliquot` 完全相同,只是改名。 - 这几种都会锁住涉及的物料(物料锁)与来源 / 目标库位所属的设备(设备锁);`move` / `pick` / `place` 之间不能组合 - (一个动作只能有一种搬运声明),`dispense` 可以与它们之外的实验性声明同时写。 + (一个动作只能有一种搬运声明),`dispense` 可以与下面不代表物料动作的声明同时写。 - 物料的**消耗 / 新建**这次不做声明式写法:消耗仍然用工作流节点上的 `inventory=`,新建仍在驱动里调用 `materials.create`(见下节)。 ### 声明式 `Material` 与运行时 `materials` 的分工 @@ -157,7 +159,7 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl | | 声明式 `Material`(`registry/material_roles.py`) | 运行时 `materials`(`unilabos.resources.materials`) | | --- | --- | --- | -| 写在哪里 | `@action(material=...)` | 驱动代码里,动作执行时调用 | +| 写在哪里 | `@action(materials=...)` | 驱动代码里,动作执行时调用 | | 谁读 / 谁执行 | 调度器派发前读:解析来源、目标、搬运设备,加锁、预留库位;动作成功后**核心**结算 | 驱动直接调用,立即改权威 | | 典型操作 | `move` / `pick` / `place`(`PhysicalMove` / 搬运回执)、`dispense`(`AliquotReceipt`) | `create` / `ensure` / `get` / `search` / `resolve` / `assign` / `update` / `remove` / `snapshot` / `transfer` / `apply_substances` …… | @@ -172,9 +174,9 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl 删除(`remove`)、启动时对齐(`ensure`)、查询(`get` / `search` / `resolve` / `snapshot`)等。 - `create` / `ensure` 这次没有声明式对应写法。 -### 实验性声明 +### 不代表物料动作的声明 -仍然写在 `material=` 里;注册时按定义告警一次「实验性功能」。 +同样写在 `materials=` 里(与整个字段一样是实验性功能)。 | 写法 | 含义 | 内部合同字段 | | --- | --- | --- | @@ -200,7 +202,7 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl 空值(`None` / `""` / `[]`)不加锁。`always_free` 只免除执行设备自身的动作锁,按类型加的设备锁 / 库位锁照旧。 -### 库位参数:`SiteSlot` 与 `Material.site_picker`(实验性) +### 库位参数:`SiteSlot` 与 `Material.site_picker` 库位参数只有一个类型 `SiteSlot`(值是库位 UUID,前端用库位选择器填写)。选择器列出哪个所属方的库位、放进去的是哪件物料、 已占用的库位怎么处理,写在 `Material.site_picker`: @@ -211,7 +213,7 @@ from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot @action( display_name="放到库位", - material=Material.site_picker("site", of="carrier", for_material="sample", occupied="show"), + materials=Material.site_picker("site", of="carrier", for_material="sample", occupied="show"), ) def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = None) -> None: ... ``` @@ -303,9 +305,10 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | 删除的写法 | 新写法 | | --- | --- | | `@action(contract="typed")` / `contract="legacy"` | 去掉:所有 JSON 动作同一标准 | -| `@action(resource_contract={...})` | `@action(material=Material.xxx(...))`,对照表见上 | +| `@action(resource_contract={...})` | `@action(materials=Material.xxx(...))`,对照表见上 | +| `@action(material=Material.xxx(...))` / `material=[...]`(字段改名前的写法) | `@action(materials=Material.xxx(...))` / `materials=[...]`:只改字段名,值不变;`materials=` 是实验性功能,写了就按定义告警一次 | | `Annotated[T, Placeholder(PLACEHOLDER_...)]`(`unilabos.registry.annotations.Placeholder`) | `@action(placeholder_keys={"参数名": PLACEHOLDER_...})`,参数照常注解为 `T` | -| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(material=Material.site_picker("参数名", of=..., for_material=..., occupied=...))`;生成的 schema 扩展与以前相同 | +| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(materials=Material.site_picker("参数名", of=..., for_material=..., occupied=...))`;生成的 schema 扩展与以前相同 | | JSON 动作的 `@action(goal={...})` / `result={...}` 重命名 | 去掉:字段名就是参数名 / 返回 TypedDict 的字段名(要改名就改参数名) | | 按名字注入的动作上下文:参数叫 `action_context` 但没有 `ActionContext` 注解 | 注解为 `Optional[ActionContext]`(`from unilabos.client.host.runtime.action import ActionContext`),名字随意;没有注解的 `action_context` 参数注册时报错(自动动作同样) | @@ -324,8 +327,8 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | `Material.uses(device=[...], tool=[...], motion=[...], site=[...], material=[...])` | 删除:参数按类型加锁(`ResourceSlot` 物料锁、`DeviceSlot` 设备锁、`SiteSlot` 库位锁),把参数注解成对应类型即可 | | `Material.load("sample", device="vessel")`(`vessel` 是 `str` / `ResourceSlot`) | `vessel` 注解为 `DeviceSlot`;装进执行设备本身时省略 `device=` | -行为上的变化:`DeviceSlot` / `SiteSlot` 参数现在默认加设备锁 / 库位锁;`load` / `unload` / `in_place` / `site_picker` / -`order_sensitive` 注册时告警一次「实验性功能」;搬运设备的夹爪库位角色统一为 `gripper`,已部署的物料权威里旧角色名 +行为上的变化:`DeviceSlot` / `SiteSlot` 参数现在默认加设备锁 / 库位锁;字段改名为 `materials=`,整个字段(包括 +`move` / `pick` / `place` / `dispense`)注册时按定义告警一次「实验性功能」;搬运设备的夹爪库位角色统一为 `gripper`,已部署的物料权威里旧角色名 (如 `robot.gripper`)不会随设备声明自动更新,需要重建或改写这些库位的 `meta_data.role`;声明的搬运在动作成功后可以不交 搬运回执(核心按冻结计划结算);`site_picker` 的库位参数不再限定 uuid 格式(也可以给所属方下的库位名)。 diff --git a/docs/developer_guide/add_device.md b/docs/developer_guide/add_device.md index a7495f3acf..842945fb42 100644 --- a/docs/developer_guide/add_device.md +++ b/docs/developer_guide/add_device.md @@ -339,7 +339,7 @@ async def async_operation(self, duration: float) -> Dict[str, Any]: 参数与返回值只有一个标准:注册表按方法签名生成 schema,调度端与 Host 调用前按它校验参数(没有默认值的参数必填, 缺了直接报错),调用后按返回注解校验返回值(注解 `-> bool` 却返回字典会按失败处理)。没写类型的参数接受任意值。 -物料托管、搬运、分装等资源语义写在 `@action(material=Material.xxx(...))` 一个字段里。完整规则、资源语义写法和 +物料托管、搬运、分装等资源语义写在 `@action(materials=Material.xxx(...))` 一个字段里(实验性:写了就按定义告警一次)。完整规则、资源语义写法和 已删除的旧写法见 [动作的参数、返回值与资源语义](action_standard.md)。 ### 超时:`timeout` 与 `execution_timeout` diff --git a/docs/developer_guide/v1_file_index/rest.md b/docs/developer_guide/v1_file_index/rest.md index 884ddf3623..ed1f80756e 100644 --- a/docs/developer_guide/v1_file_index/rest.md +++ b/docs/developer_guide/v1_file_index/rest.md @@ -119,9 +119,9 @@ | unilabos/registry/action_template_projection.py | 492 | PORTED | `registry/action_template_projection.py` | 逐字相同;`node_templates.py` 调它的 `compile_action_template_handles` | | unilabos/registry/annotation_rendering.py | 190 | PORTED | `registry/annotation_rendering.py` | 去掉 `SiteSelector(...)` 的回写(库位关系改为 `Material.site_picker`),其余相同 | | unilabos/registry/annotation_schema.py | 760 | PORTED | `registry/annotation_schema.py` | 逐字相同 | -| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(material=Material.site_picker(...))`,导入时报错并给出新写法),其余相同 | +| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(materials=Material.site_picker(...))`,导入时报错并给出新写法),其余相同 | | unilabos/registry/ast_registry_scanner.py | 1311 | PORTED | `registry/ast_registry_scanner.py`(文件级缓存、`_collect_literal_constants`、`available_sites` 常量解析) | 跟随装饰器差异:不再提取 `metadata`、`displayname`、`ExecutorKind`、`exception_handling`、`action_name`(见 decorators);与 V1 一样对每个 JSON 动作做 AST 解析(统一 schema 草稿,不认识的注解退回签名推断) | -| unilabos/registry/decorators.py | 882 | PARTIAL | `registry/decorators.py`(`device` / `action` / `resource` / `topic_config` / `always_free` / `not_action`) | V1 作者接口里有六个参数统一分支运行时装饰器不接受,驱动传了会在导入时 TypeError:`@action(action_name=…)`(对外动作名与方法名不同;AST 注册路径 `registry.py:1060` 却仍按它登记公开名、不记方法名,派发按公开名找方法,见 base_device_node 行)、`exception_handling=False`(异常不进人工决策)、`executor_kind`、`default_on_user_timeout`、`displayname`;`@device(metadata=…)`(供应商 / 规格等扩展元数据)。`legacy_action` / `contract=` 已删除(所有 JSON 动作同一标准,写了报错);资源语义用 `material=Material.xxx(...)`。`display_name` 只认新拼写是统一分支文档里的明确决定。统一分支另加了 `material`、`supported_backends`、`SiteSlot`;曾加的 `materials_need_lock` / `materials_free` 已按负责人 2026-11-17 决定移除(每个物料入参默认加共享资源锁),旧驱动传了照常加载、忽略并告警 | +| unilabos/registry/decorators.py | 882 | PARTIAL | `registry/decorators.py`(`device` / `action` / `resource` / `topic_config` / `always_free` / `not_action`) | V1 作者接口里有六个参数统一分支运行时装饰器不接受,驱动传了会在导入时 TypeError:`@action(action_name=…)`(对外动作名与方法名不同;AST 注册路径 `registry.py:1060` 却仍按它登记公开名、不记方法名,派发按公开名找方法,见 base_device_node 行)、`exception_handling=False`(异常不进人工决策)、`executor_kind`、`default_on_user_timeout`、`displayname`;`@device(metadata=…)`(供应商 / 规格等扩展元数据)。`legacy_action` / `contract=` 已删除(所有 JSON 动作同一标准,写了报错);资源语义用 `materials=Material.xxx(...)`。`display_name` 只认新拼写是统一分支文档里的明确决定。统一分支另加了 `materials`(实验性)、`supported_backends`、`SiteSlot`;曾加的 `materials_need_lock` / `materials_free` 已按负责人 2026-11-17 决定移除(每个物料入参默认加共享资源锁),旧驱动传了照常加载、忽略并告警 | | unilabos/registry/in_memory_template_projection_store.py | 348 | DROPPED | 第 4 条 | V1 给不开 SQLite 的纯 Authoring Web 进程用的进程内模板代际存储。统一分支只把模板投影写进 runtime.db(`services/runtime/workflow/node_templates.py`) | | unilabos/registry/init_enforce.py | 86 | PORTED | `registry/init_enforce.py` | 逐字相同 | | unilabos/registry/local_template_identity.py | 548 | PORTED | `resources/adapters/registry_materials.py:sync_registry_resources` / `register_resource_definitions`(启动时 `app/backend_main.py:158`、`server/startup.py:150`) | 注册表资源按 `definition_hash` 幂等同步成物料模板,UUID 稳定。没有 V1 的库位 `initial_material_template` 短名 → UUID 二次解析(见 site_definition) | diff --git a/docs/developer_guide/v1_inventory_preflight_contracts.md b/docs/developer_guide/v1_inventory_preflight_contracts.md index c3828d8a5f..38cdbd700a 100644 --- a/docs/developer_guide/v1_inventory_preflight_contracts.md +++ b/docs/developer_guide/v1_inventory_preflight_contracts.md @@ -122,7 +122,7 @@ JSON 值,解析器不认识的注解退回原来的签名推断,任何写法 ### 已知缺口 - 建任务时注册表里查不到该设备 / 动作(Host 尚未上报、设备未加载)就不冻结合同:建任务与派发都跳过参数校验和 - `order_sensitive` 检查;Host 调用前仍按自己当前的 Schema 校验,但声明了资源语义(`material=`)的动作会因计划里没有冻结的资源合同被拒绝。 + `order_sensitive` 检查;Host 调用前仍按自己当前的 Schema 校验,但声明了资源语义(`materials=`)的动作会因计划里没有冻结的资源合同被拒绝。 - 只在建任务、运行预检、派发与 Host 调用前校验参数;保存图、发布工作流、暂停期间改入口参数(`edit_input`)都不做参数校验,问题要到派发时才暴露。 - Host 按驱动**当前**的 Schema 校验输入与返回值,只要求资源合同与冻结值一致;建任务之后驱动改了参数或返回 Schema, 新 Schema 直接生效,不要求重建任务。 diff --git a/docs/developer_guide/workflow_resource_custody.md b/docs/developer_guide/workflow_resource_custody.md index 070bef75ba..5ef450a192 100644 --- a/docs/developer_guide/workflow_resource_custody.md +++ b/docs/developer_guide/workflow_resource_custody.md @@ -8,10 +8,10 @@ v1.0 的 `task_while_loaded` 表示样品装入后设备持续归该任务托管,成功卸载才释放。 任务停止、取消、超时、跳过、进程退出都不是卸载证据。 -在 `@action(material=...)` 声明参数名(写法对照见 [动作的参数、返回值与资源语义](action_standard.md)): +在 `@action(materials=...)` 声明参数名(写法对照见 [动作的参数、返回值与资源语义](action_standard.md)): ```python -@action(material=Material.load("sample", device="vessel")) +@action(materials=Material.load("sample", device="vessel")) def load_sample(self, sample: ResourceSlot, vessel: str) -> CustodyResult: ... ``` diff --git a/docs/developer_guide/workflow_static_conditions.md b/docs/developer_guide/workflow_static_conditions.md index 0d69482c5d..db7464cc93 100644 --- a/docs/developer_guide/workflow_static_conditions.md +++ b/docs/developer_guide/workflow_static_conditions.md @@ -336,7 +336,7 @@ def parallel_check(ctx): 计划的拓扑序先按它排);用同一台设备的成员因此按书写顺序依次执行。这只是同时就绪时的先后, 不是顺序保证:分支里前面有别的步骤、某个成员在等库存或另一项资源、失败重试时,后写的成员可能先做。 `parallel` 的意思是「顺序无所谓」,先后有影响就写成顺序执行。动作可以声明 -`@action(material=Material.order_sensitive())`(V1 同名合同 `order_sensitive`): +`@action(materials=Material.order_sensitive())`(V1 同名合同 `order_sensitive`): 同一资源上没有先后关系的两个兄弟动作只要有一方声明,就在发布和创建任务时被拒绝, 报错指出是哪两步,提示改成顺序执行或用依赖明确先后。这里的「同一资源」只有两类:动作节点自己的设备 (`execution_policy.always_free` 的动作不算),以及工作流 `meta_data.unilab.resource_scopes` 显式声明的资源作用域; From f8b01b04d503dc648298d3fe50cd6e9be07d6cbc Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:59:46 +0800 Subject: [PATCH 20/27] test(registry): expect AST scan cache version 29 --- tests/registry/test_backend_metadata.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/registry/test_backend_metadata.py b/tests/registry/test_backend_metadata.py index d6e43202bd..9e2cae5036 100644 --- a/tests/registry/test_backend_metadata.py +++ b/tests/registry/test_backend_metadata.py @@ -267,7 +267,7 @@ def test_ast_cache_rejects_previous_metadata_version(tmp_path) -> None: cache = load_scan_cache(cache_path) - assert _CACHE_VERSION == 28 + assert _CACHE_VERSION == 29 assert cache == {"version": _CACHE_VERSION, "files": {}} From 8d27a225e006f7e137f883993386aa828a31a0d6 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:59:47 +0800 Subject: [PATCH 21/27] test(e2e): pin LabDeviceComplexWorkflowDemo to its materials= main 996fc43 declares the reactor actions with @action(materials=). The commit has to be on the demo's origin before the pinned clone can fetch it. --- tests/e2e/readme_demos.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/readme_demos.py b/tests/e2e/readme_demos.py index 7f85e46137..8d8b550068 100644 --- a/tests/e2e/readme_demos.py +++ b/tests/e2e/readme_demos.py @@ -184,7 +184,7 @@ def runtime_timeout(self) -> float: DemoSpec( repo="LabDeviceComplexWorkflowDemo", url="https://github.com/Xuwznln/LabDeviceComplexWorkflowDemo", - ref="5516ff0242fe91db2bd9c475a0f4f6fdd1149b39", + ref="996fc439fb3bb3cae63f90fbb497eaa47cf461d5", package="complex_workflow_demo", host_graph="graph/complex_workflow_demo.json", # 循环容器:循环体节点每轮一个 attempt(trigger=loop_iteration),循环节点自身 1 个 attempt; From 544633f6b0ccfd5e5a835606f32068d2478c5741 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:18:06 +0800 Subject: [PATCH 22/27] feat(registry)!: name the experimental resource-semantics field material_contract= @action(material_contract=...) takes the same value as before (one Material.xxx(...) call or a list) and still warns once per definition as experimental. Both material= (on dev) and the short-lived materials= fail in the decorator and in the AST scan with a hint to material_contract=. The decorator imports the normalizing material_contract() under an alias so it does not shadow the parameter. AST scan cache version 30. --- .../registry/test_action_resource_contract.py | 45 +++++++++--------- tests/registry/test_backend_metadata.py | 2 +- tests/registry/test_site_selector_contract.py | 8 ++-- unilabos/registry/action_options.py | 28 ++++++----- unilabos/registry/action_schema.py | 2 +- unilabos/registry/ast_registry_scanner.py | 10 ++-- unilabos/registry/decorators.py | 40 ++++++++-------- unilabos/registry/material_roles.py | 46 +++++++++---------- unilabos/registry/site_selector_schema.py | 2 +- 9 files changed, 97 insertions(+), 86 deletions(-) diff --git a/tests/registry/test_action_resource_contract.py b/tests/registry/test_action_resource_contract.py index 966ad1b07f..6f6c2469ca 100644 --- a/tests/registry/test_action_resource_contract.py +++ b/tests/registry/test_action_resource_contract.py @@ -1,4 +1,4 @@ -"""动作资源语义:``@action(materials=Material.xxx(...))`` 从装饰器 / AST 到注册表 Schema 的行为合同。""" +"""动作资源语义:``@action(material_contract=Material.xxx(...))`` 从装饰器 / AST 到注册表 Schema 的行为合同。""" from __future__ import annotations @@ -33,7 +33,7 @@ class Result(TypedDict): @device(id="robot", category=["test"]) class Robot: - @action(materials={material}) + @action(material_contract={material}) def move({signature}) -> Result: """执行一次物料动作。""" raise NotImplementedError @@ -236,8 +236,8 @@ def test_slot_parameters_carry_their_kind_in_the_schema(tmp_path: Path) -> None: assert "x-unilabos-slot" not in goal["label"] -def test_materials_field_warns_experimental_once_per_definition(tmp_path: Path, caplog) -> None: - """整个 materials= 字段是实验性功能:写了就按定义告警一次(列出用到的声明),重复扫描不再告警。""" +def test_material_contract_field_warns_experimental_once_per_definition(tmp_path: Path, caplog) -> None: + """整个 material_contract= 字段是实验性功能:写了就按定义告警一次(列出用到的声明),重复扫描不再告警。""" caplog.set_level(logging.WARNING) material = '[Material.load("material", device="vessel_device"), Material.order_sensitive()]' @@ -245,7 +245,7 @@ def test_materials_field_warns_experimental_once_per_definition(tmp_path: Path, _scan_action(tmp_path, material) warnings = [record.getMessage() for record in caplog.records if "实验性功能" in record.getMessage()] assert len(warnings) == 1 - assert "materials= 是实验性功能" in warnings[0] + assert "material_contract= 是实验性功能" in warnings[0] assert "Material.load" in warnings[0] and "Material.order_sensitive" in warnings[0] @@ -261,7 +261,7 @@ def test_material_actions_alone_also_warn_experimental(tmp_path: Path, caplog) - warnings = [record.getMessage() for record in caplog.records if "实验性功能" in record.getMessage()] assert len(warnings) == 1 assert "move_only_experimental.Robot.move" in warnings[0] - assert "materials= 是实验性功能(Material.move)" in warnings[0] + assert "material_contract= 是实验性功能(Material.move)" in warnings[0] def test_experimental_warning_from_the_decorator(caplog) -> None: @@ -270,38 +270,41 @@ def test_experimental_warning_from_the_decorator(caplog) -> None: caplog.set_level(logging.WARNING) class Driver: - @action(materials=Material.in_place("sample")) + @action(material_contract=Material.in_place("sample")) def stir_experimental(self, sample: ResourceSlot) -> None: pass - @action(materials=Material.move("plate", to_site="target_site")) + @action(material_contract=Material.move("plate", to_site="target_site")) def move_experimental(self, plate: ResourceSlot, target_site: SiteSlot) -> None: pass messages = [record.getMessage() for record in caplog.records] - assert any("materials= 是实验性功能(Material.in_place)" in message for message in messages) - assert any("move_experimental" in message and "materials= 是实验性功能(Material.move)" in message for message in messages) + assert any("material_contract= 是实验性功能(Material.in_place)" in message for message in messages) + assert any("move_experimental" in message and "material_contract= 是实验性功能(Material.move)" in message for message in messages) -def test_old_material_field_name_fails_with_the_new_name(tmp_path: Path) -> None: - """改名前的 material= 在装饰器与 AST 扫描里都直接报错,提示改成 materials=(值不变)。""" +@pytest.mark.parametrize("old_name", ["material", "materials"]) +def test_old_field_names_fail_with_the_new_name(tmp_path: Path, old_name: str) -> None: + """dev 上的旧名 material= 与短暂出现过的 materials= 在装饰器与 AST 扫描里都直接报错(不会被静默忽略), + 提示改成 material_contract=(值不变)。""" - source = ''' + source = f''' from unilabos.registry.decorators import Material, action, device from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot -@device(id="old_material_field", category=["test"]) +@device(id="old_{old_name}_field", category=["test"]) class Driver: - @action(material=Material.move("plate", to_site="target_site")) + @action({old_name}=Material.move("plate", to_site="target_site")) def run(self, plate: ResourceSlot, target_site: SiteSlot) -> None: pass ''' - path = tmp_path / "old_material_field.py" + path = tmp_path / f"old_{old_name}_field.py" path.write_text(source, encoding="utf-8") - with pytest.raises(RemovedActionOptionError, match="material=.*字段改名为 materials="): + hint = f"不再接受 {old_name}=.*字段改名为 material_contract=" + with pytest.raises(RemovedActionOptionError, match=hint): _parse_file(path, tmp_path) - with pytest.raises(RemovedActionOptionError, match="material=.*字段改名为 materials="): - _import(tmp_path, source, name="old_material_field_runtime") + with pytest.raises(RemovedActionOptionError, match=hint): + _import(tmp_path, source, name=f"old_{old_name}_field_runtime") @pytest.mark.parametrize( @@ -337,5 +340,5 @@ def send(self, cmd: str) -> None: pass assert send._action_registry_meta["goal"] == {"command": "cmd"} - with pytest.raises(ValueError, match="materials= 只用于 JSON 动作"): - action(action_type="unilabos_msgs.action:SendCmd", materials=Material.in_place("cmd"))(send) + with pytest.raises(ValueError, match="material_contract= 只用于 JSON 动作"): + action(action_type="unilabos_msgs.action:SendCmd", material_contract=Material.in_place("cmd"))(send) diff --git a/tests/registry/test_backend_metadata.py b/tests/registry/test_backend_metadata.py index 9e2cae5036..77bb93a808 100644 --- a/tests/registry/test_backend_metadata.py +++ b/tests/registry/test_backend_metadata.py @@ -267,7 +267,7 @@ def test_ast_cache_rejects_previous_metadata_version(tmp_path) -> None: cache = load_scan_cache(cache_path) - assert _CACHE_VERSION == 29 + assert _CACHE_VERSION == 30 assert cache == {"version": _CACHE_VERSION, "files": {}} diff --git a/tests/registry/test_site_selector_contract.py b/tests/registry/test_site_selector_contract.py index ffaeb73315..bbedb7ccdf 100644 --- a/tests/registry/test_site_selector_contract.py +++ b/tests/registry/test_site_selector_contract.py @@ -1,4 +1,4 @@ -"""库位参数(``SiteSlot``)与物料参数的关系:``@action(materials=Material.site_picker(...))``。 +"""库位参数(``SiteSlot``)与物料参数的关系:``@action(material_contract=Material.site_picker(...))``。 ``SiteSelector`` 已与 ``SiteSlot`` 合一:库位参数只有一个类型 ``SiteSlot``,库位属于哪个物料参数、放进去的是 哪个物料参数、已占用库位的显示 / 可选策略写在 ``Material.site_picker``。生成的 ``x-unilabos-site-selector`` 扩展与 @@ -50,7 +50,7 @@ def _source(material: str, signature: str, *, header: str = "") -> str: @device(id="site_driver", category=["test"]) class Driver: - @action(materials={material}) + @action(material_contract={material}) def action(self, {signature}) -> None: pass ''' @@ -105,7 +105,7 @@ def test_action_site_parameter_compiles_complete_relation_metadata(tmp_path: Pat def test_decorator_records_the_same_relation(tmp_path: Path) -> None: from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot - @action(materials=Material.site_picker("site", of="warehouse")) + @action(material_contract=Material.site_picker("site", of="warehouse")) def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass @@ -114,7 +114,7 @@ def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: } with pytest.raises(MaterialRoleError, match="missing"): - @action(materials=Material.site_picker("site", of="missing")) + @action(material_contract=Material.site_picker("site", of="missing")) def bad(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass diff --git a/unilabos/registry/action_options.py b/unilabos/registry/action_options.py index c63ee15c87..3a1fa852ad 100644 --- a/unilabos/registry/action_options.py +++ b/unilabos/registry/action_options.py @@ -3,13 +3,14 @@ 这些写法不再接受,写了就报错并指出新写法(见 ``docs/developer_guide/action_standard.md`` 的「不兼容变更」): - ``contract=``:所有 JSON 动作统一按签名生成并校验 schema,没有 opt-in 开关; -- ``resource_contract={...}``:资源语义改用 ``materials=Material.xxx(...)``; -- ``material=``:字段改名为 ``materials=``,值不变(一条 ``Material.xxx(...)`` 或它们组成的列表); +- ``resource_contract={...}``:资源语义改用 ``material_contract=Material.xxx(...)``; +- ``material=``(以及短暂出现过的 ``materials=``):字段改名为 ``material_contract=``,值不变 + (一条 ``Material.xxx(...)`` 或它们组成的列表); - JSON 动作的 ``goal=`` / ``result=`` 重命名:字段名就是参数名 / 返回 TypedDict 的字段名 (ROS 动作类型的 ``goal`` / ``result`` 字段映射照旧); - 参数注解里的 ``Placeholder(...)``:前端选择器写在 ``@action(placeholder_keys={...})``; - 参数注解里的 ``SiteSelector(...)``:库位参数注解为 ``SiteSlot``,库位选择器提示写成 - ``materials=Material.site_picker(...)``; + ``material_contract=Material.site_picker(...)``; - 按名字注入的动作上下文(参数叫 ``action_context`` 却没有 ``ActionContext`` 注解):框架按类型注入, 注解为 ``Optional[ActionContext]``(见 :mod:`unilabos.registry.action_context`)。 @@ -23,18 +24,23 @@ from unilabos.registry.action_context import LEGACY_ACTION_CONTEXT_NAME, untyped_action_context_message +#: 资源语义字段改名的提示:``material=``(dev 上的旧名)与 ``materials=``(短暂出现过)都改成 ``material_contract=``。 +_MATERIAL_CONTRACT_RENAME = ( + "字段改名为 material_contract=,值不变:写成 material_contract=Material.xxx(...)" + "(多条照旧写成列表);material_contract= 是实验性功能" +) + #: 任何动作都不再接受的选项 → 新写法。 REMOVED_ACTION_OPTIONS: Dict[str, str] = { "contract": "所有 JSON 动作统一按签名生成并校验 schema,去掉 contract= 即可", "resource_contract": ( - "资源语义改用 materials=Material.xxx(...),例如 materials=Material.move(\"plate\", to_site=\"target_site\")、" - "materials=Material.dispense(from_material=\"source\", to_materials=[\"target\"])、" - "materials=[Material.in_place(\"sample\"), Material.order_sensitive()]" - ), - "material": ( - "字段改名为 materials=,值不变:把 material=Material.xxx(...) 写成 materials=Material.xxx(...)" - "(多条照旧写成列表);materials= 是实验性功能" + "资源语义改用 material_contract=Material.xxx(...),例如 " + "material_contract=Material.move(\"plate\", to_site=\"target_site\")、" + "material_contract=Material.dispense(from_material=\"source\", to_materials=[\"target\"])、" + "material_contract=[Material.in_place(\"sample\"), Material.order_sensitive()]" ), + "material": _MATERIAL_CONTRACT_RENAME, + "materials": _MATERIAL_CONTRACT_RENAME, } #: 只对 JSON 动作(没写 action_type)删除的选项 → 新写法。 REMOVED_JSON_ACTION_OPTIONS: Dict[str, str] = { @@ -49,7 +55,7 @@ "参数类型照常写,去掉 Annotated[..., Placeholder(...)] 外壳" ), "SiteSelector": ( - "库位参数注解为 SiteSlot,库位选择器提示写成 @action(materials=Material.site_picker(\"库位参数\", " + "库位参数注解为 SiteSlot,库位选择器提示写成 @action(material_contract=Material.site_picker(\"库位参数\", " "of=\"拥有库位的物料或设备参数\", for_material=\"放进去的物料参数\", occupied=\"show\"))" ), } diff --git a/unilabos/registry/action_schema.py b/unilabos/registry/action_schema.py index 947852b108..2d6d1efbda 100644 --- a/unilabos/registry/action_schema.py +++ b/unilabos/registry/action_schema.py @@ -5,7 +5,7 @@ - 严格解析器认识的注解(``str`` / ``int`` / ``float`` / ``bool``、``Literal``、``Optional`` 与 ``X | None``、``ResourceSlot`` / ``list[ResourceSlot]``、``list[X]``、``dict[str, JSONValue]``,以及 ``Annotated[..., Field(...)]`` / ``AllowedResourceTemplates``):严格 schema; -- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(materials=Material.site_picker(...))`` 声明的 +- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(material_contract=Material.site_picker(...))`` 声明的 库位关系写进该 ``SiteSlot`` 参数的 ``x-unilabos-site-selector`` 扩展(前端库位选择器、预检与派发门禁用); - 没写注解、``Any``、``object``:接受任意 JSON 值(``{}``); - 默认值是 ``None`` 的参数按可空处理(``x: str = None`` 与 ``x: Optional[str] = None`` 相同); diff --git a/unilabos/registry/ast_registry_scanner.py b/unilabos/registry/ast_registry_scanner.py index de1d90fe03..8b8d207d0c 100644 --- a/unilabos/registry/ast_registry_scanner.py +++ b/unilabos/registry/ast_registry_scanner.py @@ -62,7 +62,7 @@ MAX_SCAN_DEPTH = 10 # 最大目录递归深度 MAX_SCAN_FILES = 1000 # 最大扫描文件数量 -_CACHE_VERSION = 29 # 29:@action(material=) 改名为 materials=(旧名报错);整个字段告警「实验性功能」 +_CACHE_VERSION = 30 # 30:@action 资源语义字段改名为 material_contract=(material= / materials= 报错);整个字段告警「实验性功能」 # 允许点号分段(如 liquid_handler.prcxi),与内置 YAML 注册表的命名先例一致; # 点号只用于注册表模板名,设备实例 id(图节点)另有约束。 _DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$") @@ -1093,7 +1093,7 @@ def _extract_class_body( for name in REMOVED_MATERIAL_LOCK_OPTIONS: action_args.pop(name, None) json_action = not action_args.get("action_type") - # 已删除的写法(contract= / resource_contract= / 改名前的 material= / JSON 动作的 goal= 与 result=, + # 已删除的写法(contract= / resource_contract= / 改名前的 material= 与 materials= / JSON 动作的 goal= 与 result=, # 以及注解里的 Placeholder / SiteSelector)与装饰器同一套报错:整个文件记为扫描错误,错误信息指出新写法。 check_action_options(action_args, json_action=json_action, definition=definition) # 框架注入的参数(sample_uuids、按类型识别的 ActionContext)不属于动作接口; @@ -1109,10 +1109,10 @@ def _extract_class_body( draft: Dict[str, Any] = {} resource_contract: Dict[str, Any] = {} site_selectors: Dict[str, Any] = {} - material_value = action_args.pop("materials", None) + material_value = action_args.pop("material_contract", None) if material_value is not None: if not json_action: - raise ValueError(f"{definition}:materials= 只用于 JSON 动作(不写 action_type)") + raise ValueError(f"{definition}:material_contract= 只用于 JSON 动作(不写 action_type)") roles = material_roles_from_ast(material_value) resource_contract = material_contract(roles) site_selectors = material_site_selectors(roles) @@ -1127,7 +1127,7 @@ def _extract_class_body( ) canonical_schema = draft["schema"] if material_value is not None: - # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;materials= 是实验性功能,告警一次 + # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;material_contract= 是实验性功能,告警一次 goal_fields = canonical_schema["properties"]["goal"]["properties"] check_material_parameter_types( roles, diff --git a/unilabos/registry/decorators.py b/unilabos/registry/decorators.py index cd2dbf4888..3bfda08a0e 100644 --- a/unilabos/registry/decorators.py +++ b/unilabos/registry/decorators.py @@ -41,7 +41,7 @@ def set_valve_position(self, position): ... # 资源语义(实验性):一个字段,Material 的一条或多条 - @action(materials=Material.in_place("vessel")) + @action(material_contract=Material.in_place("vessel")) def flush(self, vessel: ResourceSlot) -> None: ... @@ -280,7 +280,7 @@ def _slot_kind_of_annotation(annotation: Any) -> str: def _runtime_slot_kinds(func: Callable[..., Any], parameters: Any) -> Dict[str, str]: - """签名里每个参数(不含 self / cls / 可变参数)的槽位类型;用于对照 ``materials=`` 引用的参数。""" + """签名里每个参数(不含 self / cls / 可变参数)的槽位类型;用于对照 ``material_contract=`` 引用的参数。""" import inspect import typing @@ -475,7 +475,7 @@ def action( execution_timeout: Optional[Union[float, str]] = None, estimate_duration_fixed: Any = _ESTIMATE_UNSET, estimate_duration_express: str = "", - materials: Any = None, + material_contract: Any = None, **removed_options: Any, ): """ @@ -517,11 +517,11 @@ def AddProtocol(self): ... parent: 若为 True,当方法参数为空 (*args, **kwargs) 时,通过 MRO 从父类获取真实方法参数 node_type: 动作的节点类型 (NodeType.ILAB / NodeType.MANUAL_CONFIRM)。 不填写时不写入注册表。 - materials: (实验性)动作的资源语义:物料动作 ``Material.move / pick / place / dispense``,以及 - ``Material.load / unload / in_place / site_picker / order_sensitive``,一条或多条组成的列表 - (见 ``unilabos.registry.material_roles``)。字符串都是参数名,注册时对照签名检查 - (物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot);写了就按定义告警一次「实验性功能」。 - 旧字段名 ``material=`` 直接报错并提示改成 ``materials=``。 + material_contract: (实验性)动作的资源语义:物料动作 ``Material.move / pick / place / dispense``,以及 + ``Material.load / unload / in_place / site_picker / order_sensitive``,一条或多条组成的列表 + (见 ``unilabos.registry.material_roles``)。字符串都是参数名,注册时对照签名检查 + (物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot);写了就按定义告警一次「实验性功能」。 + 旧字段名 ``material=``(以及短暂出现过的 ``materials=``)直接报错并提示改成 ``material_contract=``。 error_policy: 按异常类名匹配审批选项的策略。结构见 unilabos.registry.action_policy.ErrorPolicy。 timeout: 硬超时(秒,正数)。到期后执行面协作式取消动作,并以 @@ -537,7 +537,7 @@ def AddProtocol(self): ... 同一语法("cycles * 2",也认 V1 的 "{cycles} * 2");派发时 按真实 action_args 求值,失败时退回兜底。 详见 unilabos.registry.action_duration。 - removed_options: 已删除的 ``contract`` / ``resource_contract`` / ``material`` 直接报错并指出新写法 + removed_options: 已删除的 ``contract`` / ``resource_contract`` / ``material`` / ``materials`` 直接报错并指出新写法 (``unilabos.registry.action_options``)。已移除的 ``materials_need_lock`` / ``materials_free`` 照常加载:值被忽略,按定义告警一次。物料锁不再按动作改写: 每个物料入参(ResourceSlot / List[ResourceSlot],或 placeholder_keys 标为 @@ -562,13 +562,15 @@ def decorator(func: F) -> F: ) resource_contract: Dict[str, Any] = {} site_selectors: Dict[str, Any] = {} - if materials is not None: - from unilabos.registry.material_roles import material_contract, material_site_selectors + if material_contract is not None: + # 别名导入:同名的规范化函数不能遮住 material_contract= 参数 + from unilabos.registry.material_roles import material_contract as normalize_material_contract + from unilabos.registry.material_roles import material_site_selectors if not json_action: - raise ValueError(f"{definition}:materials= 只用于 JSON 动作(不写 action_type)") - resource_contract = material_contract(materials) - site_selectors = material_site_selectors(materials) + raise ValueError(f"{definition}:material_contract= 只用于 JSON 动作(不写 action_type)") + resource_contract = normalize_material_contract(material_contract) + site_selectors = material_site_selectors(material_contract) if _inspect.iscoroutinefunction(func): @wraps(func) @@ -619,15 +621,15 @@ def wrapper(*args, **kwargs): unknown = [name for name in dict.fromkeys(referenced) if name not in signature_parameters] if unknown: raise MaterialRoleError( - f"{func.__qualname__} 的 materials= 引用了签名里没有的参数:{'、'.join(unknown)}" + f"{func.__qualname__} 的 material_contract= 引用了签名里没有的参数:{'、'.join(unknown)}" ) - if materials is not None: - # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;materials= 是实验性功能,按定义告警一次 + if material_contract is not None: + # 字符串参数对照签名:物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot;material_contract= 是实验性功能,按定义告警一次 from unilabos.registry.material_roles import check_material_parameter_types, warn_experimental slots = _runtime_slot_kinds(func, signature_parameters) - check_material_parameter_types(materials, slots.get, definition=definition) - warn_experimental(materials, definition) + check_material_parameter_types(material_contract, slots.get, definition=definition) + warn_experimental(material_contract, definition) if resource_contract: meta["resource_contract"] = resource_contract if site_selectors: diff --git a/unilabos/registry/material_roles.py b/unilabos/registry/material_roles.py index 8d291f8db2..ef9257cf17 100644 --- a/unilabos/registry/material_roles.py +++ b/unilabos/registry/material_roles.py @@ -1,25 +1,25 @@ -"""动作的资源语义:``@action(materials=...)`` 唯一的写法(实验性)。 +"""动作的资源语义:``@action(material_contract=...)`` 唯一的写法(实验性)。 -``materials=`` 的值是 ``Material`` 的一个方法调用,或多个调用组成的列表: +``material_contract=`` 的值是 ``Material`` 的一个方法调用,或多个调用组成的列表: from unilabos.registry.decorators import action, Material - @action(materials=Material.move("plate", to_site="target_site")) + @action(material_contract=Material.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... - @action(materials=Material.dispense(from_material="source", to_materials=["target"])) + @action(material_contract=Material.dispense(from_material="source", to_materials=["target"])) def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... 物料动作:``move`` / ``pick`` / ``place`` / ``dispense``。不代表物料动作的声明:``load`` / ``unload`` 跨动作 设备独占、``in_place`` 原位检查、``site_picker`` 库位选择器提示、``order_sensitive`` 顺序约束。整个 -``materials=`` 字段都是实验性功能:写了就按定义告警一次,语义与写法以后可能调整。 +``material_contract=`` 字段都是实验性功能:写了就按定义告警一次,语义与写法以后可能调整。 字符串参数都是动作的参数名,注册时对照签名检查:物料是 ``ResourceSlot``,库位是 ``SiteSlot``(库位 uuid), 设备是 ``DeviceSlot``(省略即执行设备)。内部规范化成第 2 版资源合同 (``x-unilabos-action-contract.resource_contract``),调度器照旧按合同执行;``site_picker`` 不进资源合同, 写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展。 -旧写法(字段名 ``material=``,``transfer`` / ``aliquot`` / ``site`` / ``uses``,带 ``owner`` / ``site`` / +旧写法(字段名 ``material=`` / ``materials=``,``transfer`` / ``aliquot`` / ``site`` / ``uses``,带 ``owner`` / ``site`` / ``carriers`` 的 ``pick`` / ``place``)直接报错并给出新写法。 本模块只依赖标准库与纯声明的合同规范化:装饰器(导入期)与 AST 扫描(不导入作者模块)共用。 @@ -59,7 +59,7 @@ def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> class MaterialRoleError(ValueError): - """``materials=`` 写法不对:注册失败并指出正确写法。""" + """``material_contract=`` 写法不对:注册失败并指出正确写法。""" def _names(value: Union[str, Sequence[str], None], label: str) -> List[str]: @@ -197,7 +197,7 @@ def parameter_types(self) -> List[Tuple[str, str, str]]: class Material: - """资源语义的唯一入口:每个方法返回一条语义,``@action(materials=...)`` 接收一条或一个列表(实验性)。""" + """资源语义的唯一入口:每个方法返回一条语义,``@action(material_contract=...)`` 接收一条或一个列表(实验性)。""" # ------------------------------------------------------------------ 物料动作 @@ -392,26 +392,26 @@ def _roles(value: Any) -> List[MaterialRole]: roles = list(value) if isinstance(value, (list, tuple)) else [value] for role in roles: if not isinstance(role, MaterialRole): - raise MaterialRoleError("materials= 只接受 Material.xxx(...) 或它们组成的列表") + raise MaterialRoleError("material_contract= 只接受 Material.xxx(...) 或它们组成的列表") if not roles: - raise MaterialRoleError("materials= 至少写一条 Material.xxx(...)") + raise MaterialRoleError("material_contract= 至少写一条 Material.xxx(...)") return roles def material_roles(value: Any) -> List[MaterialRole]: - """``materials=`` 的值(一条语义或列表)→ 语义列表;``None`` 为空列表。""" + """``material_contract=`` 的值(一条语义或列表)→ 语义列表;``None`` 为空列表。""" return [] if value is None else _roles(value) def material_kinds(value: Any) -> List[str]: - """``materials=`` 里用到的声明种类(按出现顺序去重)。""" + """``material_contract=`` 里用到的声明种类(按出现顺序去重)。""" return list(dict.fromkeys(role.kind for role in material_roles(value))) def warn_experimental(value: Any, definition: str) -> None: - """注册时按定义告警一次:整个 ``materials=`` 字段是实验性功能(装饰器与 AST 扫描共用同一身份)。""" + """注册时按定义告警一次:整个 ``material_contract=`` 字段是实验性功能(装饰器与 AST 扫描共用同一身份)。""" kinds = material_kinds(value) if not kinds: @@ -420,13 +420,13 @@ def warn_experimental(value: Any, definition: str) -> None: warn_once( definition, - "materials= 是实验性功能(" + "、".join(f"Material.{kind}" for kind in kinds) + "material_contract= 是实验性功能(" + "、".join(f"Material.{kind}" for kind in kinds) + "):语义与写法以后可能调整", ) def material_contract(value: Any) -> Dict[str, Any]: - """``materials=`` 的值(一条语义或列表)→ 规范化的第 2 版资源合同;``None`` 或只有 ``site_picker`` 时返回空字典。""" + """``material_contract=`` 的值(一条语义或列表)→ 规范化的第 2 版资源合同;``None`` 或只有 ``site_picker`` 时返回空字典。""" if value is None: return {} @@ -448,11 +448,11 @@ def material_contract(value: Any) -> Dict[str, Any]: try: return normalize_action_resource_contract(raw) except ActionResourceContractError as error: - raise MaterialRoleError(f"materials= 写法无效:{error.message}") from None + raise MaterialRoleError(f"material_contract= 写法无效:{error.message}") from None def material_site_selectors(value: Any) -> Dict[str, Dict[str, Any]]: - """``materials=`` 里的 ``Material.site_picker(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" + """``material_contract=`` 里的 ``Material.site_picker(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" if value is None: return {} @@ -468,7 +468,7 @@ def material_site_selectors(value: Any) -> Dict[str, Dict[str, Any]]: def material_parameter_types(value: Any) -> List[Tuple[str, str, str]]: - """``materials=`` 引用的全部参数与要求的类型(见 :meth:`MaterialRole.parameter_types`)。""" + """``material_contract=`` 引用的全部参数与要求的类型(见 :meth:`MaterialRole.parameter_types`)。""" items: List[Tuple[str, str, str]] = [] for role in material_roles(value): @@ -477,7 +477,7 @@ def material_parameter_types(value: Any) -> List[Tuple[str, str, str]]: def check_material_parameter_types(value: Any, slot_of, *, definition: str) -> None: - """对照签名检查 ``materials=`` 引用的参数存在且类型正确。 + """对照签名检查 ``material_contract=`` 引用的参数存在且类型正确。 ``slot_of(name)`` 返回参数的槽位类型:``"resource"``(单个 ``ResourceSlot``)、``"resource_list"``、 ``"site"``、``"device"``、``"device_list"``、``""``(其他类型);参数不存在返回 ``None``。 @@ -550,20 +550,20 @@ def add(value: Any) -> None: def material_roles_from_ast(value: Any) -> List[MaterialRole]: - """AST 扫描提取的 ``materials=`` 值(``{"_call": ..., "_pos_0": ...}`` 或其列表)→ 语义列表。""" + """AST 扫描提取的 ``material_contract=`` 值(``{"_call": ..., "_pos_0": ...}`` 或其列表)→ 语义列表。""" items = value if isinstance(value, list) else [value] roles: List[MaterialRole] = [] for item in items: if not isinstance(item, Mapping) or "_call" not in item: - raise MaterialRoleError("materials= 只接受 Material.xxx(...) 或它们组成的列表(参数须是字面量)") + raise MaterialRoleError("material_contract= 只接受 Material.xxx(...) 或它们组成的列表(参数须是字面量)") call = str(item["_call"]) prefix, _, method = call.rpartition(".") module, _, owner = prefix.rpartition(":") if owner != "Material" and prefix != "Material": - raise MaterialRoleError(f"materials= 只接受 Material.xxx(...),不认识 {call}") + raise MaterialRoleError(f"material_contract= 只接受 Material.xxx(...),不认识 {call}") if module and module not in _MATERIAL_MODULES: - raise MaterialRoleError(f"materials= 的 Material 必须从 unilabos.registry.decorators 导入,不认识 {call}") + raise MaterialRoleError(f"material_contract= 的 Material 必须从 unilabos.registry.decorators 导入,不认识 {call}") factory = getattr(Material, method, None) if not method.startswith("_") else None if factory is None: raise MaterialRoleError(f"Material 没有 {method}(...)") diff --git a/unilabos/registry/site_selector_schema.py b/unilabos/registry/site_selector_schema.py index 1634db231e..7abb5a9e56 100644 --- a/unilabos/registry/site_selector_schema.py +++ b/unilabos/registry/site_selector_schema.py @@ -1,6 +1,6 @@ """库位关系(``Material.site_picker(...)``)的静态跨字段校验。 -库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(materials=Material.site_picker(...))``:库位属于 +库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(material_contract=Material.site_picker(...))``:库位属于 哪个物料参数(``owner``)、放进去的是哪个物料参数(``occupant``)、已占用库位的显示 / 可选策略。注册表 把它写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展;本模块在生成 schema 时核对关系指向的参数。 """ From 4f80ce23447d2e140e90ff3edafdaf91030618a1 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:18:44 +0800 Subject: [PATCH 23/27] docs: describe the experimental @action(material_contract=) field The guides, skills and AGENTS.md use material_contract=. The breaking-changes row for material= now points at material_contract=; the short-lived materials= is mentioned as rejected but has no row of its own. --- .cursor/skills/add-device/SKILL.md | 6 ++-- .cursor/skills/create-device-package/SKILL.md | 14 ++++---- AGENTS.md | 2 +- docs/developer_guide/action_standard.md | 33 ++++++++++--------- docs/developer_guide/add_device.md | 2 +- docs/developer_guide/v1_file_index/rest.md | 4 +-- .../v1_inventory_preflight_contracts.md | 2 +- .../workflow_resource_custody.md | 4 +-- .../workflow_static_conditions.md | 2 +- 9 files changed, 35 insertions(+), 34 deletions(-) diff --git a/.cursor/skills/add-device/SKILL.md b/.cursor/skills/add-device/SKILL.md index 02f7213842..7bb71f10ed 100644 --- a/.cursor/skills/add-device/SKILL.md +++ b/.cursor/skills/add-device/SKILL.md @@ -159,13 +159,13 @@ from unilabos.registry.decorators import action auto_prefix=True, # 强制使用 auto- 前缀 parent=True, # 从父类 MRO 获取参数签名 ) -@action(materials=Material.move("plate", to_site="target_site")) # 资源语义(实验性):一个字段,见下 +@action(material_contract=Material.move("plate", to_site="target_site")) # 资源语义(实验性):一个字段,见下 ``` JSON 动作(不写 `action_type`)的参数与返回值只有一个标准:注册表按签名生成 schema,调度端与 Host 调用前按它校验参数, 调用后按返回注解校验返回值。写了类型的参数严格校验;没写类型或 `Any` 接受任意 JSON 值;没有默认值的参数必填。 -资源语义用 `materials=`,声明动作真实的物料动作 `Material.move / pick / place / dispense(...)`,多个写成列表; -不代表物料动作的 `Material.load / unload / in_place / site_picker / order_sensitive(...)` 也写在这里。整个 `materials=` 字段是实验性功能 +资源语义用 `material_contract=`,声明动作真实的物料动作 `Material.move / pick / place / dispense(...)`,多个写成列表; +不代表物料动作的 `Material.load / unload / in_place / site_picker / order_sensitive(...)` 也写在这里。整个 `material_contract=` 字段是实验性功能 (写了就按定义告警一次);改名前的 `material=` 注册时报错。 字符串都是参数名:物料 `ResourceSlot`、库位 `SiteSlot`(库位 uuid,所属方由库位决定)、设备 `DeviceSlot`(省略即执行设备)。 库位选择器列出哪个所属方的库位写 `Material.site_picker("site", of="carrier", for_material="sample")`。 diff --git a/.cursor/skills/create-device-package/SKILL.md b/.cursor/skills/create-device-package/SKILL.md index 78166a9d8a..4e80cacce6 100644 --- a/.cursor/skills/create-device-package/SKILL.md +++ b/.cursor/skills/create-device-package/SKILL.md @@ -117,12 +117,12 @@ class : - `always_free=True`:动作不占用设备 busy 队列,适合 `get_status`、`query_*`、`ping`、连接测试等轻量查询动作;会在 `action_value_mappings..always_free` 中写入 `true`。 - `feedback_interval`:动作反馈发布间隔,单位秒;AST 扫描默认补 `1.0`,长任务可调大,例如 `5.0`、`30.0`。 - `goal_default`:编辑器里的初始参数值,叠加在签名默认值上;它不让参数变成可选,没有签名默认值的参数仍然必填。 -- `materials`(实验性,写了就按定义告警一次):资源语义(搬运、两步搬运、分装;以及装载托管、原位处理、库位选择器提示、顺序敏感),一个字段,值是 `Material` 的一个方法或列表,见下文「资源语义」。 +- `material_contract`(实验性,写了就按定义告警一次):资源语义(搬运、两步搬运、分装;以及装载托管、原位处理、库位选择器提示、顺序敏感),一个字段,值是 `Material` 的一个方法或列表,见下文「资源语义」。 - `placeholder_keys`:前端选择器 `{参数名: PLACEHOLDER_...}`。物料 `ResourceSlot`、设备 `DeviceSlot`、库位 `SiteSlot` 由类型自动推出; 节点、人工确认指派人、扣减等没有专门类型的选择器,或想把某个参数换一种显示,就在这里手写。两者取并集,同一参数以手写为准; 只改前端显示,参数类型与校验不变(兼容规则:手写成 `unilabos_resources` 的参数也加物料锁)。键必须是参数名。 - `handles`:动作级输入/输出端口,使用 `ActionInputHandle`、`ActionOutputHandle`;不写时按 schema 生成。 -- 已删除、写了会报错的写法:`contract=`、`resource_contract=`、改名前的 `material=`(改成 `materials=`,值不变)、JSON 动作的 `goal=` / `result=` 重命名(参数名就是字段名), +- 已删除、写了会报错的写法:`contract=`、`resource_contract=`、改名前的 `material=`(改成 `material_contract=`,值不变)、JSON 动作的 `goal=` / `result=` 重命名(参数名就是字段名), 注解里的 `Placeholder(...)`(改成 `placeholder_keys=`)与 `SiteSelector(...)`(改成 `SiteSlot` + `Material.site_picker(...)`), 以及 `Material.transfer / aliquot / site / uses`、带 `owner` / `site` / `carriers` 的 `Material.pick / place`(新写法见下文「资源语义」)。 @@ -144,22 +144,22 @@ class : 旧的 `@always_free` 仍可被 AST 扫描识别,但新设备包优先使用 `@action(always_free=True)`,把动作元数据集中在一个装饰器里。 -#### 资源语义:`materials=`(实验性) +#### 资源语义:`material_contract=`(实验性) ```python from unilabos.registry.decorators import Material, action from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="搬运板", materials=Material.move("plate", to_site="target_site")) +@action(display_name="搬运板", material_contract=Material.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="抓取", materials=Material.pick("plate")) +@action(display_name="抓取", material_contract=Material.pick("plate")) def pick_plate(self, plate: ResourceSlot) -> dict: ... -@action(display_name="放下", materials=Material.place("plate", to_site="target_site")) +@action(display_name="放下", material_contract=Material.place("plate", to_site="target_site")) def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="原位搅拌", materials=[Material.in_place("sample"), Material.order_sensitive()]) +@action(display_name="原位搅拌", material_contract=[Material.in_place("sample"), Material.order_sensitive()]) def stir(self, sample: ResourceSlot, rpm: int = 300) -> None: ... ``` diff --git a/AGENTS.md b/AGENTS.md index 4a15670713..46f4340d1f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ pytest tests/resources/test_resourcetreeset_groups.py::test_name # single test ### Core Layers -**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one experimental decorator field, `@action(materials=Material.move(...) | [...])` (`registry/material_roles.py`; any use warns once per definition, the old field name `material=` is rejected with the new spelling): the material actions are `Material.move` / `pick` / `place` / `dispense` (sites are `SiteSlot` uuids whose owner the scheduler derives from the site, carriers are `DeviceSlot` parameters defaulting to the executing device and its `gripper` site); `load` / `unload` / `in_place` / `site_picker` / `order_sensitive` are the declarations that are not material actions. A site parameter is annotated `SiteSlot`; `Material.site_picker(...)` writes the selector hint into that field's `x-unilabos-site-selector` extension. `Material.transfer` / `aliquot` / `site` / `uses` and `pick` / `place` with `owner` / `site` / `carriers` are rejected with the new spelling. Parameters are locked by type: `ResourceSlot` material locks, `DeviceSlot` device locks, `SiteSlot` site locks. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, the old `material=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. +**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one experimental decorator field, `@action(material_contract=Material.move(...) | [...])` (`registry/material_roles.py`; any use warns once per definition; the old field name `material=` and the short-lived `materials=` are rejected with the new spelling): the material actions are `Material.move` / `pick` / `place` / `dispense` (sites are `SiteSlot` uuids whose owner the scheduler derives from the site, carriers are `DeviceSlot` parameters defaulting to the executing device and its `gripper` site); `load` / `unload` / `in_place` / `site_picker` / `order_sensitive` are the declarations that are not material actions. A site parameter is annotated `SiteSlot`; `Material.site_picker(...)` writes the selector hint into that field's `x-unilabos-site-selector` extension. `Material.transfer` / `aliquot` / `site` / `uses` and `pick` / `place` with `owner` / `site` / `carriers` are rejected with the new spelling. Parameters are locked by type: `ResourceSlot` material locks, `DeviceSlot` device locks, `SiteSlot` site locks. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, the old `material=` / `materials=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. **Resource Tracking** (`unilabos/resources/resource_tracker.py`): Pydantic-based `ResourceDict` → `ResourceDictInstance` → `ResourceTreeSet` hierarchy. `ResourceTreeSet` is the canonical in-memory representation of all devices and resources, used throughout the system, and it owns every resource conversion: flat dicts (`from_raw_dict_list`, `dump`/`load`) and PLR (`from_plr_resources`, `to_plr_resources`). PLR drafts from a registry resource class come from `resources/materials.py:instantiate_registry_resource`. There is no separate graph I/O module: device graphs are node-link JSON only (GraphML is not supported) and are turned into runtime structures by the Graph Authority (`server/services/materials/graph.py:load_graph_payload`). diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 0ed8f8c3b1..ff0836562d 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -17,7 +17,7 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) | `Annotated[X, Field(ge=, le=, min_length=, max_length=, title=, description=)]` | 带范围与说明 | 严格 | | `ResourceSlot` / `list[ResourceSlot]` | 物料引用 `{"uuid": ...}`(或按库位绑定的 `{"site_uuid": ...}`,准入时解析),加物料锁 | 严格;Host 解析成物料实例 | | `DeviceSlot` / `SiteSlot` | 设备 ID / 库位 UUID 字符串(字段带 `x-unilabos-slot: "device"` / `"site"`),加设备锁 / 库位锁 | 严格 | -| `SiteSlot` 且写了 `materials=Material.site_picker("site", of=...)` | 库位 UUID、所属方下的库位名(工作流里写死的工位,派发前解析成库位 uuid),或按所属物料选择的 `{"owner_uuid": ...}`(准入时选定);带库位关系(`x-unilabos-site-selector`),不限定 uuid 格式 | 严格;预检与派发前核对库位归属与占用 | +| `SiteSlot` 且写了 `material_contract=Material.site_picker("site", of=...)` | 库位 UUID、所属方下的库位名(工作流里写死的工位,派发前解析成库位 uuid),或按所属物料选择的 `{"owner_uuid": ...}`(准入时选定);带库位关系(`x-unilabos-site-selector`),不限定 uuid 格式 | 严格;预检与派发前核对库位归属与占用 | | `dict`、`Dict[str, Any]`、`Mapping` | 任意 JSON 对象 | 只校验是对象 | | 没写注解、`Any`、`object` | 任意 JSON 值(`{}`) | 不限值 | | 严格解析器不认识的注解(`Union[int, str]`、`List[Optional[float]]`、枚举、PLR / pydantic 类型……) | 退回注册表原来的签名类型推断 | 按推断结果;推断不出的部分接受任意值 | @@ -93,14 +93,15 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 手写 YAML 注册表里的 JSON 动作要跑一次 `unilab --complete_registry`,才会按同一标准重新生成 schema; 没有这个扩展的 schema(ROS 动作类型,或还没补全的手写 YAML)不做上面的校验。 -## 资源语义:`materials=`(实验性) +## 资源语义:`material_contract=`(实验性) -**整个 `materials=` 字段都是实验性功能**:写了就在注册时按定义告警一次「materials= 是实验性功能(用到的声明):语义与写法 -以后可能调整」,装饰器(导入时)与注册表 AST 扫描共用同一身份,同一定义只告警一次。 +**整个 `material_contract=` 字段都是实验性功能**:写了就在注册时按定义告警一次「material_contract= 是实验性功能(用到的声明):语义与写法 +以后可能调整」,装饰器(导入时)与注册表 AST 扫描共用同一身份,同一定义只告警一次。改名前的 `material=`(见「不兼容变更」) +与短暂出现过的 `materials=` 注册时都直接报错并提示改成 `material_contract=`,不会被静默忽略。 `Material` 声明的是动作**真实的物料动作**:搬运一件容器、两步搬运、在容器之间转移内容物。调度器在派发前按它解析 来源、目标与搬运设备,动作成功后由核心一次结算物料位置 / 内容物(`PhysicalMove` / 搬运回执、`AliquotReceipt`)。 -不代表物料动作的声明(跨动作的设备独占、原位检查、库位选择器提示、顺序约束)也写在 `materials=` 里。 +不代表物料动作的声明(跨动作的设备独占、原位检查、库位选择器提示、顺序约束)也写在 `material_contract=` 里。 一个动作的语义只用 `@action` 的这一个字段声明,值是 `Material` 的一个方法调用,多个语义写成列表。 字符串参数都是动作的参数名,注册时对照签名检查参数存在、类型正确: @@ -115,16 +116,16 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 from unilabos.registry.decorators import Material, action from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="搬运板", materials=Material.move("plate", to_site="target_site")) +@action(display_name="搬运板", material_contract=Material.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="抓取", materials=Material.pick("plate")) +@action(display_name="抓取", material_contract=Material.pick("plate")) def pick_plate(self, plate: ResourceSlot) -> dict: ... -@action(display_name="放下", materials=Material.place("plate", to_site="target_site")) +@action(display_name="放下", material_contract=Material.place("plate", to_site="target_site")) def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="移液", materials=Material.dispense(from_material="source", to_materials=["target"])) +@action(display_name="移液", material_contract=Material.dispense(from_material="source", to_materials=["target"])) def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... ``` @@ -159,7 +160,7 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl | | 声明式 `Material`(`registry/material_roles.py`) | 运行时 `materials`(`unilabos.resources.materials`) | | --- | --- | --- | -| 写在哪里 | `@action(materials=...)` | 驱动代码里,动作执行时调用 | +| 写在哪里 | `@action(material_contract=...)` | 驱动代码里,动作执行时调用 | | 谁读 / 谁执行 | 调度器派发前读:解析来源、目标、搬运设备,加锁、预留库位;动作成功后**核心**结算 | 驱动直接调用,立即改权威 | | 典型操作 | `move` / `pick` / `place`(`PhysicalMove` / 搬运回执)、`dispense`(`AliquotReceipt`) | `create` / `ensure` / `get` / `search` / `resolve` / `assign` / `update` / `remove` / `snapshot` / `transfer` / `apply_substances` …… | @@ -176,7 +177,7 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl ### 不代表物料动作的声明 -同样写在 `materials=` 里(与整个字段一样是实验性功能)。 +同样写在 `material_contract=` 里(与整个字段一样是实验性功能)。 | 写法 | 含义 | 内部合同字段 | | --- | --- | --- | @@ -213,7 +214,7 @@ from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot @action( display_name="放到库位", - materials=Material.site_picker("site", of="carrier", for_material="sample", occupied="show"), + material_contract=Material.site_picker("site", of="carrier", for_material="sample", occupied="show"), ) def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = None) -> None: ... ``` @@ -305,10 +306,10 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | 删除的写法 | 新写法 | | --- | --- | | `@action(contract="typed")` / `contract="legacy"` | 去掉:所有 JSON 动作同一标准 | -| `@action(resource_contract={...})` | `@action(materials=Material.xxx(...))`,对照表见上 | -| `@action(material=Material.xxx(...))` / `material=[...]`(字段改名前的写法) | `@action(materials=Material.xxx(...))` / `materials=[...]`:只改字段名,值不变;`materials=` 是实验性功能,写了就按定义告警一次 | +| `@action(resource_contract={...})` | `@action(material_contract=Material.xxx(...))`,对照表见上 | +| `@action(material=Material.xxx(...))` / `material=[...]`(字段改名前的写法) | `@action(material_contract=Material.xxx(...))` / `material_contract=[...]`:只改字段名,值不变;`material_contract=` 是实验性功能,写了就按定义告警一次 | | `Annotated[T, Placeholder(PLACEHOLDER_...)]`(`unilabos.registry.annotations.Placeholder`) | `@action(placeholder_keys={"参数名": PLACEHOLDER_...})`,参数照常注解为 `T` | -| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(materials=Material.site_picker("参数名", of=..., for_material=..., occupied=...))`;生成的 schema 扩展与以前相同 | +| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(material_contract=Material.site_picker("参数名", of=..., for_material=..., occupied=...))`;生成的 schema 扩展与以前相同 | | JSON 动作的 `@action(goal={...})` / `result={...}` 重命名 | 去掉:字段名就是参数名 / 返回 TypedDict 的字段名(要改名就改参数名) | | 按名字注入的动作上下文:参数叫 `action_context` 但没有 `ActionContext` 注解 | 注解为 `Optional[ActionContext]`(`from unilabos.client.host.runtime.action import ActionContext`),名字随意;没有注解的 `action_context` 参数注册时报错(自动动作同样) | @@ -327,7 +328,7 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | `Material.uses(device=[...], tool=[...], motion=[...], site=[...], material=[...])` | 删除:参数按类型加锁(`ResourceSlot` 物料锁、`DeviceSlot` 设备锁、`SiteSlot` 库位锁),把参数注解成对应类型即可 | | `Material.load("sample", device="vessel")`(`vessel` 是 `str` / `ResourceSlot`) | `vessel` 注解为 `DeviceSlot`;装进执行设备本身时省略 `device=` | -行为上的变化:`DeviceSlot` / `SiteSlot` 参数现在默认加设备锁 / 库位锁;字段改名为 `materials=`,整个字段(包括 +行为上的变化:`DeviceSlot` / `SiteSlot` 参数现在默认加设备锁 / 库位锁;字段改名为 `material_contract=`,整个字段(包括 `move` / `pick` / `place` / `dispense`)注册时按定义告警一次「实验性功能」;搬运设备的夹爪库位角色统一为 `gripper`,已部署的物料权威里旧角色名 (如 `robot.gripper`)不会随设备声明自动更新,需要重建或改写这些库位的 `meta_data.role`;声明的搬运在动作成功后可以不交 搬运回执(核心按冻结计划结算);`site_picker` 的库位参数不再限定 uuid 格式(也可以给所属方下的库位名)。 diff --git a/docs/developer_guide/add_device.md b/docs/developer_guide/add_device.md index 842945fb42..f86a5f1c67 100644 --- a/docs/developer_guide/add_device.md +++ b/docs/developer_guide/add_device.md @@ -339,7 +339,7 @@ async def async_operation(self, duration: float) -> Dict[str, Any]: 参数与返回值只有一个标准:注册表按方法签名生成 schema,调度端与 Host 调用前按它校验参数(没有默认值的参数必填, 缺了直接报错),调用后按返回注解校验返回值(注解 `-> bool` 却返回字典会按失败处理)。没写类型的参数接受任意值。 -物料托管、搬运、分装等资源语义写在 `@action(materials=Material.xxx(...))` 一个字段里(实验性:写了就按定义告警一次)。完整规则、资源语义写法和 +物料托管、搬运、分装等资源语义写在 `@action(material_contract=Material.xxx(...))` 一个字段里(实验性:写了就按定义告警一次)。完整规则、资源语义写法和 已删除的旧写法见 [动作的参数、返回值与资源语义](action_standard.md)。 ### 超时:`timeout` 与 `execution_timeout` diff --git a/docs/developer_guide/v1_file_index/rest.md b/docs/developer_guide/v1_file_index/rest.md index ed1f80756e..4039a74773 100644 --- a/docs/developer_guide/v1_file_index/rest.md +++ b/docs/developer_guide/v1_file_index/rest.md @@ -119,9 +119,9 @@ | unilabos/registry/action_template_projection.py | 492 | PORTED | `registry/action_template_projection.py` | 逐字相同;`node_templates.py` 调它的 `compile_action_template_handles` | | unilabos/registry/annotation_rendering.py | 190 | PORTED | `registry/annotation_rendering.py` | 去掉 `SiteSelector(...)` 的回写(库位关系改为 `Material.site_picker`),其余相同 | | unilabos/registry/annotation_schema.py | 760 | PORTED | `registry/annotation_schema.py` | 逐字相同 | -| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(materials=Material.site_picker(...))`,导入时报错并给出新写法),其余相同 | +| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(material_contract=Material.site_picker(...))`,导入时报错并给出新写法),其余相同 | | unilabos/registry/ast_registry_scanner.py | 1311 | PORTED | `registry/ast_registry_scanner.py`(文件级缓存、`_collect_literal_constants`、`available_sites` 常量解析) | 跟随装饰器差异:不再提取 `metadata`、`displayname`、`ExecutorKind`、`exception_handling`、`action_name`(见 decorators);与 V1 一样对每个 JSON 动作做 AST 解析(统一 schema 草稿,不认识的注解退回签名推断) | -| unilabos/registry/decorators.py | 882 | PARTIAL | `registry/decorators.py`(`device` / `action` / `resource` / `topic_config` / `always_free` / `not_action`) | V1 作者接口里有六个参数统一分支运行时装饰器不接受,驱动传了会在导入时 TypeError:`@action(action_name=…)`(对外动作名与方法名不同;AST 注册路径 `registry.py:1060` 却仍按它登记公开名、不记方法名,派发按公开名找方法,见 base_device_node 行)、`exception_handling=False`(异常不进人工决策)、`executor_kind`、`default_on_user_timeout`、`displayname`;`@device(metadata=…)`(供应商 / 规格等扩展元数据)。`legacy_action` / `contract=` 已删除(所有 JSON 动作同一标准,写了报错);资源语义用 `materials=Material.xxx(...)`。`display_name` 只认新拼写是统一分支文档里的明确决定。统一分支另加了 `materials`(实验性)、`supported_backends`、`SiteSlot`;曾加的 `materials_need_lock` / `materials_free` 已按负责人 2026-11-17 决定移除(每个物料入参默认加共享资源锁),旧驱动传了照常加载、忽略并告警 | +| unilabos/registry/decorators.py | 882 | PARTIAL | `registry/decorators.py`(`device` / `action` / `resource` / `topic_config` / `always_free` / `not_action`) | V1 作者接口里有六个参数统一分支运行时装饰器不接受,驱动传了会在导入时 TypeError:`@action(action_name=…)`(对外动作名与方法名不同;AST 注册路径 `registry.py:1060` 却仍按它登记公开名、不记方法名,派发按公开名找方法,见 base_device_node 行)、`exception_handling=False`(异常不进人工决策)、`executor_kind`、`default_on_user_timeout`、`displayname`;`@device(metadata=…)`(供应商 / 规格等扩展元数据)。`legacy_action` / `contract=` 已删除(所有 JSON 动作同一标准,写了报错);资源语义用 `material_contract=Material.xxx(...)`。`display_name` 只认新拼写是统一分支文档里的明确决定。统一分支另加了 `material_contract`(实验性)、`supported_backends`、`SiteSlot`;曾加的 `materials_need_lock` / `materials_free` 已按负责人 2026-11-17 决定移除(每个物料入参默认加共享资源锁),旧驱动传了照常加载、忽略并告警 | | unilabos/registry/in_memory_template_projection_store.py | 348 | DROPPED | 第 4 条 | V1 给不开 SQLite 的纯 Authoring Web 进程用的进程内模板代际存储。统一分支只把模板投影写进 runtime.db(`services/runtime/workflow/node_templates.py`) | | unilabos/registry/init_enforce.py | 86 | PORTED | `registry/init_enforce.py` | 逐字相同 | | unilabos/registry/local_template_identity.py | 548 | PORTED | `resources/adapters/registry_materials.py:sync_registry_resources` / `register_resource_definitions`(启动时 `app/backend_main.py:158`、`server/startup.py:150`) | 注册表资源按 `definition_hash` 幂等同步成物料模板,UUID 稳定。没有 V1 的库位 `initial_material_template` 短名 → UUID 二次解析(见 site_definition) | diff --git a/docs/developer_guide/v1_inventory_preflight_contracts.md b/docs/developer_guide/v1_inventory_preflight_contracts.md index 38cdbd700a..c0f5d9026b 100644 --- a/docs/developer_guide/v1_inventory_preflight_contracts.md +++ b/docs/developer_guide/v1_inventory_preflight_contracts.md @@ -122,7 +122,7 @@ JSON 值,解析器不认识的注解退回原来的签名推断,任何写法 ### 已知缺口 - 建任务时注册表里查不到该设备 / 动作(Host 尚未上报、设备未加载)就不冻结合同:建任务与派发都跳过参数校验和 - `order_sensitive` 检查;Host 调用前仍按自己当前的 Schema 校验,但声明了资源语义(`materials=`)的动作会因计划里没有冻结的资源合同被拒绝。 + `order_sensitive` 检查;Host 调用前仍按自己当前的 Schema 校验,但声明了资源语义(`material_contract=`)的动作会因计划里没有冻结的资源合同被拒绝。 - 只在建任务、运行预检、派发与 Host 调用前校验参数;保存图、发布工作流、暂停期间改入口参数(`edit_input`)都不做参数校验,问题要到派发时才暴露。 - Host 按驱动**当前**的 Schema 校验输入与返回值,只要求资源合同与冻结值一致;建任务之后驱动改了参数或返回 Schema, 新 Schema 直接生效,不要求重建任务。 diff --git a/docs/developer_guide/workflow_resource_custody.md b/docs/developer_guide/workflow_resource_custody.md index 5ef450a192..5eef7d19dd 100644 --- a/docs/developer_guide/workflow_resource_custody.md +++ b/docs/developer_guide/workflow_resource_custody.md @@ -8,10 +8,10 @@ v1.0 的 `task_while_loaded` 表示样品装入后设备持续归该任务托管,成功卸载才释放。 任务停止、取消、超时、跳过、进程退出都不是卸载证据。 -在 `@action(materials=...)` 声明参数名(写法对照见 [动作的参数、返回值与资源语义](action_standard.md)): +在 `@action(material_contract=...)` 声明参数名(写法对照见 [动作的参数、返回值与资源语义](action_standard.md)): ```python -@action(materials=Material.load("sample", device="vessel")) +@action(material_contract=Material.load("sample", device="vessel")) def load_sample(self, sample: ResourceSlot, vessel: str) -> CustodyResult: ... ``` diff --git a/docs/developer_guide/workflow_static_conditions.md b/docs/developer_guide/workflow_static_conditions.md index db7464cc93..1809db22b9 100644 --- a/docs/developer_guide/workflow_static_conditions.md +++ b/docs/developer_guide/workflow_static_conditions.md @@ -336,7 +336,7 @@ def parallel_check(ctx): 计划的拓扑序先按它排);用同一台设备的成员因此按书写顺序依次执行。这只是同时就绪时的先后, 不是顺序保证:分支里前面有别的步骤、某个成员在等库存或另一项资源、失败重试时,后写的成员可能先做。 `parallel` 的意思是「顺序无所谓」,先后有影响就写成顺序执行。动作可以声明 -`@action(materials=Material.order_sensitive())`(V1 同名合同 `order_sensitive`): +`@action(material_contract=Material.order_sensitive())`(V1 同名合同 `order_sensitive`): 同一资源上没有先后关系的两个兄弟动作只要有一方声明,就在发布和创建任务时被拒绝, 报错指出是哪两步,提示改成顺序执行或用依赖明确先后。这里的「同一资源」只有两类:动作节点自己的设备 (`execution_policy.always_free` 的动作不算),以及工作流 `meta_data.unilab.resource_scopes` 显式声明的资源作用域; From 3aeca29dd08a824e3af5479340a28d19d007ce5c Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:19:18 +0800 Subject: [PATCH 24/27] test(e2e): pin LabDeviceComplexWorkflowDemo to its material_contract= main d25221c declares the reactor actions with @action(material_contract=). The commit has to be on the demo's origin before the pinned clone can fetch it. --- tests/e2e/readme_demos.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/readme_demos.py b/tests/e2e/readme_demos.py index 8d8b550068..fc32f81f2e 100644 --- a/tests/e2e/readme_demos.py +++ b/tests/e2e/readme_demos.py @@ -184,7 +184,7 @@ def runtime_timeout(self) -> float: DemoSpec( repo="LabDeviceComplexWorkflowDemo", url="https://github.com/Xuwznln/LabDeviceComplexWorkflowDemo", - ref="996fc439fb3bb3cae63f90fbb497eaa47cf461d5", + ref="d25221c1e11104581dc323bd677bed99ca855c9f", package="complex_workflow_demo", host_graph="graph/complex_workflow_demo.json", # 循环容器:循环体节点每轮一个 attempt(trigger=loop_iteration),循环节点自身 1 个 attempt; From 3156de2359db3138074b14ca3ca79e923fa53be8 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:08:54 +0800 Subject: [PATCH 25/27] feat(registry)!: declare resource semantics with MaterialRole.xxx(...) The factory methods move / pick / place / dispense / load / unload / in_place / site_picker / order_sensitive now live on the frozen MaterialRole dataclass they return, so there is one public name, easy to tell apart from the runtime unilabos.resources.materials module. Material (on dev since #372) stays importable from unilabos.registry.decorators and material_roles only as a stub: any Material.xxx(...) fails at import time, and the AST scan rejects it, both with a hint to MaterialRole.xxx(...). The AST scan only calls the declaration factories, never instance methods or fields. Messages say MaterialRole. AST scan cache version 31. --- .../registry/test_action_resource_contract.py | 159 +++++++++++------ tests/registry/test_backend_metadata.py | 2 +- tests/registry/test_site_selector_contract.py | 54 +++--- tests/server/test_material_actions.py | 38 ++-- tests/server/test_site_selection_by_owner.py | 2 +- unilabos/protocol/runtime/site_references.py | 2 +- unilabos/registry/action_options.py | 18 +- unilabos/registry/action_resource_contract.py | 2 +- unilabos/registry/action_schema.py | 12 +- unilabos/registry/ast_registry_scanner.py | 2 +- unilabos/registry/decorators.py | 13 +- unilabos/registry/material_roles.py | 164 +++++++++++------- unilabos/registry/site_selector_schema.py | 10 +- .../registry/site_selector_value_schema.py | 2 +- unilabos/server/api/envelope.py | 2 +- .../server/scheduler/physical_contract.py | 12 +- .../server/scheduler/physical_recovery.py | 4 +- unilabos/server/scheduler/tenancy_contract.py | 6 +- .../runtime/workflow/run_preflight.py | 2 +- .../services/runtime/workflow/service.py | 2 +- .../runtime/workflow/site_selections.py | 8 +- 21 files changed, 299 insertions(+), 217 deletions(-) diff --git a/tests/registry/test_action_resource_contract.py b/tests/registry/test_action_resource_contract.py index 6f6c2469ca..9ca2fe5ded 100644 --- a/tests/registry/test_action_resource_contract.py +++ b/tests/registry/test_action_resource_contract.py @@ -1,4 +1,4 @@ -"""动作资源语义:``@action(material_contract=Material.xxx(...))`` 从装饰器 / AST 到注册表 Schema 的行为合同。""" +"""动作资源语义:``@action(material_contract=MaterialRole.xxx(...))`` 从装饰器 / AST 到注册表 Schema 的行为合同。""" from __future__ import annotations @@ -12,7 +12,7 @@ from unilabos.registry.action_options import RemovedActionOptionError from unilabos.registry.action_resource_contract import EXECUTING_DEVICE from unilabos.registry.ast_registry_scanner import _parse_file -from unilabos.registry.decorators import Material, action +from unilabos.registry.decorators import MaterialRole, action from unilabos.registry.material_roles import MaterialRoleError, material_contract, material_site_selectors _SIGNATURE = ( @@ -25,7 +25,7 @@ def _source(material: str, *, signature: str | None = None) -> str: signature = signature or _SIGNATURE return f''' from typing import TypedDict -from unilabos.registry.decorators import Material, action, device +from unilabos.registry.decorators import MaterialRole, action, device from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot class Result(TypedDict): @@ -67,9 +67,9 @@ def _contract(entry: dict) -> dict: def test_move_freezes_into_the_transfer_contract_with_site_derived_owner(tmp_path: Path) -> None: - """Material.move:所属方由库位决定(不写所属物料参数),搬运设备省略即执行设备。""" + """MaterialRole.move:所属方由库位决定(不写所属物料参数),搬运设备省略即执行设备。""" - contract = _contract(_scan_action(tmp_path, 'Material.move("material", to_site="target_site")')) + contract = _contract(_scan_action(tmp_path, 'MaterialRole.move("material", to_site="target_site")')) assert contract == { "version": 2, "transfer": { @@ -84,14 +84,14 @@ def test_move_freezes_into_the_transfer_contract_with_site_derived_owner(tmp_pat }, } explicit = _contract(_scan_action( - tmp_path, 'Material.move("material", to_site="target_site", from_site="source_site", carrier_device="arm_device")' + tmp_path, 'MaterialRole.move("material", to_site="target_site", from_site="source_site", carrier_device="arm_device")' )) assert explicit["transfer"]["source_site_uuid_param"] == "source_site" assert explicit["transfer"]["carrier_device_param"] == "arm_device" def test_decorator_and_ast_scan_produce_the_same_contract(tmp_path: Path) -> None: - material = '[Material.pick("material", from_site="source_site", carrier_device="arm_device")]' + material = '[MaterialRole.pick("material", from_site="source_site", carrier_device="arm_device")]' scanned = _contract(_scan_action(tmp_path, material)) module = _import(tmp_path, _source(material)) assert module.Robot.move._action_registry_meta["resource_contract"] == scanned @@ -105,45 +105,45 @@ def test_decorator_and_ast_scan_produce_the_same_contract(tmp_path: Path) -> Non ("role", "expected"), [ ( - Material.load("s"), + MaterialRole.load("s"), {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", "acquire_device_param": EXECUTING_DEVICE, "release_device_param": ""}}, ), ( - Material.load("s", device="b", from_device="a"), + MaterialRole.load("s", device="b", from_device="a"), {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", "acquire_device_param": "b", "release_device_param": "a"}}, ), ( - Material.unload("s", device="v"), + MaterialRole.unload("s", device="v"), {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", "acquire_device_param": "", "release_device_param": "v"}}, ), ( - Material.unload("s"), + MaterialRole.unload("s"), {"device_tenancy": {"mode": "task_while_loaded", "material_param": "s", "acquire_device_param": "", "release_device_param": EXECUTING_DEVICE}}, ), - (Material.in_place("s"), {"operate_in_place": {"material_param": "s"}}), + (MaterialRole.in_place("s"), {"operate_in_place": {"material_param": "s"}}), ( - Material.pick("s"), + MaterialRole.pick("s"), {"transfer_step": {"operation": "pick", "material_param": "s", "owner_param": "", "site_param": "", "carrier_params": []}}, ), ( - Material.place("s", to_site="t", carrier_device="c"), + MaterialRole.place("s", to_site="t", carrier_device="c"), {"transfer_step": {"operation": "place", "material_param": "s", "owner_param": "", "site_param": "t", "carrier_params": ["c"]}}, ), ( - Material.dispense(from_material="a", to_materials=["b", "c"]), + MaterialRole.dispense(from_material="a", to_materials=["b", "c"]), {"aliquot": {"source_material_param": "a", "target_material_params": ["b", "c"]}}, ), ( - Material.dispense(from_material="a", to_materials="b"), + MaterialRole.dispense(from_material="a", to_materials="b"), {"aliquot": {"source_material_param": "a", "target_material_params": ["b"]}}, ), - (Material.order_sensitive(), {"order_sensitive": True}), + (MaterialRole.order_sensitive(), {"order_sensitive": True}), ], ) def test_every_role_maps_to_the_existing_contract_field(role, expected) -> None: @@ -151,39 +151,39 @@ def test_every_role_maps_to_the_existing_contract_field(role, expected) -> None: def test_site_picker_keeps_the_site_selector_shape() -> None: - assert material_site_selectors(Material.site_picker("site", of="carrier", for_material="s")) == { + assert material_site_selectors(MaterialRole.site_picker("site", of="carrier", for_material="s")) == { "site": {"version": 1, "owner": "carrier", "occupant": "s", "show_occupied": True, "allow_occupied": False} } - assert material_site_selectors(Material.site_picker("site", occupied="hide"))["site"] == { + assert material_site_selectors(MaterialRole.site_picker("site", occupied="hide"))["site"] == { "version": 1, "owner": None, "occupant": None, "show_occupied": False, "allow_occupied": False, } - assert material_site_selectors(Material.site_picker("site", of="o", occupied="allow"))["site"]["allow_occupied"] + assert material_site_selectors(MaterialRole.site_picker("site", of="o", occupied="allow"))["site"]["allow_occupied"] with pytest.raises(MaterialRoleError, match="hide"): - Material.site_picker("site", occupied="never") + MaterialRole.site_picker("site", occupied="never") def test_conflicting_or_invalid_roles_are_rejected() -> None: with pytest.raises(MaterialRoleError, match="不能写在同一个动作上"): - material_contract([Material.load("s", device="a"), Material.unload("s", device="b")]) + material_contract([MaterialRole.load("s", device="a"), MaterialRole.unload("s", device="b")]) with pytest.raises(MaterialRoleError, match="不能写在同一个动作上"): - material_contract([Material.move("s", to_site="t"), Material.pick("s")]) + material_contract([MaterialRole.move("s", to_site="t"), MaterialRole.pick("s")]) with pytest.raises(MaterialRoleError): material_contract({"device_tenancy": {}}) with pytest.raises(MaterialRoleError, match="不能是同一个参数"): - Material.load("s", device="v", from_device="v") + MaterialRole.load("s", device="v", from_device="v") with pytest.raises(MaterialRoleError, match="不同的参数"): - Material.dispense(from_material="a", to_materials=["a"]) + MaterialRole.dispense(from_material="a", to_materials=["a"]) @pytest.mark.parametrize( ("call", "hint"), [ - ('Material.transfer("material", to="other", site="target_site", gripper="robot.gripper")', "Material.move"), - ('Material.aliquot(source="material", targets=["other"])', "Material.dispense"), - ('Material.site("target_site", owner="other", occupant="material")', "Material.site_picker"), - ('Material.uses(device=["arm_device"])', "按类型加锁"), - ('Material.pick("material", owner="other", site="source_site", carriers=["other"])', "carrier_device"), - ('Material.place("material", owner="other", site="target_site", carriers=["other"])', "to_site"), + ('MaterialRole.transfer("material", to="other", site="target_site", gripper="robot.gripper")', "MaterialRole.move"), + ('MaterialRole.aliquot(source="material", targets=["other"])', "MaterialRole.dispense"), + ('MaterialRole.site("target_site", owner="other", occupant="material")', "MaterialRole.site_picker"), + ('MaterialRole.uses(device=["arm_device"])', "按类型加锁"), + ('MaterialRole.pick("material", owner="other", site="source_site", carriers=["other"])', "carrier_device"), + ('MaterialRole.place("material", owner="other", site="target_site", carriers=["other"])', "to_site"), ], ) def test_legacy_spellings_fail_in_the_decorator_and_in_the_scan(tmp_path: Path, call: str, hint: str) -> None: @@ -198,14 +198,14 @@ def test_legacy_spellings_fail_in_the_decorator_and_in_the_scan(tmp_path: Path, @pytest.mark.parametrize( ("call", "hint"), [ - ('Material.move("material", to_site="label")', "必须注解为 SiteSlot"), - ('Material.move("material", to_site="target_site", carrier_device="other")', "必须注解为 DeviceSlot"), - ('Material.pick("label")', "必须注解为单个 ResourceSlot"), - ('Material.load("material", device="other")', "必须注解为 DeviceSlot"), - ('Material.site_picker("label")', "SiteSlot"), - ('Material.site_picker("target_site", of="label")', "ResourceSlot 或 DeviceSlot"), - ('Material.dispense(from_material="material", to_materials=["arm_device"])', "必须注解为单个 ResourceSlot"), - ('Material.in_place("missing")', "签名里没有的参数.*missing"), + ('MaterialRole.move("material", to_site="label")', "必须注解为 SiteSlot"), + ('MaterialRole.move("material", to_site="target_site", carrier_device="other")', "必须注解为 DeviceSlot"), + ('MaterialRole.pick("label")', "必须注解为单个 ResourceSlot"), + ('MaterialRole.load("material", device="other")', "必须注解为 DeviceSlot"), + ('MaterialRole.site_picker("label")', "SiteSlot"), + ('MaterialRole.site_picker("target_site", of="label")', "ResourceSlot 或 DeviceSlot"), + ('MaterialRole.dispense(from_material="material", to_materials=["arm_device"])', "必须注解为单个 ResourceSlot"), + ('MaterialRole.in_place("missing")', "签名里没有的参数.*missing"), ], ) def test_parameter_types_are_checked_against_the_signature(tmp_path: Path, call: str, hint: str) -> None: @@ -218,11 +218,11 @@ def test_parameter_types_are_checked_against_the_signature(tmp_path: Path, call: def test_device_owner_and_omitted_owner_are_accepted_by_the_site_picker(tmp_path: Path) -> None: - entry = _scan_action(tmp_path, '[Material.site_picker("target_site", of="arm_device", for_material="material")]') + entry = _scan_action(tmp_path, '[MaterialRole.site_picker("target_site", of="arm_device", for_material="material")]') field = entry["canonical_schema"]["properties"]["goal"]["properties"]["target_site"] assert field["x-unilabos-site-selector"]["owner"] == "arm_device" assert field["x-unilabos-editor-control"] == "site_selector" - entry = _scan_action(tmp_path, '[Material.site_picker("target_site", occupied="allow")]') + entry = _scan_action(tmp_path, '[MaterialRole.site_picker("target_site", occupied="allow")]') selector = entry["canonical_schema"]["properties"]["goal"]["properties"]["target_site"]["x-unilabos-site-selector"] assert selector == {"version": 1, "owner": None, "occupant": None, "show_occupied": True, "allow_occupied": True} @@ -230,7 +230,7 @@ def test_device_owner_and_omitted_owner_are_accepted_by_the_site_picker(tmp_path def test_slot_parameters_carry_their_kind_in_the_schema(tmp_path: Path) -> None: """DeviceSlot / SiteSlot 字段带 x-unilabos-slot:调度器按它给设备 / 库位加锁。""" - goal = _scan_action(tmp_path, 'Material.pick("material")')["canonical_schema"]["properties"]["goal"]["properties"] + goal = _scan_action(tmp_path, 'MaterialRole.pick("material")')["canonical_schema"]["properties"]["goal"]["properties"] assert goal["arm_device"]["x-unilabos-slot"] == "device" assert goal["target_site"]["x-unilabos-slot"] == "site" assert "x-unilabos-slot" not in goal["label"] @@ -240,28 +240,28 @@ def test_material_contract_field_warns_experimental_once_per_definition(tmp_path """整个 material_contract= 字段是实验性功能:写了就按定义告警一次(列出用到的声明),重复扫描不再告警。""" caplog.set_level(logging.WARNING) - material = '[Material.load("material", device="vessel_device"), Material.order_sensitive()]' + material = '[MaterialRole.load("material", device="vessel_device"), MaterialRole.order_sensitive()]' _scan_action(tmp_path, material) _scan_action(tmp_path, material) warnings = [record.getMessage() for record in caplog.records if "实验性功能" in record.getMessage()] assert len(warnings) == 1 assert "material_contract= 是实验性功能" in warnings[0] - assert "Material.load" in warnings[0] and "Material.order_sensitive" in warnings[0] + assert "MaterialRole.load" in warnings[0] and "MaterialRole.order_sensitive" in warnings[0] def test_material_actions_alone_also_warn_experimental(tmp_path: Path, caplog) -> None: - """move / pick / place / dispense 不再单独算稳定:只写一条 Material.move 也告警一次。""" + """move / pick / place / dispense 不再单独算稳定:只写一条 MaterialRole.move 也告警一次。""" caplog.set_level(logging.WARNING) # 独立的模块名:告警按「定义 + 原因」进程内去重,不能与其他用例扫描过的 robot.Robot.move 同一身份 path = tmp_path / "move_only_experimental.py" - path.write_text(_source('Material.move("material", to_site="target_site")'), encoding="utf-8") + path.write_text(_source('MaterialRole.move("material", to_site="target_site")'), encoding="utf-8") _parse_file(path, tmp_path) _parse_file(path, tmp_path) warnings = [record.getMessage() for record in caplog.records if "实验性功能" in record.getMessage()] assert len(warnings) == 1 assert "move_only_experimental.Robot.move" in warnings[0] - assert "material_contract= 是实验性功能(Material.move)" in warnings[0] + assert "material_contract= 是实验性功能(MaterialRole.move)" in warnings[0] def test_experimental_warning_from_the_decorator(caplog) -> None: @@ -270,17 +270,66 @@ def test_experimental_warning_from_the_decorator(caplog) -> None: caplog.set_level(logging.WARNING) class Driver: - @action(material_contract=Material.in_place("sample")) + @action(material_contract=MaterialRole.in_place("sample")) def stir_experimental(self, sample: ResourceSlot) -> None: pass - @action(material_contract=Material.move("plate", to_site="target_site")) + @action(material_contract=MaterialRole.move("plate", to_site="target_site")) def move_experimental(self, plate: ResourceSlot, target_site: SiteSlot) -> None: pass messages = [record.getMessage() for record in caplog.records] - assert any("material_contract= 是实验性功能(Material.in_place)" in message for message in messages) - assert any("move_experimental" in message and "material_contract= 是实验性功能(Material.move)" in message for message in messages) + assert any("material_contract= 是实验性功能(MaterialRole.in_place)" in message for message in messages) + assert any("move_experimental" in message and "material_contract= 是实验性功能(MaterialRole.move)" in message for message in messages) + + +_OLD_CLASS_SOURCE = ''' +from unilabos.registry.decorators import Material, action, device +from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot + +@device(id="old_material_class", category=["test"]) +class Driver: + @action(material_contract=Material.move("plate", to_site="target_site")) + def run(self, plate: ResourceSlot, target_site: SiteSlot) -> None: + pass +''' + + +def test_old_class_name_material_fails_in_the_scan_with_the_new_name(tmp_path: Path) -> None: + """改名前的类名 Material:AST 扫描(不导入作者模块)直接报错,提示改成 MaterialRole.xxx(...)。""" + + path = tmp_path / "old_material_class.py" + path.write_text(_OLD_CLASS_SOURCE, encoding="utf-8") + with pytest.raises(MaterialRoleError, match=r"Material 已改名为 MaterialRole:把 Material\.move\(\.\.\.\) 写成 MaterialRole\.move"): + _parse_file(path, tmp_path) + + +def test_old_class_name_material_fails_at_import_with_the_new_name(tmp_path: Path) -> None: + """Material 仍可从 decorators / material_roles 导入(不是 ImportError),但 Material.xxx(...) 一用就报错。""" + + from unilabos.registry import material_roles + from unilabos.registry.decorators import Material as FromDecorators + + assert FromDecorators is material_roles.Material + with pytest.raises(MaterialRoleError, match=r"写成 MaterialRole\.move\(\.\.\.\)"): + _import(tmp_path, _OLD_CLASS_SOURCE, name="old_material_class_runtime") + for name in ("pick", "site_picker", "anything"): + with pytest.raises(MaterialRoleError, match=rf"写成 MaterialRole\.{name}\(\.\.\.\)"): + getattr(FromDecorators, name) + with pytest.raises(MaterialRoleError, match="MaterialRole"): + FromDecorators() + # 内省(pytest / inspect 查 __wrapped__ 之类)仍按普通属性缺失处理 + assert getattr(FromDecorators, "__wrapped__", None) is None + + +def test_material_role_factories_return_material_roles_and_ast_only_calls_factories(tmp_path: Path) -> None: + """MaterialRole.xxx(...) 返回 MaterialRole;AST 扫描只调声明工厂,不会调到实例方法或字段。""" + + role = MaterialRole.move("material", to_site="target_site") + assert isinstance(role, MaterialRole) and role.kind == "move" + for method in ("values", "contract_part", "fields", "kind"): + with pytest.raises(MaterialRoleError, match=rf"MaterialRole 没有 {method}"): + _scan_action(tmp_path, f'MaterialRole.{method}("material")') @pytest.mark.parametrize("old_name", ["material", "materials"]) @@ -289,12 +338,12 @@ def test_old_field_names_fail_with_the_new_name(tmp_path: Path, old_name: str) - 提示改成 material_contract=(值不变)。""" source = f''' -from unilabos.registry.decorators import Material, action, device +from unilabos.registry.decorators import MaterialRole, action, device from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot @device(id="old_{old_name}_field", category=["test"]) class Driver: - @action({old_name}=Material.move("plate", to_site="target_site")) + @action({old_name}=MaterialRole.move("plate", to_site="target_site")) def run(self, plate: ResourceSlot, target_site: SiteSlot) -> None: pass ''' @@ -311,7 +360,7 @@ def run(self, plate: ResourceSlot, target_site: SiteSlot) -> None: ("option", "hint"), [ ('contract="typed"', "去掉 contract="), - ('resource_contract={"version": 2, "operate_in_place": {"material_param": "x"}}', "Material.in_place"), + ('resource_contract={"version": 2, "operate_in_place": {"material_param": "x"}}', "MaterialRole.in_place"), ('goal={"y": "x"}', "字段名就是参数名"), ('result={"y": "x"}', "返回 TypedDict"), ], @@ -341,4 +390,4 @@ def send(self, cmd: str) -> None: assert send._action_registry_meta["goal"] == {"command": "cmd"} with pytest.raises(ValueError, match="material_contract= 只用于 JSON 动作"): - action(action_type="unilabos_msgs.action:SendCmd", material_contract=Material.in_place("cmd"))(send) + action(action_type="unilabos_msgs.action:SendCmd", material_contract=MaterialRole.in_place("cmd"))(send) diff --git a/tests/registry/test_backend_metadata.py b/tests/registry/test_backend_metadata.py index 77bb93a808..da4304e66c 100644 --- a/tests/registry/test_backend_metadata.py +++ b/tests/registry/test_backend_metadata.py @@ -267,7 +267,7 @@ def test_ast_cache_rejects_previous_metadata_version(tmp_path) -> None: cache = load_scan_cache(cache_path) - assert _CACHE_VERSION == 30 + assert _CACHE_VERSION == 31 assert cache == {"version": _CACHE_VERSION, "files": {}} diff --git a/tests/registry/test_site_selector_contract.py b/tests/registry/test_site_selector_contract.py index bbedb7ccdf..ef80afbb7a 100644 --- a/tests/registry/test_site_selector_contract.py +++ b/tests/registry/test_site_selector_contract.py @@ -1,7 +1,7 @@ -"""库位参数(``SiteSlot``)与物料参数的关系:``@action(material_contract=Material.site_picker(...))``。 +"""库位参数(``SiteSlot``)与物料参数的关系:``@action(material_contract=MaterialRole.site_picker(...))``。 ``SiteSelector`` 已与 ``SiteSlot`` 合一:库位参数只有一个类型 ``SiteSlot``,库位属于哪个物料参数、放进去的是 -哪个物料参数、已占用库位的显示 / 可选策略写在 ``Material.site_picker``。生成的 ``x-unilabos-site-selector`` 扩展与 +哪个物料参数、已占用库位的显示 / 可选策略写在 ``MaterialRole.site_picker``。生成的 ``x-unilabos-site-selector`` 扩展与 原 ``SiteSelector`` 相同,连接点投影、运行预检与派发前的库位门禁照旧按它工作。 """ @@ -20,7 +20,7 @@ compile_action_template_handles, ) from unilabos.registry.ast_registry_scanner import _parse_file -from unilabos.registry.decorators import Material, action +from unilabos.registry.decorators import MaterialRole, action from unilabos.registry.material_roles import MaterialRoleError, material_contract, material_site_selectors from unilabos.registry.registry import Registry @@ -44,7 +44,7 @@ def _source(material: str, signature: str, *, header: str = "") -> str: return textwrap.dedent( f''' from typing import Optional - from unilabos.registry.decorators import Material, action, device + from unilabos.registry.decorators import MaterialRole, action, device from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot {header} @@ -67,7 +67,7 @@ def _scan(tmp_path: Path, material: str, signature: str, *, header: str = "") -> return entry["class"]["action_value_mappings"]["action"] -_FULL = 'Material.site_picker("site", of="warehouse", for_material="resource", occupied="show")' +_FULL = 'MaterialRole.site_picker("site", of="warehouse", for_material="resource", occupied="show")' _FULL_SIGNATURE = "warehouse: ResourceSlot, resource: ResourceSlot, site: SiteSlot = None" @@ -76,20 +76,20 @@ def _without_description(field: dict[str, Any]) -> dict[str, Any]: def test_material_site_builds_the_same_extension_as_the_removed_site_selector() -> None: - role = Material.site_picker("site", of="warehouse", for_material="resource", occupied="show") + role = MaterialRole.site_picker("site", of="warehouse", for_material="resource", occupied="show") assert material_site_selectors(role) == {"site": _SITE_SELECTOR_FIELD["x-unilabos-site-selector"]} # 库位关系不进资源合同:只写库位关系的动作没有资源合同,与其他语义写在一起时互不影响 assert material_contract(role) == {} - assert material_contract([Material.in_place("resource"), role]) == { + assert material_contract([MaterialRole.in_place("resource"), role]) == { "version": 2, "operate_in_place": {"material_param": "resource"}, } with pytest.raises(MaterialRoleError): - Material.site_picker("site", of="warehouse", occupied="yes") + MaterialRole.site_picker("site", of="warehouse", occupied="yes") with pytest.raises(MaterialRoleError, match="自身"): - Material.site_picker("site", of="site") + MaterialRole.site_picker("site", of="site") with pytest.raises(MaterialRoleError, match="多条"): - material_site_selectors([Material.site_picker("site", of="a"), Material.site_picker("site", of="b")]) + material_site_selectors([MaterialRole.site_picker("site", of="a"), MaterialRole.site_picker("site", of="b")]) def test_action_site_parameter_compiles_complete_relation_metadata(tmp_path: Path) -> None: @@ -105,7 +105,7 @@ def test_action_site_parameter_compiles_complete_relation_metadata(tmp_path: Pat def test_decorator_records_the_same_relation(tmp_path: Path) -> None: from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot - @action(material_contract=Material.site_picker("site", of="warehouse")) + @action(material_contract=MaterialRole.site_picker("site", of="warehouse")) def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass @@ -114,7 +114,7 @@ def place(self, warehouse: ResourceSlot, site: SiteSlot) -> None: } with pytest.raises(MaterialRoleError, match="missing"): - @action(material_contract=Material.site_picker("site", of="missing")) + @action(material_contract=MaterialRole.site_picker("site", of="missing")) def bad(self, warehouse: ResourceSlot, site: SiteSlot) -> None: pass @@ -124,43 +124,43 @@ def bad(self, warehouse: ResourceSlot, site: SiteSlot) -> None: [ pytest.param( "warehouse: ResourceSlot, resource: ResourceSlot, site: SiteSlot", - 'Material.site_picker("site", of="missing", for_material="resource")', + 'MaterialRole.site_picker("site", of="missing", for_material="resource")', "of='missing'", id="missing-owner", ), pytest.param( "warehouse: str, resource: ResourceSlot, site: SiteSlot", - 'Material.site_picker("site", of="warehouse", for_material="resource")', + 'MaterialRole.site_picker("site", of="warehouse", for_material="resource")', "of='warehouse'", id="scalar-owner", ), pytest.param( "warehouse: ResourceSlot, resource: str, site: SiteSlot", - 'Material.site_picker("site", of="warehouse", for_material="resource")', + 'MaterialRole.site_picker("site", of="warehouse", for_material="resource")', "for_material='resource'", id="scalar-occupant", ), pytest.param( "warehouse: list[ResourceSlot], site: SiteSlot", - 'Material.site_picker("site", of="warehouse")', + 'MaterialRole.site_picker("site", of="warehouse")', "单个 ResourceSlot", id="list-owner", ), pytest.param( "warehouse: ResourceSlot, site: str", - 'Material.site_picker("site", of="warehouse")', + 'MaterialRole.site_picker("site", of="warehouse")', "必须注解为 SiteSlot", id="plain-string-site", ), pytest.param( "warehouse: ResourceSlot, site: list[SiteSlot]", - 'Material.site_picker("site", of="warehouse")', + 'MaterialRole.site_picker("site", of="warehouse")', "必须注解为 SiteSlot", id="site-list", ), pytest.param( "warehouse: ResourceSlot", - 'Material.site_picker("site", of="warehouse")', + 'MaterialRole.site_picker("site", of="warehouse")', "签名里没有", id="missing-site", ), @@ -179,8 +179,8 @@ def test_material_site_rejects_forged_material_import(tmp_path: Path) -> None: path = tmp_path / "site_driver.py" path.write_text( _source(_FULL, _FULL_SIGNATURE).replace( - "from unilabos.registry.decorators import Material, action, device", - "from unilabos.registry.decorators import action, device\nfrom malicious.roles import Material", + "from unilabos.registry.decorators import MaterialRole, action, device", + "from unilabos.registry.decorators import action, device\nfrom malicious.roles import MaterialRole", ), encoding="utf-8", ) @@ -189,7 +189,7 @@ def test_material_site_rejects_forged_material_import(tmp_path: Path) -> None: def test_removed_site_selector_points_to_material_site(tmp_path: Path) -> None: - with pytest.raises(ImportError, match=r"Material\.site"): + with pytest.raises(ImportError, match=r"MaterialRole\.site"): from unilabos.registry.annotations import SiteSelector # noqa: F401 path = tmp_path / "old_site_driver.py" path.write_text( @@ -209,13 +209,13 @@ def place(self, warehouse: ResourceSlot, site: Annotated[str, SiteSelector(owner ), encoding="utf-8", ) - with pytest.raises(ActionSchemaError, match=r"SiteSelector 已删除.*SiteSlot.*Material\.site"): + with pytest.raises(ActionSchemaError, match=r"SiteSelector 已删除.*SiteSlot.*MaterialRole\.site"): _parse_file(path, tmp_path) def test_material_site_allows_omitting_the_optional_occupant(tmp_path: Path) -> None: action_entry = _scan( - tmp_path, 'Material.site_picker("site", of="warehouse")', "warehouse: ResourceSlot, site: SiteSlot" + tmp_path, 'MaterialRole.site_picker("site", of="warehouse")', "warehouse: ResourceSlot, site: SiteSlot" ) site = action_entry["schema"]["properties"]["goal"]["properties"]["site"] assert site["type"] == "string" @@ -276,7 +276,7 @@ def test_action_template_handle_projects_complete_site_selector_metadata(tmp_pat def test_action_template_projection_rejects_invalid_site_selector_extensions( tmp_path: Path, field_name: str, schema_change: dict[str, object], message: str ) -> None: - schema = _scan(tmp_path, 'Material.site_picker("site", of="warehouse")', "warehouse: ResourceSlot, site: SiteSlot")[ + schema = _scan(tmp_path, 'MaterialRole.site_picker("site", of="warehouse")', "warehouse: ResourceSlot, site: SiteSlot")[ "schema" ] field_schema = schema["properties"]["goal"]["properties"][field_name] @@ -309,7 +309,7 @@ def get_material(self, identity: str) -> Any: @pytest.mark.parametrize("allow_occupied", [False, True]) def test_preflight_and_dispatch_gate_follow_the_material_site_relation(tmp_path: Path, allow_occupied: bool) -> None: - """运行预检与派发前共用的库位门禁按 Material.site_picker 生成的扩展核对归属与占用,行为与原 SiteSelector 相同。""" + """运行预检与派发前共用的库位门禁按 MaterialRole.site_picker 生成的扩展核对归属与占用,行为与原 SiteSelector 相同。""" from unilabos.server.services.runtime.workflow.run_preflight import ( ResourceUnavailableError, @@ -317,7 +317,7 @@ def test_preflight_and_dispatch_gate_follow_the_material_site_relation(tmp_path: ) material = ( - f'Material.site_picker("site", of="warehouse", for_material="resource", occupied={'"allow"' if allow_occupied else '"show"'})' + f'MaterialRole.site_picker("site", of="warehouse", for_material="resource", occupied={'"allow"' if allow_occupied else '"show"'})' ) schema = _scan(tmp_path, material, "warehouse: ResourceSlot, resource: ResourceSlot, site: SiteSlot")["schema"] materials = _Materials() diff --git a/tests/server/test_material_actions.py b/tests/server/test_material_actions.py index 52f42ab2e4..118917e206 100644 --- a/tests/server/test_material_actions.py +++ b/tests/server/test_material_actions.py @@ -1,4 +1,4 @@ -"""``Material.move`` / ``pick`` / ``place`` 的调度解析与按类型加锁(真实物料权威,不起调度器)。 +"""``MaterialRole.move`` / ``pick`` / ``place`` 的调度解析与按类型加锁(真实物料权威,不起调度器)。 - 所属方由库位 uuid 决定:载架(仓库)或设备根节点; - 搬运设备省略即执行设备,写了是 ``DeviceSlot``(设备 id 解析成设备物料); @@ -23,7 +23,7 @@ ResourceTemplateWrite, SiteCreate, ) -from unilabos.registry.decorators import Material +from unilabos.registry.decorators import MaterialRole from unilabos.registry.material_roles import material_contract from unilabos.resources import materials from unilabos.server.scheduler.models import SchedulerResourceRequest @@ -100,7 +100,7 @@ def test_move_derives_the_owner_from_the_site_and_carries_with_the_executor(auth source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") arm = _device(service, "arm", [("grip", {"role": "gripper"})]) sample = source["A01"].resource.unilabos_uuid - schema = _schema(Material.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + schema = _schema(MaterialRole.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) target_site = _site(service, target.unilabos_uuid, "A02").site_uuid plan = resolve_physical_contract(schema, {"plate": {"uuid": sample}, "target_site": target_site}, "arm", gateway) @@ -123,7 +123,7 @@ def test_move_checks_a_given_from_site_against_the_authority(authority) -> None: _device(service, "arm", [("grip", {"role": "gripper"})]) sample = source["A01"].resource.unilabos_uuid schema = _schema( - Material.move("plate", to_site="target_site", from_site="source_site"), + MaterialRole.move("plate", to_site="target_site", from_site="source_site"), {"plate": _MATERIAL, "target_site": _SITE, "source_site": _SITE}, ) values = {"plate": {"uuid": sample}, "target_site": _site(service, target.unilabos_uuid, "A02").site_uuid} @@ -146,7 +146,7 @@ def test_move_onto_a_device_root_site_with_a_device_slot_carrier(authority) -> N reader = _device(service, "reader", [("S1", {}), ("S2", {})]) sample = source["A01"].resource.unilabos_uuid schema = _schema( - Material.move("plate", to_site="target_site", carrier_device="carrier_device"), + MaterialRole.move("plate", to_site="target_site", carrier_device="carrier_device"), {"plate": _MATERIAL, "target_site": _SITE, "carrier_device": _DEVICE}, ) target_site = _site(service, reader, "S2").site_uuid @@ -166,7 +166,7 @@ def test_move_without_a_gripper_site_is_a_contract_error(authority) -> None: service, gateway = authority source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") _device(service, "arm", [("grip", {"role": "robot.gripper"})]) - schema = _schema(Material.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + schema = _schema(MaterialRole.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) with pytest.raises(ValueError, match="role=gripper"): resolve_physical_contract(schema, { "plate": {"uuid": source["A01"].resource.unilabos_uuid}, @@ -183,7 +183,7 @@ def test_pick_then_place_hold_the_material_on_the_gripper(authority) -> None: sample = source["A01"].resource.unilabos_uuid grip = _site(service, arm, "grip").site_uuid - pick = _schema(Material.pick("plate"), {"plate": _MATERIAL}) + pick = _schema(MaterialRole.pick("plate"), {"plate": _MATERIAL}) plan = resolve_physical_contract(pick, {"plate": {"uuid": sample}}, "arm", gateway) (move,) = plan["moves"] assert (move.target_owner_uuid, move.target_site_uuid) == (arm, grip) @@ -193,7 +193,7 @@ def test_pick_then_place_hold_the_material_on_the_gripper(authority) -> None: assert _occupant(service, arm, "grip") == sample assert _occupant(service, source.unilabos_uuid, "A01") is None - place = _schema(Material.place("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + place = _schema(MaterialRole.place("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) target_site = _site(service, target.unilabos_uuid, "A03").site_uuid plan = resolve_physical_contract(place, {"plate": {"uuid": sample}, "target_site": target_site}, "arm", gateway) (move,) = plan["moves"] @@ -209,7 +209,7 @@ def test_pick_with_a_from_site_that_disagrees_waits(authority) -> None: service, gateway = authority source = _warehouse(gateway, "src") _device(service, "arm", [("grip", {"role": "gripper"})]) - schema = _schema(Material.pick("plate", from_site="from_site"), {"plate": _MATERIAL, "from_site": _SITE}) + schema = _schema(MaterialRole.pick("plate", from_site="from_site"), {"plate": _MATERIAL, "from_site": _SITE}) values = {"plate": {"uuid": source["A01"].resource.unilabos_uuid}} resolve_physical_contract(schema, {**values, "from_site": _site(service, source.unilabos_uuid, "A01").site_uuid}, "arm", gateway) @@ -224,11 +224,11 @@ def test_place_with_a_device_slot_carrier_releases_that_device(authority) -> Non _device(service, "executor", []) arm = _device(service, "arm", [("grip", {"role": "gripper"})]) sample = source["A01"].resource.unilabos_uuid - pick = _schema(Material.pick("plate", carrier_device="arm_device"), {"plate": _MATERIAL, "arm_device": _DEVICE}) + pick = _schema(MaterialRole.pick("plate", carrier_device="arm_device"), {"plate": _MATERIAL, "arm_device": _DEVICE}) plan = resolve_physical_contract(pick, {"plate": {"uuid": sample}, "arm_device": "arm"}, "executor", gateway) assert plan["device_tenancy"].acquire_device_id == "arm" _settle(service, plan) - place = _schema(Material.place("plate", to_site="to_site", carrier_device="arm_device"), + place = _schema(MaterialRole.place("plate", to_site="to_site", carrier_device="arm_device"), {"plate": _MATERIAL, "to_site": _SITE, "arm_device": _DEVICE}) plan = resolve_physical_contract(place, { "plate": {"uuid": sample}, "arm_device": "arm", @@ -272,14 +272,14 @@ def test_load_without_a_device_holds_the_executing_device(authority) -> None: vial = materials.create(_bottle("vial"), gateway=gateway) _device(service, "reactor", []) _device(service, "shelf", []) - load = _schema(Material.load("sample"), {"sample": _MATERIAL}) + load = _schema(MaterialRole.load("sample"), {"sample": _MATERIAL}) tenancy = resolve_tenancy_contract(load, {"sample": {"uuid": vial.unilabos_uuid}}, "reactor", gateway) assert tenancy["device_tenancy"].acquire_device_id == "reactor" assert tenancy["device_tenancy"].release_device_id is None - unload = _schema(Material.unload("sample"), {"sample": _MATERIAL}) + unload = _schema(MaterialRole.unload("sample"), {"sample": _MATERIAL}) tenancy = resolve_tenancy_contract(unload, {"sample": {"uuid": vial.unilabos_uuid}}, "reactor", gateway) assert tenancy["device_tenancy"].release_device_id == "reactor" - moved = _schema(Material.load("sample", from_device="from_device"), {"sample": _MATERIAL, "from_device": _DEVICE}) + moved = _schema(MaterialRole.load("sample", from_device="from_device"), {"sample": _MATERIAL, "from_device": _DEVICE}) tenancy = resolve_tenancy_contract( moved, {"sample": {"uuid": vial.unilabos_uuid}, "from_device": "shelf"}, "reactor", gateway) assert (tenancy["device_tenancy"].acquire_device_id, tenancy["device_tenancy"].release_device_id) == ( @@ -307,7 +307,7 @@ def schema(picker, fields): return {"properties": {"goal": {"properties": {**fields, "site": site_field}}}, "x-unilabos-action-contract": {"version": 2}} - own = schema(Material.site_picker("site", for_material="sample"), {"sample": _MATERIAL}) + own = schema(MaterialRole.site_picker("site", for_material="sample"), {"sample": _MATERIAL}) values = {"sample": {"uuid": vial.unilabos_uuid}} validate_resource_values(own, {**values, "site": _site(service, reader, "S1").site_uuid}, gateway, device_id="reader") with pytest.raises(ValueError, match="不属于所选容器"): @@ -317,7 +317,7 @@ def schema(picker, fields): validate_resource_values(own, {**values, "site": _site(service, warehouse.unilabos_uuid, "A02").site_uuid}, gateway, device_id="reader") - of_device = schema(Material.site_picker("site", of="target_device", for_material="sample"), + of_device = schema(MaterialRole.site_picker("site", of="target_device", for_material="sample"), {"sample": _MATERIAL, "target_device": _DEVICE}) validate_resource_values(of_device, {**values, "target_device": "other", "site": _site(service, other, "T1").site_uuid}, gateway, device_id="reader") @@ -363,8 +363,8 @@ def test_a_site_label_resolves_under_the_site_picker_owner(authority) -> None: source, target = _warehouse(gateway, "src"), _warehouse(gateway, "dst") _device(service, "arm", [("grip", {"role": "gripper"})]) sample = source["A01"].resource.unilabos_uuid - declared = [Material.move("plate", to_site="target_site"), - Material.site_picker("target_site", of="target", for_material="plate")] + declared = [MaterialRole.move("plate", to_site="target_site"), + MaterialRole.site_picker("target_site", of="target", for_material="plate")] site_field = {**_SITE, "x-unilabos-site-selector": material_site_selectors(declared)["target_site"]} schema = _schema(declared, {"plate": _MATERIAL, "target": _MATERIAL, "target_site": site_field}) values = {"plate": {"uuid": sample}, "target": {"uuid": target.unilabos_uuid}, "target_site": "A03"} @@ -376,7 +376,7 @@ def test_a_site_label_resolves_under_the_site_picker_owner(authority) -> None: (claim,) = resolve_tenancy_contract(schema, values, "arm", gateway)["site_claims"] assert (claim.owner_material_uuid, claim.site_uuid) == (target.unilabos_uuid, target_site) # 没有 site_picker 关系的库位名无从解析:派发前报错,也不加库位锁 - bare = _schema(Material.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) + bare = _schema(MaterialRole.move("plate", to_site="target_site"), {"plate": _MATERIAL, "target_site": _SITE}) with pytest.raises(ValueError, match="site_picker"): resolve_physical_contract(bare, {"plate": {"uuid": sample}, "target_site": "A03"}, "arm", gateway) assert "site_claims" not in resolve_tenancy_contract(bare, {"plate": {"uuid": sample}, "target_site": "A03"}, diff --git a/tests/server/test_site_selection_by_owner.py b/tests/server/test_site_selection_by_owner.py index f7c3ad6b25..9d25ad33f1 100644 --- a/tests/server/test_site_selection_by_owner.py +++ b/tests/server/test_site_selection_by_owner.py @@ -1,6 +1,6 @@ """库位参数按所属物料选择:``{"owner_uuid": ...}`` 在任务准入时选定、经入口预留占住并冻结进任务。 -候选是所属物料下接受放入物料(``Material.site_picker`` 的 for_material)的库位(模板白名单 / 允许的资源类别),按库位序号选第一个 +候选是所属物料下接受放入物料(``MaterialRole.site_picker`` 的 for_material)的库位(模板白名单 / 允许的资源类别),按库位序号选第一个 空着且没被预留的;没有接受的库位是预检错误(``reason=no_acceptable_site``),接受的都被占着时任务排队 (``wait_reason.code=site_group_unavailable``)。精确库位 uuid 照旧。 """ diff --git a/unilabos/protocol/runtime/site_references.py b/unilabos/protocol/runtime/site_references.py index 5fc808c06f..0ba7ae2324 100644 --- a/unilabos/protocol/runtime/site_references.py +++ b/unilabos/protocol/runtime/site_references.py @@ -3,7 +3,7 @@ - 物料参数(``ResourceSlot`` / ``list[ResourceSlot]``)按库位绑定:``{"site_uuid": "<库位 uuid>"}``, 表示「此刻占着这个库位的物料」。建任务 / 运行预检时解析成占用物料的 ``{"uuid": ...}`` 并冻结进任务, 之后物料被挪走也不改变任务用的是哪件物料。 -- 库位参数(``SiteSlot``,带 ``Material.site_picker`` 关系)按所属物料选择:``{"owner_uuid": "<所属物料 uuid>"}``, +- 库位参数(``SiteSlot``,带 ``MaterialRole.site_picker`` 关系)按所属物料选择:``{"owner_uuid": "<所属物料 uuid>"}``, 表示「这个物料下一个接受放入物料的空库位」。任务准入时调度器按库位序号选一个、经入口预留占住, 并把选中的库位 uuid 冻结进任务。 diff --git a/unilabos/registry/action_options.py b/unilabos/registry/action_options.py index 3a1fa852ad..27167f609d 100644 --- a/unilabos/registry/action_options.py +++ b/unilabos/registry/action_options.py @@ -3,14 +3,14 @@ 这些写法不再接受,写了就报错并指出新写法(见 ``docs/developer_guide/action_standard.md`` 的「不兼容变更」): - ``contract=``:所有 JSON 动作统一按签名生成并校验 schema,没有 opt-in 开关; -- ``resource_contract={...}``:资源语义改用 ``material_contract=Material.xxx(...)``; +- ``resource_contract={...}``:资源语义改用 ``material_contract=MaterialRole.xxx(...)``; - ``material=``(以及短暂出现过的 ``materials=``):字段改名为 ``material_contract=``,值不变 - (一条 ``Material.xxx(...)`` 或它们组成的列表); + (一条 ``MaterialRole.xxx(...)`` 或它们组成的列表); - JSON 动作的 ``goal=`` / ``result=`` 重命名:字段名就是参数名 / 返回 TypedDict 的字段名 (ROS 动作类型的 ``goal`` / ``result`` 字段映射照旧); - 参数注解里的 ``Placeholder(...)``:前端选择器写在 ``@action(placeholder_keys={...})``; - 参数注解里的 ``SiteSelector(...)``:库位参数注解为 ``SiteSlot``,库位选择器提示写成 - ``material_contract=Material.site_picker(...)``; + ``material_contract=MaterialRole.site_picker(...)``; - 按名字注入的动作上下文(参数叫 ``action_context`` 却没有 ``ActionContext`` 注解):框架按类型注入, 注解为 ``Optional[ActionContext]``(见 :mod:`unilabos.registry.action_context`)。 @@ -26,7 +26,7 @@ #: 资源语义字段改名的提示:``material=``(dev 上的旧名)与 ``materials=``(短暂出现过)都改成 ``material_contract=``。 _MATERIAL_CONTRACT_RENAME = ( - "字段改名为 material_contract=,值不变:写成 material_contract=Material.xxx(...)" + "字段改名为 material_contract=,值不变:写成 material_contract=MaterialRole.xxx(...)" "(多条照旧写成列表);material_contract= 是实验性功能" ) @@ -34,10 +34,10 @@ REMOVED_ACTION_OPTIONS: Dict[str, str] = { "contract": "所有 JSON 动作统一按签名生成并校验 schema,去掉 contract= 即可", "resource_contract": ( - "资源语义改用 material_contract=Material.xxx(...),例如 " - "material_contract=Material.move(\"plate\", to_site=\"target_site\")、" - "material_contract=Material.dispense(from_material=\"source\", to_materials=[\"target\"])、" - "material_contract=[Material.in_place(\"sample\"), Material.order_sensitive()]" + "资源语义改用 material_contract=MaterialRole.xxx(...),例如 " + "material_contract=MaterialRole.move(\"plate\", to_site=\"target_site\")、" + "material_contract=MaterialRole.dispense(from_material=\"source\", to_materials=[\"target\"])、" + "material_contract=[MaterialRole.in_place(\"sample\"), MaterialRole.order_sensitive()]" ), "material": _MATERIAL_CONTRACT_RENAME, "materials": _MATERIAL_CONTRACT_RENAME, @@ -55,7 +55,7 @@ "参数类型照常写,去掉 Annotated[..., Placeholder(...)] 外壳" ), "SiteSelector": ( - "库位参数注解为 SiteSlot,库位选择器提示写成 @action(material_contract=Material.site_picker(\"库位参数\", " + "库位参数注解为 SiteSlot,库位选择器提示写成 @action(material_contract=MaterialRole.site_picker(\"库位参数\", " "of=\"拥有库位的物料或设备参数\", for_material=\"放进去的物料参数\", occupied=\"show\"))" ), } diff --git a/unilabos/registry/action_resource_contract.py b/unilabos/registry/action_resource_contract.py index 3a8646b0a2..9fe93277b7 100644 --- a/unilabos/registry/action_resource_contract.py +++ b/unilabos/registry/action_resource_contract.py @@ -22,7 +22,7 @@ #: transfer 的可选字段:搬运设备参数(``DeviceSlot``),省略时是执行设备。 TRANSFER_OPTIONAL_FIELDS: tuple[str, ...] = ("carrier_device_param",) RESOURCE_PARAM_ROLES = frozenset({"device", "tool", "motion", "site", "material"}) -#: 设备托管合同里表示「执行设备本身」的记号(``Material.load`` / ``unload`` 省略 ``device`` 时); +#: 设备托管合同里表示「执行设备本身」的记号(``MaterialRole.load`` / ``unload`` 省略 ``device`` 时); #: 参数名不可能以 ``$`` 开头,调度器把它解析成执行动作的设备。 EXECUTING_DEVICE = "$executor" diff --git a/unilabos/registry/action_schema.py b/unilabos/registry/action_schema.py index 2d6d1efbda..3ba2eaebb8 100644 --- a/unilabos/registry/action_schema.py +++ b/unilabos/registry/action_schema.py @@ -5,7 +5,7 @@ - 严格解析器认识的注解(``str`` / ``int`` / ``float`` / ``bool``、``Literal``、``Optional`` 与 ``X | None``、``ResourceSlot`` / ``list[ResourceSlot]``、``list[X]``、``dict[str, JSONValue]``,以及 ``Annotated[..., Field(...)]`` / ``AllowedResourceTemplates``):严格 schema; -- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(material_contract=Material.site_picker(...))`` 声明的 +- ``DeviceSlot`` / ``SiteSlot``:设备 ID / 库位 UUID 字符串;``@action(material_contract=MaterialRole.site_picker(...))`` 声明的 库位关系写进该 ``SiteSlot`` 参数的 ``x-unilabos-site-selector`` 扩展(前端库位选择器、预检与派发门禁用); - 没写注解、``Any``、``object``:接受任意 JSON 值(``{}``); - 默认值是 ``None`` 的参数按可空处理(``x: str = None`` 与 ``x: Optional[str] = None`` 相同); @@ -20,7 +20,7 @@ 不认识的字段退回推断);其他注解整体退回推断。 参数注解里已删除的 ``Placeholder(...)`` / ``SiteSelector(...)`` 是注册错误,报错信息给出新写法 -(前端选择器写 ``@action(placeholder_keys=...)``,库位关系写 ``Material.site_picker(...)``)。 +(前端选择器写 ``@action(placeholder_keys=...)``,库位关系写 ``MaterialRole.site_picker(...)``)。 ROS 动作类型(``@action(action_type=...)``)不经过这里,照旧按 ROS 消息生成 schema。 """ @@ -261,7 +261,7 @@ def reject_removed_annotations( def _is_site_slot(node: ast.AST, bindings: ModuleBindings) -> bool: - """单个 ``SiteSlot``(可带 ``Optional`` / ``| None`` / ``Annotated``):``Material.site_picker`` 的库位参数只能是它。""" + """单个 ``SiteSlot``(可带 ``Optional`` / ``| None`` / ``Annotated``):``MaterialRole.site_picker`` 的库位参数只能是它。""" if bindings.identity(node) == _SITE_SLOT: return True @@ -491,7 +491,7 @@ def build_action_schema_draft( 由注册表 ``finalize_action_schema`` 补全;``inferred`` / ``result_inferred`` 列出退回推断的参数与 返回字段;``skipped`` 是无法表示、被忽略的参数写法。 - ``site_selectors`` 是 ``Material.site_picker(...)`` 给出的 ``{库位参数名: x-unilabos-site-selector 扩展}``: + ``site_selectors`` 是 ``MaterialRole.site_picker(...)`` 给出的 ``{库位参数名: x-unilabos-site-selector 扩展}``: 库位参数必须注解为 ``SiteSlot``,owner / occupant 必须是单个 ``ResourceSlot`` 参数,扩展写进该参数的 schema。动作声明写错(库位关系不对、注解里写了已删除的 ``Placeholder`` / ``SiteSelector``)抛 :class:`ActionSchemaError`。 @@ -583,9 +583,9 @@ def build_action_schema_draft( for name, extension in (site_selectors or {}).items(): if name not in goal: - raise ActionSchemaError(f"动作 {definition}:Material.site_picker 引用了签名里没有的参数 {name}") + raise ActionSchemaError(f"动作 {definition}:MaterialRole.site_picker 引用了签名里没有的参数 {name}") if name not in site_slots: - raise ActionSchemaError(f"动作 {definition}:Material.site_picker 的库位参数 {name} 必须注解为 SiteSlot") + raise ActionSchemaError(f"动作 {definition}:MaterialRole.site_picker 的库位参数 {name} 必须注解为 SiteSlot") try: validate_site_selector_relations( strict_descriptors, diff --git a/unilabos/registry/ast_registry_scanner.py b/unilabos/registry/ast_registry_scanner.py index 8b8d207d0c..fe5013cc90 100644 --- a/unilabos/registry/ast_registry_scanner.py +++ b/unilabos/registry/ast_registry_scanner.py @@ -62,7 +62,7 @@ MAX_SCAN_DEPTH = 10 # 最大目录递归深度 MAX_SCAN_FILES = 1000 # 最大扫描文件数量 -_CACHE_VERSION = 30 # 30:@action 资源语义字段改名为 material_contract=(material= / materials= 报错);整个字段告警「实验性功能」 +_CACHE_VERSION = 31 # 31:资源语义声明类改名为 MaterialRole(Material.xxx(...) 报错) # 允许点号分段(如 liquid_handler.prcxi),与内置 YAML 注册表的命名先例一致; # 点号只用于注册表模板名,设备实例 id(图节点)另有约束。 _DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$") diff --git a/unilabos/registry/decorators.py b/unilabos/registry/decorators.py index 3bfda08a0e..cc2c8e6c47 100644 --- a/unilabos/registry/decorators.py +++ b/unilabos/registry/decorators.py @@ -5,7 +5,7 @@ Usage: from unilabos.registry.decorators import ( - device, action, resource, Material, + device, action, resource, MaterialRole, InputHandle, OutputHandle, ActionInputHandle, ActionOutputHandle, HardwareInterface, Side, DataSource, NodeType, @@ -40,8 +40,8 @@ def close(self): def set_valve_position(self, position): ... - # 资源语义(实验性):一个字段,Material 的一条或多条 - @action(material_contract=Material.in_place("vessel")) + # 资源语义(实验性):一个字段,MaterialRole 的一条或多条 + @action(material_contract=MaterialRole.in_place("vessel")) def flush(self, vessel: ResourceSlot) -> None: ... @@ -61,7 +61,8 @@ def is_open(self): REMOVED_MATERIAL_LOCK_OPTIONS, warn_ignored_material_lock_override, ) -from unilabos.registry.material_roles import Material +# Material:改名前的类名,只作占位(Material.xxx(...) 直接报错并提示 MaterialRole.xxx(...)) +from unilabos.registry.material_roles import Material, MaterialRole # noqa: F401 from unilabos.registry.utils.backend_metadata import normalize_supported_backends from unilabos.resources.objects.site import ( SiteDefinitionInput, @@ -517,8 +518,8 @@ def AddProtocol(self): ... parent: 若为 True,当方法参数为空 (*args, **kwargs) 时,通过 MRO 从父类获取真实方法参数 node_type: 动作的节点类型 (NodeType.ILAB / NodeType.MANUAL_CONFIRM)。 不填写时不写入注册表。 - material_contract: (实验性)动作的资源语义:物料动作 ``Material.move / pick / place / dispense``,以及 - ``Material.load / unload / in_place / site_picker / order_sensitive``,一条或多条组成的列表 + material_contract: (实验性)动作的资源语义:物料动作 ``MaterialRole.move / pick / place / dispense``,以及 + ``MaterialRole.load / unload / in_place / site_picker / order_sensitive``,一条或多条组成的列表 (见 ``unilabos.registry.material_roles``)。字符串都是参数名,注册时对照签名检查 (物料 ResourceSlot、库位 SiteSlot、设备 DeviceSlot);写了就按定义告警一次「实验性功能」。 旧字段名 ``material=``(以及短暂出现过的 ``materials=``)直接报错并提示改成 ``material_contract=``。 diff --git a/unilabos/registry/material_roles.py b/unilabos/registry/material_roles.py index ef9257cf17..ecde086618 100644 --- a/unilabos/registry/material_roles.py +++ b/unilabos/registry/material_roles.py @@ -1,13 +1,13 @@ """动作的资源语义:``@action(material_contract=...)`` 唯一的写法(实验性)。 -``material_contract=`` 的值是 ``Material`` 的一个方法调用,或多个调用组成的列表: +``material_contract=`` 的值是 ``MaterialRole`` 的一个方法调用,或多个调用组成的列表: - from unilabos.registry.decorators import action, Material + from unilabos.registry.decorators import action, MaterialRole - @action(material_contract=Material.move("plate", to_site="target_site")) + @action(material_contract=MaterialRole.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... - @action(material_contract=Material.dispense(from_material="source", to_materials=["target"])) + @action(material_contract=MaterialRole.dispense(from_material="source", to_materials=["target"])) def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... 物料动作:``move`` / ``pick`` / ``place`` / ``dispense``。不代表物料动作的声明:``load`` / ``unload`` 跨动作 @@ -19,7 +19,8 @@ def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> (``x-unilabos-action-contract.resource_contract``),调度器照旧按合同执行;``site_picker`` 不进资源合同, 写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展。 -旧写法(字段名 ``material=`` / ``materials=``,``transfer`` / ``aliquot`` / ``site`` / ``uses``,带 ``owner`` / ``site`` / +类名是 ``MaterialRole``(区别于运行时的物料操作模块 ``unilabos.resources.materials``)。旧写法(类名 ``Material``, +字段名 ``material=`` / ``materials=``,``transfer`` / ``aliquot`` / ``site`` / ``uses``,带 ``owner`` / ``site`` / ``carriers`` 的 ``pick`` / ``place``)直接报错并给出新写法。 本模块只依赖标准库与纯声明的合同规范化:装饰器(导入期)与 AST 扫描(不导入作者模块)共用。 @@ -54,7 +55,7 @@ def pipette(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> GRIPPER_ROLE = "gripper" #: ``site_picker`` 的已占用库位策略 → ``(show_occupied, allow_occupied)``。 _OCCUPIED = {"hide": (False, False), "show": (True, False), "allow": (True, True)} -#: AST 扫描认可的 ``Material`` 来源模块(``module:Material.method``)。 +#: AST 扫描认可的 ``MaterialRole`` 来源模块(``module:MaterialRole.method``)。 _MATERIAL_MODULES = ("unilabos.registry.decorators", "unilabos.registry.material_roles") @@ -83,12 +84,16 @@ def _optional(value: Any, label: str) -> str: def _legacy(message: str) -> MaterialRoleError: - return MaterialRoleError(f"{message}(Material 辅助 API 已重做,见 docs/developer_guide/action_standard.md「不兼容变更」)") + return MaterialRoleError(f"{message}(资源语义辅助 API 已重做,见 docs/developer_guide/action_standard.md「不兼容变更」)") @dataclass(frozen=True) class MaterialRole: - """``Material.xxx(...)`` 的结果:一条资源语义(不可变,按字段规范化成合同片段)。""" + """一条资源语义(不可变,按字段规范化成合同片段),也是写资源语义的唯一入口。 + + 每个工厂方法(``MaterialRole.move(...)`` 等)返回一条语义;``@action(material_contract=...)`` 接收一条或一个列表 + (实验性)。 + """ kind: str fields: Tuple[Tuple[str, Any], ...] = () @@ -146,10 +151,10 @@ def contract_part(self) -> Dict[str, Any]: raise MaterialRoleError(f"未知的资源语义 {self.kind}") def site_selector(self) -> Tuple[str, Dict[str, Any]]: - """``Material.site_picker(...)`` → ``(库位参数名, x-unilabos-site-selector 扩展)``。""" + """``MaterialRole.site_picker(...)`` → ``(库位参数名, x-unilabos-site-selector 扩展)``。""" if self.kind != "site_picker": - raise MaterialRoleError(f"Material.{self.kind} 不是库位选择器提示") + raise MaterialRoleError(f"MaterialRole.{self.kind} 不是库位选择器提示") values = self.values() show, allow = _OCCUPIED[values["occupied"]] return values["site"], { @@ -167,7 +172,7 @@ def parameter_types(self) -> List[Tuple[str, str, str]]: """ values = self.values() - label = f"Material.{self.kind}" + label = f"MaterialRole.{self.kind}" items: List[Tuple[str, str, str]] = [] if self.kind in {"load", "unload", "in_place", "move", "pick", "place"}: items.append((values["material"], "resource", f"{label} 的物料")) @@ -195,10 +200,6 @@ def parameter_types(self) -> List[Tuple[str, str, str]]: items.append((values["for_material"], "resource", f"{label} 的 for_material")) return items - -class Material: - """资源语义的唯一入口:每个方法返回一条语义,``@action(material_contract=...)`` 接收一条或一个列表(实验性)。""" - # ------------------------------------------------------------------ 物料动作 @staticmethod @@ -217,16 +218,16 @@ def move( """ fields: List[Tuple[str, Any]] = [ - ("material", _name(material, "Material.move 的物料")), - ("to_site", _name(to_site, "Material.move 的 to_site")), + ("material", _name(material, "MaterialRole.move 的物料")), + ("to_site", _name(to_site, "MaterialRole.move 的 to_site")), ] if from_site is not None: - fields.append(("from_site", _name(from_site, "Material.move 的 from_site"))) + fields.append(("from_site", _name(from_site, "MaterialRole.move 的 from_site"))) if carrier_device is not None: - fields.append(("carrier_device", _name(carrier_device, "Material.move 的 carrier_device"))) + fields.append(("carrier_device", _name(carrier_device, "MaterialRole.move 的 carrier_device"))) names = [value for _, value in fields] if len(set(names)) != len(names): - raise MaterialRoleError("Material.move 的物料、库位与搬运设备必须是不同的参数") + raise MaterialRoleError("MaterialRole.move 的物料、库位与搬运设备必须是不同的参数") return MaterialRole("move", tuple(fields)) @staticmethod @@ -244,10 +245,10 @@ def pick( if legacy: raise _legacy( - "Material.pick 不再接受 owner / site / carriers / gripper:写成 " - "Material.pick(\"物料参数\", from_site=\"SiteSlot 库位参数\"(可省略), carrier_device=\"DeviceSlot 设备参数\"(可省略,即执行设备))" + "MaterialRole.pick 不再接受 owner / site / carriers / gripper:写成 " + "MaterialRole.pick(\"物料参数\", from_site=\"SiteSlot 库位参数\"(可省略), carrier_device=\"DeviceSlot 设备参数\"(可省略,即执行设备))" ) - return Material._step("pick", material, from_site, carrier_device) + return MaterialRole._step("pick", material, from_site, carrier_device) @staticmethod def place( @@ -261,35 +262,35 @@ def place( if legacy or to_site is None: raise _legacy( - "Material.place 写成 Material.place(\"物料参数\", to_site=\"SiteSlot 库位参数\", " + "MaterialRole.place 写成 MaterialRole.place(\"物料参数\", to_site=\"SiteSlot 库位参数\", " "carrier_device=\"DeviceSlot 设备参数\"(可省略,即执行设备)),不再接受 owner / site / carriers / gripper" ) - return Material._step("place", material, to_site, carrier_device) + return MaterialRole._step("place", material, to_site, carrier_device) @staticmethod def _step(kind: str, material: str, site: Optional[str], carrier_device: Optional[str]) -> MaterialRole: keyword = "from_site" if kind == "pick" else "to_site" - fields: List[Tuple[str, Any]] = [("material", _name(material, f"Material.{kind} 的物料"))] + fields: List[Tuple[str, Any]] = [("material", _name(material, f"MaterialRole.{kind} 的物料"))] if site is not None: - fields.append(("site", _name(site, f"Material.{kind} 的 {keyword}"))) + fields.append(("site", _name(site, f"MaterialRole.{kind} 的 {keyword}"))) if carrier_device is not None: - fields.append(("carrier_device", _name(carrier_device, f"Material.{kind} 的 carrier_device"))) + fields.append(("carrier_device", _name(carrier_device, f"MaterialRole.{kind} 的 carrier_device"))) names = [value for _, value in fields] if len(set(names)) != len(names): - raise MaterialRoleError(f"Material.{kind} 的物料、库位与搬运设备必须是不同的参数") + raise MaterialRoleError(f"MaterialRole.{kind} 的物料、库位与搬运设备必须是不同的参数") return MaterialRole(kind, tuple(fields)) @staticmethod def dispense(*, from_material: str, to_materials: Union[str, Sequence[str]]) -> MaterialRole: """按驱动回报的实际量,把内容物从 ``from_material`` 转移到 ``to_materials``(``AliquotReceipt`` 结算)。""" - names = _names(to_materials, "Material.dispense 的 to_materials") + names = _names(to_materials, "MaterialRole.dispense 的 to_materials") if not names: - raise MaterialRoleError("Material.dispense 至少需要一个 to_materials") - source = _name(from_material, "Material.dispense 的 from_material") - targets = tuple(_name(item, "Material.dispense 的 to_materials") for item in names) + raise MaterialRoleError("MaterialRole.dispense 至少需要一个 to_materials") + source = _name(from_material, "MaterialRole.dispense 的 from_material") + targets = tuple(_name(item, "MaterialRole.dispense 的 to_materials") for item in names) if source in targets or len(set(targets)) != len(targets): - raise MaterialRoleError("Material.dispense 的来源与目标必须是不同的参数") + raise MaterialRoleError("MaterialRole.dispense 的来源与目标必须是不同的参数") return MaterialRole("dispense", (("from_material", source), ("to_materials", targets))) # ------------------------------------------------------------------ 不代表物料动作的声明 @@ -301,12 +302,12 @@ def load(material: str, *, device: Optional[str] = None, from_device: Optional[s ``from_device``:同时从另一台设备(``DeviceSlot`` 参数)转出。 """ - acquire = _optional(device, "Material.load 的 device") or EXECUTING_DEVICE - fields = [("material", _name(material, "Material.load 的物料")), ("acquire", acquire)] + acquire = _optional(device, "MaterialRole.load 的 device") or EXECUTING_DEVICE + fields = [("material", _name(material, "MaterialRole.load 的物料")), ("acquire", acquire)] if from_device is not None: - release = _name(from_device, "Material.load 的 from_device") + release = _name(from_device, "MaterialRole.load 的 from_device") if release == acquire: - raise MaterialRoleError("Material.load 的 device 与 from_device 不能是同一个参数") + raise MaterialRoleError("MaterialRole.load 的 device 与 from_device 不能是同一个参数") fields.append(("release", release)) return MaterialRole("load", tuple(fields)) @@ -314,14 +315,14 @@ def load(material: str, *, device: Optional[str] = None, from_device: Optional[s def unload(material: str, *, device: Optional[str] = None) -> MaterialRole: """把物料从设备 ``device``(``DeviceSlot`` 参数,省略即执行设备)取出并结束设备托管。""" - release = _optional(device, "Material.unload 的 device") or EXECUTING_DEVICE - return MaterialRole("unload", (("material", _name(material, "Material.unload 的物料")), ("release", release))) + release = _optional(device, "MaterialRole.unload 的 device") or EXECUTING_DEVICE + return MaterialRole("unload", (("material", _name(material, "MaterialRole.unload 的物料")), ("release", release))) @staticmethod def in_place(material: str) -> MaterialRole: """物料必须仍在执行设备内(原位处理)。""" - return MaterialRole("in_place", (("material", _name(material, "Material.in_place 的物料")),)) + return MaterialRole("in_place", (("material", _name(material, "MaterialRole.in_place 的物料")),)) @staticmethod def site_picker( @@ -338,16 +339,16 @@ def site_picker( ``"show"`` 列出但不能选,``"allow"`` 列出且能选。 """ - fields: List[Tuple[str, Any]] = [("site", _name(site, "Material.site_picker 的库位参数"))] + fields: List[Tuple[str, Any]] = [("site", _name(site, "MaterialRole.site_picker 的库位参数"))] if of is not None: - fields.append(("of", _name(of, "Material.site_picker 的 of"))) + fields.append(("of", _name(of, "MaterialRole.site_picker 的 of"))) if for_material is not None: - fields.append(("for_material", _name(for_material, "Material.site_picker 的 for_material"))) + fields.append(("for_material", _name(for_material, "MaterialRole.site_picker 的 for_material"))) if occupied not in _OCCUPIED: - raise MaterialRoleError('Material.site_picker 的 occupied 只能是 "hide"、"show" 或 "allow"') + raise MaterialRoleError('MaterialRole.site_picker 的 occupied 只能是 "hide"、"show" 或 "allow"') fields.append(("occupied", occupied)) if site in {of, for_material}: - raise MaterialRoleError("Material.site_picker 不能把库位参数自身作为 of / for_material") + raise MaterialRoleError("MaterialRole.site_picker 不能把库位参数自身作为 of / for_material") return MaterialRole("site_picker", tuple(fields)) @staticmethod @@ -361,7 +362,7 @@ def order_sensitive() -> MaterialRole: @staticmethod def transfer(*_args: Any, **_kwargs: Any) -> MaterialRole: raise _legacy( - "Material.transfer 已删除:写成 Material.move(\"物料参数\", to_site=\"SiteSlot 库位参数\", " + "MaterialRole.transfer 已删除:写成 MaterialRole.move(\"物料参数\", to_site=\"SiteSlot 库位参数\", " "from_site=\"SiteSlot 库位参数\"(可省略), carrier_device=\"DeviceSlot 设备参数\"(可省略,即执行设备));" "所属方由库位决定(不写 to / source),库位参数注解为 SiteSlot(值是库位 uuid)," "搬运设备的夹爪库位角色统一为 gripper(不写 gripper=)" @@ -370,31 +371,59 @@ def transfer(*_args: Any, **_kwargs: Any) -> MaterialRole: @staticmethod def aliquot(*_args: Any, **_kwargs: Any) -> MaterialRole: raise _legacy( - "Material.aliquot 已改名:写成 Material.dispense(from_material=\"来源物料参数\", to_materials=[\"目标物料参数\", ...])" + "MaterialRole.aliquot 已改名:写成 MaterialRole.dispense(from_material=\"来源物料参数\", to_materials=[\"目标物料参数\", ...])" ) @staticmethod def site(*_args: Any, **_kwargs: Any) -> MaterialRole: raise _legacy( - "Material.site 已改名:写成 Material.site_picker(\"SiteSlot 库位参数\", of=\"所属物料或设备参数\"(可省略,即执行设备), " + "MaterialRole.site 已改名:写成 MaterialRole.site_picker(\"SiteSlot 库位参数\", of=\"所属物料或设备参数\"(可省略,即执行设备), " "for_material=\"放入物料参数\", occupied=\"hide\" | \"show\" | \"allow\")" ) @staticmethod def uses(*_args: Any, **_kwargs: Any) -> MaterialRole: raise _legacy( - "Material.uses 已删除:参数按类型加锁(ResourceSlot 物料锁、DeviceSlot 设备锁、SiteSlot 库位锁)," - "把参数注解成对应类型即可,去掉 Material.uses(...)" + "MaterialRole.uses 已删除:参数按类型加锁(ResourceSlot 物料锁、DeviceSlot 设备锁、SiteSlot 库位锁)," + "把参数注解成对应类型即可,去掉 MaterialRole.uses(...)" ) +#: ``MaterialRole`` 上的声明工厂(AST 扫描只认这些名字,不会调到实例方法)。 +_FACTORY_NAMES = frozenset({ + "move", "pick", "place", "dispense", + "load", "unload", "in_place", "site_picker", "order_sensitive", + "transfer", "aliquot", "site", "uses", +}) + + +def _renamed(method: str) -> MaterialRoleError: + return MaterialRoleError( + f"Material 已改名为 MaterialRole:把 Material.{method}(...) 写成 MaterialRole.{method}(...)," + "从 unilabos.registry.decorators 导入 MaterialRole(声明式资源语义;运行时物料操作是 unilabos.resources.materials)" + ) + + +class _RenamedMaterialMeta(type): + def __getattr__(cls, name: str) -> Any: + if name.startswith("_"): + raise AttributeError(name) + raise _renamed(name) + + +class Material(metaclass=_RenamedMaterialMeta): + """已改名为 :class:`MaterialRole`。只为让旧写法 ``Material.xxx(...)`` 在导入时报错并给出新写法而保留。""" + + def __new__(cls, *_args: Any, **_kwargs: Any) -> "Material": + raise _renamed("xxx") + def _roles(value: Any) -> List[MaterialRole]: roles = list(value) if isinstance(value, (list, tuple)) else [value] for role in roles: if not isinstance(role, MaterialRole): - raise MaterialRoleError("material_contract= 只接受 Material.xxx(...) 或它们组成的列表") + raise MaterialRoleError("material_contract= 只接受 MaterialRole.xxx(...) 或它们组成的列表") if not roles: - raise MaterialRoleError("material_contract= 至少写一条 Material.xxx(...)") + raise MaterialRoleError("material_contract= 至少写一条 MaterialRole.xxx(...)") return roles @@ -420,7 +449,7 @@ def warn_experimental(value: Any, definition: str) -> None: warn_once( definition, - "material_contract= 是实验性功能(" + "、".join(f"Material.{kind}" for kind in kinds) + "material_contract= 是实验性功能(" + "、".join(f"MaterialRole.{kind}" for kind in kinds) + "):语义与写法以后可能调整", ) @@ -438,11 +467,11 @@ def material_contract(value: Any) -> Dict[str, Any]: part = role.contract_part() for key, item in part.items(): if key in raw: - raise MaterialRoleError(f"Material.{seen[key]} 与 Material.{role.kind} 不能写在同一个动作上") + raise MaterialRoleError(f"MaterialRole.{seen[key]} 与 MaterialRole.{role.kind} 不能写在同一个动作上") raw[key] = item seen[key] = role.kind if "transfer" in raw and "transfer_step" in raw: - raise MaterialRoleError(f"Material.{seen['transfer']} 与 Material.{seen['transfer_step']} 不能写在同一个动作上") + raise MaterialRoleError(f"MaterialRole.{seen['transfer']} 与 MaterialRole.{seen['transfer_step']} 不能写在同一个动作上") if len(raw) == 1: return {} try: @@ -452,7 +481,7 @@ def material_contract(value: Any) -> Dict[str, Any]: def material_site_selectors(value: Any) -> Dict[str, Dict[str, Any]]: - """``material_contract=`` 里的 ``Material.site_picker(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" + """``material_contract=`` 里的 ``MaterialRole.site_picker(...)`` → ``{库位参数名: x-unilabos-site-selector 扩展}``。""" if value is None: return {} @@ -462,7 +491,7 @@ def material_site_selectors(value: Any) -> Dict[str, Dict[str, Any]]: continue site, extension = role.site_selector() if site in selectors: - raise MaterialRoleError(f"库位参数 {site} 写了多条 Material.site_picker") + raise MaterialRoleError(f"库位参数 {site} 写了多条 MaterialRole.site_picker") selectors[site] = extension return selectors @@ -556,23 +585,26 @@ def material_roles_from_ast(value: Any) -> List[MaterialRole]: roles: List[MaterialRole] = [] for item in items: if not isinstance(item, Mapping) or "_call" not in item: - raise MaterialRoleError("material_contract= 只接受 Material.xxx(...) 或它们组成的列表(参数须是字面量)") + raise MaterialRoleError("material_contract= 只接受 MaterialRole.xxx(...) 或它们组成的列表(参数须是字面量)") call = str(item["_call"]) prefix, _, method = call.rpartition(".") module, _, owner = prefix.rpartition(":") - if owner != "Material" and prefix != "Material": - raise MaterialRoleError(f"material_contract= 只接受 Material.xxx(...),不认识 {call}") + if owner == "Material" and (not module or module in _MATERIAL_MODULES): + # 改名前的类名:与导入期的 Material 占位类同一句提示 + raise _renamed(method) + if owner != "MaterialRole": + raise MaterialRoleError(f"material_contract= 只接受 MaterialRole.xxx(...),不认识 {call}") if module and module not in _MATERIAL_MODULES: - raise MaterialRoleError(f"material_contract= 的 Material 必须从 unilabos.registry.decorators 导入,不认识 {call}") - factory = getattr(Material, method, None) if not method.startswith("_") else None - if factory is None: - raise MaterialRoleError(f"Material 没有 {method}(...)") + raise MaterialRoleError(f"material_contract= 的 MaterialRole 必须从 unilabos.registry.decorators 导入,不认识 {call}") + if method not in _FACTORY_NAMES: + raise MaterialRoleError(f"MaterialRole 没有 {method}(...)") + factory = getattr(MaterialRole, method) positional = [item[key] for key in sorted((k for k in item if k.startswith("_pos_")), key=lambda k: int(k[5:]))] keywords = {key: val for key, val in item.items() if not key.startswith("_")} try: roles.append(factory(*positional, **keywords)) except TypeError as error: - raise MaterialRoleError(f"Material.{method}(...) 参数不对:{error}") from None + raise MaterialRoleError(f"MaterialRole.{method}(...) 参数不对:{error}") from None return roles diff --git a/unilabos/registry/site_selector_schema.py b/unilabos/registry/site_selector_schema.py index 7abb5a9e56..68766fa6d7 100644 --- a/unilabos/registry/site_selector_schema.py +++ b/unilabos/registry/site_selector_schema.py @@ -1,6 +1,6 @@ -"""库位关系(``Material.site_picker(...)``)的静态跨字段校验。 +"""库位关系(``MaterialRole.site_picker(...)``)的静态跨字段校验。 -库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(material_contract=Material.site_picker(...))``:库位属于 +库位参数注解为 ``SiteSlot``,它与物料参数的关系写在 ``@action(material_contract=MaterialRole.site_picker(...))``:库位属于 哪个物料参数(``owner``)、放进去的是哪个物料参数(``occupant``)、已占用库位的显示 / 可选策略。注册表 把它写进库位参数 schema 的 ``x-unilabos-site-selector`` 扩展;本模块在生成 schema 时核对关系指向的参数。 """ @@ -59,7 +59,7 @@ def validate_site_selector_relations( if referenced_name == site_name: raise SiteSelectorSchemaError( relation_path, - "Material.site_picker 不能把库位参数自身作为 of / for_material", + "MaterialRole.site_picker 不能把库位参数自身作为 of / for_material", ) if relation_name == "owner" and referenced_name in device_parameters: continue @@ -67,7 +67,7 @@ def validate_site_selector_relations( if referenced_entry is None: raise SiteSelectorSchemaError( relation_path, - f"Material.site_picker 的 {keyword}={referenced_name!r} 必须是注解为 ResourceSlot" + f"MaterialRole.site_picker 的 {keyword}={referenced_name!r} 必须是注解为 ResourceSlot" + (" 或 DeviceSlot" if relation_name == "owner" else "") + " 的参数", ) # ``referenced`` 是 owner/occupant 指向的动作输入合同。 @@ -76,7 +76,7 @@ def validate_site_selector_relations( if not isinstance(schema, Mapping) or not _is_single_resource_slot(schema): raise SiteSelectorSchemaError( relation_path, - f"Material.site_picker 的 {keyword}={referenced_name!r} 必须是单个 ResourceSlot" + f"MaterialRole.site_picker 的 {keyword}={referenced_name!r} 必须是单个 ResourceSlot" + (" 或 DeviceSlot" if relation_name == "owner" else "") + " 参数", ) diff --git a/unilabos/registry/site_selector_value_schema.py b/unilabos/registry/site_selector_value_schema.py index 8c207ed7da..1b01a3a61b 100644 --- a/unilabos/registry/site_selector_value_schema.py +++ b/unilabos/registry/site_selector_value_schema.py @@ -98,7 +98,7 @@ def parse_site_selector_extension( "库位选择合同版本无效", ) # ``owner`` 是提供库位集合的所属方连接点字段名(ResourceSlot 物料或 DeviceSlot 设备); - # ``None`` 表示执行设备的根节点(``Material.site_picker`` 省略 ``of``)。 + # ``None`` 表示执行设备的根节点(``MaterialRole.site_picker`` 省略 ``of``)。 raw_owner = raw_selector["owner"] owner = ( None diff --git a/unilabos/server/api/envelope.py b/unilabos/server/api/envelope.py index 5e2b8e11e8..69774ec432 100644 --- a/unilabos/server/api/envelope.py +++ b/unilabos/server/api/envelope.py @@ -330,7 +330,7 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "material_site_invalid", # 工作流物料输入直接给的物料不是 @workflow(allowed_templates=...) 允许的模板(细节在 error.details) "material_template_mismatch", - # 库位参数按所属物料选择的写法不对(没有 Material.site_picker 关系、放入物料不确定……,细节在 error.details) + # 库位参数按所属物料选择的写法不对(没有 MaterialRole.site_picker 关系、放入物料不确定……,细节在 error.details) "site_selection_invalid", }) diff --git a/unilabos/server/scheduler/physical_contract.py b/unilabos/server/scheduler/physical_contract.py index 24123cb9a0..9ed5e07410 100644 --- a/unilabos/server/scheduler/physical_contract.py +++ b/unilabos/server/scheduler/physical_contract.py @@ -1,7 +1,7 @@ """将动作资源合同解析为权威物料、完整库位和托管范围。 -``Material.move`` / ``pick`` / ``place`` 规范化成 ``transfer`` / ``transfer_step``:目标与来源按库位 uuid 给出时, -所属方(载架或设备根节点)由库位决定;库位参数带 ``Material.site_picker(of=...)`` 关系时,值也可以是所属方下的 +``MaterialRole.move`` / ``pick`` / ``place`` 规范化成 ``transfer`` / ``transfer_step``:目标与来源按库位 uuid 给出时, +所属方(载架或设备根节点)由库位决定;库位参数带 ``MaterialRole.site_picker(of=...)`` 关系时,值也可以是所属方下的 库位名(工作流里写死的工位;库位 uuid 由物料权威建树时发号,不能写死)。搬运设备参数(``DeviceSlot``,设备 id) 解析成该设备的物料,省略时是执行设备。旧合同里显式的所属物料参数(ResourceSlot)照旧可用。 """ @@ -45,7 +45,7 @@ def device_material_uuid(materials: Any, device_id: str) -> str: def site_picker_owner( schema: Mapping[str, Any] | None, values: Mapping[str, Any], name: str, materials: Any, device_id: str | None, ) -> str | None: - """库位参数 ``name`` 的 ``Material.site_picker`` 所属方 → 所属物料 uuid;没有这层关系或所属方未给时为 ``None``。 + """库位参数 ``name`` 的 ``MaterialRole.site_picker`` 所属方 → 所属物料 uuid;没有这层关系或所属方未给时为 ``None``。 ``of`` 是 ``ResourceSlot`` 时取它的物料 uuid,是 ``DeviceSlot`` 时取设备根节点,省略时是执行设备根节点。 """ @@ -66,7 +66,7 @@ def site_picker_owner( def site_by_label( schema: Mapping[str, Any] | None, values: Mapping[str, Any], name: str, materials: Any, device_id: str | None, ) -> tuple[str, str] | None: - """库位参数的值不是已登记的库位 uuid 时(工作流里写死的库位名或序号):在 ``Material.site_picker`` 的所属方下 + """库位参数的值不是已登记的库位 uuid 时(工作流里写死的库位名或序号):在 ``MaterialRole.site_picker`` 的所属方下 唯一匹配,返回 ``(所属物料 uuid, 库位 uuid)``;没有 site_picker 关系或匹配不唯一时为 ``None``。""" selected = values.get(name) @@ -142,7 +142,7 @@ def site(owner, selected): def site_by_uuid(name): """库位参数(``SiteSlot``)→ ``(所属物料, 库位)``:库位 uuid 的所属方由库位决定; - 带 ``Material.site_picker`` 关系时也可以是所属方下的库位名。""" + 带 ``MaterialRole.site_picker`` 关系时也可以是所属方下的库位名。""" selected = values.get(name) if not isinstance(selected, str) or not selected.strip(): @@ -152,7 +152,7 @@ def site_by_uuid(name): found = site_by_label(schema, values, name, materials, device_id) if found is None: raise ValueError(f"库位参数 {name} 指向不存在的库位 {selected}" - "(不是库位 uuid,也不是 Material.site_picker 所属方下唯一的库位名)") + "(不是库位 uuid,也不是 MaterialRole.site_picker 所属方下唯一的库位名)") owner, selected = found return owner, site(owner, selected) diff --git a/unilabos/server/scheduler/physical_recovery.py b/unilabos/server/scheduler/physical_recovery.py index 73aaae4a7c..88919cac12 100644 --- a/unilabos/server/scheduler/physical_recovery.py +++ b/unilabos/server/scheduler/physical_recovery.py @@ -115,9 +115,9 @@ def settle(self, job_uuid, *, job_status, return_info, error_info, resolution): def _receipt(record, value, *, planned_moves=False): """设备结果 → 结算回执。 - ``planned_moves``:动作成功时,声明的搬运(``Material.move`` / ``pick`` / ``place``)由核心按冻结计划结算—— + ``planned_moves``:动作成功时,声明的搬运(``MaterialRole.move`` / ``pick`` / ``place``)由核心按冻结计划结算—— 结果里没有 ``material_transfer_receipts`` 就用冻结的搬运;给了就必须与冻结计划完全一致。人工补记结算不按计划补。 - 分装(``Material.dispense``)的实际量只能由驱动回报,始终要求 ``material_aliquot_receipts``。 + 分装(``MaterialRole.dispense``)的实际量只能由驱动回报,始终要求 ``material_aliquot_receipts``。 """ request = record["request"] diff --git a/unilabos/server/scheduler/tenancy_contract.py b/unilabos/server/scheduler/tenancy_contract.py index 0723e60e8b..8741ba6f88 100644 --- a/unilabos/server/scheduler/tenancy_contract.py +++ b/unilabos/server/scheduler/tenancy_contract.py @@ -1,10 +1,10 @@ """从冻结的动作合同和实际参数解析托管与按类型的设备 / 库位锁;设备使用物料权威的可读 resource_id。 -- 设备托管(``Material.load`` / ``unload``,实验性):设备参数是 ``DeviceSlot``,省略时(合同里的 +- 设备托管(``MaterialRole.load`` / ``unload``,实验性):设备参数是 ``DeviceSlot``,省略时(合同里的 ``EXECUTING_DEVICE`` 记号)是执行设备; - 按类型加锁:``DeviceSlot`` / ``list[DeviceSlot]`` 参数加设备锁(``device_claims``),``SiteSlot`` 参数加库位锁 (``site_claims``,按「所属物料 + 库位」);字段由注册表标出 ``x-unilabos-slot``。空值不加锁;库位参数的值是 - ``Material.site_picker`` 所属方下的库位名时按解析出的库位加锁,解析不出时不加库位锁。 + ``MaterialRole.site_picker`` 所属方下的库位名时按解析出的库位加锁,解析不出时不加库位锁。 """ from unilabos.registry.action_resource_contract import EXECUTING_DEVICE from unilabos.server.scheduler.models import DeviceTenancyTransition, DeviceTenancyRequirement, SiteLockClaim @@ -30,7 +30,7 @@ def _slot_values(value) -> list[str]: def resolve_site_claims(schema: dict | None, values: dict, materials, device_id: str | None = None) -> list[SiteLockClaim]: """``SiteSlot`` 参数 → 库位锁(所属物料 + 库位)。 - 值是库位 uuid 时所属方由库位决定;是 ``Material.site_picker`` 所属方下的库位名时按解析出的库位加锁; + 值是库位 uuid 时所属方由库位决定;是 ``MaterialRole.site_picker`` 所属方下的库位名时按解析出的库位加锁; 两者都解析不出时不加锁(派发前的物料 / 物理合同会报错)。 """ diff --git a/unilabos/server/services/runtime/workflow/run_preflight.py b/unilabos/server/services/runtime/workflow/run_preflight.py index 3f2a239ea9..64d2bafe83 100644 --- a/unilabos/server/services/runtime/workflow/run_preflight.py +++ b/unilabos/server/services/runtime/workflow/run_preflight.py @@ -285,7 +285,7 @@ def validate_resource_values( schema: Mapping[str, Any], values: Mapping[str, Any], materials: Any, *, deferred: Sequence[str] = (), device_id: str | None = None, ) -> None: - """校验已知物料身份、设备参数及库位参数(Material.site_picker 声明的库位关系)的归属/占用;预检与派发共用。 + """校验已知物料身份、设备参数及库位参数(MaterialRole.site_picker 声明的库位关系)的归属/占用;预检与派发共用。 ``device_id`` 是执行设备:``site_picker`` 省略 ``of`` 时库位属于它的根节点(不给时跳过这条核对)。 """ diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 1b9aab8df4..7da297fecd 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -1534,7 +1534,7 @@ def build_plan(graph: Dict[str, Any]) -> Any: # 按库位绑定的物料参数解析成占用物料,计划、attempt 参数与任务输入一起冻结 self._bind_material_sites(plan, jobs, resolved["input"], site_facts, input_contract=declared_input_contract(graph["workflow"])) - # 按所属物料选择的库位参数在任务准入时由调度器选定;写法不对(没有 Material.site_picker 关系、放入物料不确定、 + # 按所属物料选择的库位参数在任务准入时由调度器选定;写法不对(没有 MaterialRole.site_picker 关系、放入物料不确定、 # 与所属物料参数不一致)建任务时就拒绝 self._check_site_selections(plan) try: diff --git a/unilabos/server/services/runtime/workflow/site_selections.py b/unilabos/server/services/runtime/workflow/site_selections.py index 92fbb02de9..a6cf3178ac 100644 --- a/unilabos/server/services/runtime/workflow/site_selections.py +++ b/unilabos/server/services/runtime/workflow/site_selections.py @@ -1,9 +1,9 @@ """库位参数按所属物料选择:``{"owner_uuid": ...}`` 在任务准入时选定一个库位、经入口预留占住并冻结进任务。 -``SiteSlot`` 参数(带 ``Material.site_picker("site", of=..., for_material=...)`` 关系)可以给 +``SiteSlot`` 参数(带 ``MaterialRole.site_picker("site", of=..., for_material=...)`` 关系)可以给 ``{"owner_uuid": "<所属物料 uuid>"}`` 而不是库位 uuid,工作流入口参数(``SiteSlot``)也可以。规则: -- 候选是所属物料下接受放入物料(``Material.site_picker`` 的 ``for_material`` 参数,按库位绑定的已先解析)的库位: +- 候选是所属物料下接受放入物料(``MaterialRole.site_picker`` 的 ``for_material`` 参数,按库位绑定的已先解析)的库位: 库位的接收规则(模板白名单与允许的资源类别)要接受它;按库位序号选第一个空着、没有被别的任务预留的; - 调度器在任务准入时(``BackendScheduler._admit_fresh_task``)用物料权威的入口预留占住选中的库位 (``owner_material_uuid`` 写法,预留随任务:``backend_task_uuid`` = 任务 uuid),再把库位 uuid 冻结进计划节点参数、 @@ -126,12 +126,12 @@ def owner_site_requests(plan: Mapping[str, Any]) -> list[SiteSelectionRequest]: selector = (fields.get(name) or {}).get("x-unilabos-site-selector") if not isinstance(selector, Mapping): raise SiteSelectionError( - NO_SITE_RELATION, f"{where} 按所属物料 {owner} 选库位:动作没有用 Material.site_picker 声明这个库位参数的关系," + NO_SITE_RELATION, f"{where} 按所属物料 {owner} 选库位:动作没有用 MaterialRole.site_picker 声明这个库位参数的关系," "选不出接受放入物料的库位;请给库位 uuid", parameter=name, owner_uuid=owner, node_uuid=node_uuid) occupant_param = selector.get("occupant") if not occupant_param: raise SiteSelectionError( - OCCUPANT_UNDECLARED, f"{where} 按所属物料 {owner} 选库位:Material.site_picker 没有声明 for_material(放进去的物料)," + OCCUPANT_UNDECLARED, f"{where} 按所属物料 {owner} 选库位:MaterialRole.site_picker 没有声明 for_material(放进去的物料)," "无法按库位的接收规则挑选", parameter=name, owner_uuid=owner, node_uuid=node_uuid) upstream = _upstream_parameters(plan, node_uuid) occupant = None if occupant_param in upstream else _material_uuid(param.get(occupant_param)) From 6c39635636b6e98c74654a71d1d78636671dc0f0 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:11:21 +0800 Subject: [PATCH 26/27] docs: write resource semantics with MaterialRole.xxx(...) The guides, skills and AGENTS.md use MaterialRole; the removed old forms keep their original Material. spelling. The breaking-changes table gets a row for the Material class name, and the material= row points at material_contract=MaterialRole.xxx(...). --- .cursor/skills/add-device/SKILL.md | 10 +-- .cursor/skills/create-device-package/SKILL.md | 34 ++++---- AGENTS.md | 2 +- docs/developer_guide/action_standard.md | 81 ++++++++++--------- docs/developer_guide/add_device.md | 2 +- .../scheduling_and_execution.md | 2 +- docs/developer_guide/v1_file_index/rest.md | 8 +- .../v1_file_index/scheduler.md | 2 +- .../workflow_resource_custody.md | 8 +- .../workflow_static_conditions.md | 2 +- 10 files changed, 76 insertions(+), 75 deletions(-) diff --git a/.cursor/skills/add-device/SKILL.md b/.cursor/skills/add-device/SKILL.md index 7bb71f10ed..16be0b209c 100644 --- a/.cursor/skills/add-device/SKILL.md +++ b/.cursor/skills/add-device/SKILL.md @@ -159,16 +159,16 @@ from unilabos.registry.decorators import action auto_prefix=True, # 强制使用 auto- 前缀 parent=True, # 从父类 MRO 获取参数签名 ) -@action(material_contract=Material.move("plate", to_site="target_site")) # 资源语义(实验性):一个字段,见下 +@action(material_contract=MaterialRole.move("plate", to_site="target_site")) # 资源语义(实验性):一个字段,见下 ``` JSON 动作(不写 `action_type`)的参数与返回值只有一个标准:注册表按签名生成 schema,调度端与 Host 调用前按它校验参数, 调用后按返回注解校验返回值。写了类型的参数严格校验;没写类型或 `Any` 接受任意 JSON 值;没有默认值的参数必填。 -资源语义用 `material_contract=`,声明动作真实的物料动作 `Material.move / pick / place / dispense(...)`,多个写成列表; -不代表物料动作的 `Material.load / unload / in_place / site_picker / order_sensitive(...)` 也写在这里。整个 `material_contract=` 字段是实验性功能 -(写了就按定义告警一次);改名前的 `material=` 注册时报错。 +资源语义用 `material_contract=`,声明动作真实的物料动作 `MaterialRole.move / pick / place / dispense(...)`,多个写成列表; +不代表物料动作的 `MaterialRole.load / unload / in_place / site_picker / order_sensitive(...)` 也写在这里。整个 `material_contract=` 字段是实验性功能 +(写了就按定义告警一次);改名前的 `material=` 与声明类 `Material`(现在叫 `MaterialRole`,区别于运行时的 `unilabos.resources.materials`)注册时报错。 字符串都是参数名:物料 `ResourceSlot`、库位 `SiteSlot`(库位 uuid,所属方由库位决定)、设备 `DeviceSlot`(省略即执行设备)。 -库位选择器列出哪个所属方的库位写 `Material.site_picker("site", of="carrier", for_material="sample")`。 +库位选择器列出哪个所属方的库位写 `MaterialRole.site_picker("site", of="carrier", for_material="sample")`。 `DeviceSlot` 参数加设备锁、`SiteSlot` 参数加库位锁,不需要额外声明。 前端选择器:物料 `ResourceSlot`、设备 `DeviceSlot`、库位 `SiteSlot` 自动推出,其他(节点、人工确认指派人、扣减……)或想换一种 显示时写 `@action(placeholder_keys={"参数名": PLACEHOLDER_...})`,两者取并集、同一参数以手写为准,只改显示不改类型。 diff --git a/.cursor/skills/create-device-package/SKILL.md b/.cursor/skills/create-device-package/SKILL.md index 4e80cacce6..247f651bf9 100644 --- a/.cursor/skills/create-device-package/SKILL.md +++ b/.cursor/skills/create-device-package/SKILL.md @@ -117,13 +117,13 @@ class : - `always_free=True`:动作不占用设备 busy 队列,适合 `get_status`、`query_*`、`ping`、连接测试等轻量查询动作;会在 `action_value_mappings..always_free` 中写入 `true`。 - `feedback_interval`:动作反馈发布间隔,单位秒;AST 扫描默认补 `1.0`,长任务可调大,例如 `5.0`、`30.0`。 - `goal_default`:编辑器里的初始参数值,叠加在签名默认值上;它不让参数变成可选,没有签名默认值的参数仍然必填。 -- `material_contract`(实验性,写了就按定义告警一次):资源语义(搬运、两步搬运、分装;以及装载托管、原位处理、库位选择器提示、顺序敏感),一个字段,值是 `Material` 的一个方法或列表,见下文「资源语义」。 +- `material_contract`(实验性,写了就按定义告警一次):资源语义(搬运、两步搬运、分装;以及装载托管、原位处理、库位选择器提示、顺序敏感),一个字段,值是 `MaterialRole` 的一个方法或列表,见下文「资源语义」。 - `placeholder_keys`:前端选择器 `{参数名: PLACEHOLDER_...}`。物料 `ResourceSlot`、设备 `DeviceSlot`、库位 `SiteSlot` 由类型自动推出; 节点、人工确认指派人、扣减等没有专门类型的选择器,或想把某个参数换一种显示,就在这里手写。两者取并集,同一参数以手写为准; 只改前端显示,参数类型与校验不变(兼容规则:手写成 `unilabos_resources` 的参数也加物料锁)。键必须是参数名。 - `handles`:动作级输入/输出端口,使用 `ActionInputHandle`、`ActionOutputHandle`;不写时按 schema 生成。 -- 已删除、写了会报错的写法:`contract=`、`resource_contract=`、改名前的 `material=`(改成 `material_contract=`,值不变)、JSON 动作的 `goal=` / `result=` 重命名(参数名就是字段名), - 注解里的 `Placeholder(...)`(改成 `placeholder_keys=`)与 `SiteSelector(...)`(改成 `SiteSlot` + `Material.site_picker(...)`), +- 已删除、写了会报错的写法:`contract=`、`resource_contract=`、改名前的 `material=`(改成 `material_contract=`,值不变)、改名前的声明类 `Material`(改成 `MaterialRole`,方法不变;`Material` 仍可导入,但 `Material.xxx(...)` 直接报错)、JSON 动作的 `goal=` / `result=` 重命名(参数名就是字段名), + 注解里的 `Placeholder(...)`(改成 `placeholder_keys=`)与 `SiteSelector(...)`(改成 `SiteSlot` + `MaterialRole.site_picker(...)`), 以及 `Material.transfer / aliquot / site / uses`、带 `owner` / `site` / `carriers` 的 `Material.pick / place`(新写法见下文「资源语义」)。 参数与返回值只有一个标准,注册表按签名生成 schema,调度端与 Host 调用前校验参数,调用后按返回注解校验返回值: @@ -147,19 +147,19 @@ class : #### 资源语义:`material_contract=`(实验性) ```python -from unilabos.registry.decorators import Material, action +from unilabos.registry.decorators import MaterialRole, action from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="搬运板", material_contract=Material.move("plate", to_site="target_site")) +@action(display_name="搬运板", material_contract=MaterialRole.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="抓取", material_contract=Material.pick("plate")) +@action(display_name="抓取", material_contract=MaterialRole.pick("plate")) def pick_plate(self, plate: ResourceSlot) -> dict: ... -@action(display_name="放下", material_contract=Material.place("plate", to_site="target_site")) +@action(display_name="放下", material_contract=MaterialRole.place("plate", to_site="target_site")) def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="原位搅拌", material_contract=[Material.in_place("sample"), Material.order_sensitive()]) +@action(display_name="原位搅拌", material_contract=[MaterialRole.in_place("sample"), MaterialRole.order_sensitive()]) def stir(self, sample: ResourceSlot, rpm: int = 300) -> None: ... ``` @@ -167,19 +167,19 @@ def stir(self, sample: ResourceSlot, rpm: int = 300) -> None: ... | 写法 | 含义 | | --- | --- | -| `Material.move("plate", to_site="site", from_site=None, carrier_device=None)` | 一个动作把容器搬到 `to_site`;所属方由库位决定,搬运途中在搬运设备的 `gripper` 夹爪库位上 | -| `Material.pick("plate", from_site=None, carrier_device=None)` | 两步搬运第一步:抓到搬运设备的夹爪库位,任务托管搬运设备 | -| `Material.place("plate", to_site="site", carrier_device=None)` | 两步搬运第二步:从夹爪库位放到 `to_site`,结束托管 | -| `Material.dispense(from_material="source", to_materials=["target", ...])` | 按实测量在容器之间转移内容物 | +| `MaterialRole.move("plate", to_site="site", from_site=None, carrier_device=None)` | 一个动作把容器搬到 `to_site`;所属方由库位决定,搬运途中在搬运设备的 `gripper` 夹爪库位上 | +| `MaterialRole.pick("plate", from_site=None, carrier_device=None)` | 两步搬运第一步:抓到搬运设备的夹爪库位,任务托管搬运设备 | +| `MaterialRole.place("plate", to_site="site", carrier_device=None)` | 两步搬运第二步:从夹爪库位放到 `to_site`,结束托管 | +| `MaterialRole.dispense(from_material="source", to_materials=["target", ...])` | 按实测量在容器之间转移内容物 | 不代表物料动作的声明: | 写法 | 含义 | | --- | --- | -| `Material.load("sample", device=None, from_device=None)` / `Material.unload("sample", device=None)` | 装进 / 取出设备,期间任务托管设备;`device` 省略即执行设备,`from_device` 表示设备间转移 | -| `Material.in_place("sample")` | 物料必须仍在执行设备内 | -| `Material.site_picker("site", of=None, for_material=None, occupied="show")` | 库位选择器提示:`site` 列出 `of`(省略即执行设备根节点)的库位,放进去的是 `for_material`;`occupied` 取 `"hide"` / `"show"` / `"allow"` | -| `Material.order_sensitive()` | 同一资源上的兄弟动作必须显式排序 | +| `MaterialRole.load("sample", device=None, from_device=None)` / `MaterialRole.unload("sample", device=None)` | 装进 / 取出设备,期间任务托管设备;`device` 省略即执行设备,`from_device` 表示设备间转移 | +| `MaterialRole.in_place("sample")` | 物料必须仍在执行设备内 | +| `MaterialRole.site_picker("site", of=None, for_material=None, occupied="show")` | 库位选择器提示:`site` 列出 `of`(省略即执行设备根节点)的库位,放进去的是 `for_material`;`occupied` 取 `"hide"` / `"show"` / `"allow"` | +| `MaterialRole.order_sensitive()` | 同一资源上的兄弟动作必须显式排序 | 字符串都是参数名,注册时对照签名检查:物料(`material`、`from_material`、`to_materials`、`for_material`)必须是单个 `ResourceSlot`; 库位(`to_site`、`from_site`、`site_picker` 的库位参数)必须是 `SiteSlot`(值是库位 uuid);设备(`carrier_device`、`device`、 @@ -187,7 +187,7 @@ def stir(self, sample: ResourceSlot, rpm: int = 300) -> None: ... 搬运设备的夹爪库位 `meta_data.role` 统一为 `gripper`(有且只有一个)。参数按类型加锁:`ResourceSlot` 物料锁、`DeviceSlot` 设备锁、 `SiteSlot` 库位锁。 -用 `Material.move / pick / place` 声明了的搬运由核心按回执结算物料位置,驱动不要再对同一物料调用 `materials.transfer` / +用 `MaterialRole.move / pick / place` 声明了的搬运由核心按回执结算物料位置,驱动不要再对同一物料调用 `materials.transfer` / `materials.assign`;`materials.*` 只用于没有声明的运行时变化(新建、写内容物、删除、启动对齐等)。 ### 3.2 `@topic_config` 规则 diff --git a/AGENTS.md b/AGENTS.md index 46f4340d1f..608b32b6e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ pytest tests/resources/test_resourcetreeset_groups.py::test_name # single test ### Core Layers -**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one experimental decorator field, `@action(material_contract=Material.move(...) | [...])` (`registry/material_roles.py`; any use warns once per definition; the old field name `material=` and the short-lived `materials=` are rejected with the new spelling): the material actions are `Material.move` / `pick` / `place` / `dispense` (sites are `SiteSlot` uuids whose owner the scheduler derives from the site, carriers are `DeviceSlot` parameters defaulting to the executing device and its `gripper` site); `load` / `unload` / `in_place` / `site_picker` / `order_sensitive` are the declarations that are not material actions. A site parameter is annotated `SiteSlot`; `Material.site_picker(...)` writes the selector hint into that field's `x-unilabos-site-selector` extension. `Material.transfer` / `aliquot` / `site` / `uses` and `pick` / `place` with `owner` / `site` / `carriers` are rejected with the new spelling. Parameters are locked by type: `ResourceSlot` material locks, `DeviceSlot` device locks, `SiteSlot` site locks. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, the old `material=` / `materials=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. +**Registry** (`unilabos/registry/`): Singleton `Registry` class discovers and catalogs all device types, resource types, and communication devices from YAML definitions. Device types live in `registry/devices/**/*.yaml`, resources in `registry/resources/`, comms in `registry/device_comms/` (all read recursively; a declared `category` is kept, the file stem is only the fallback). The registry resolves class paths to actual Python classes via `utils/import_manager.py`. Loading is ordered: files merge in sorted path order and entries in declaration order, independent of thread timing and the string hash seed (the first YAML file wins a duplicate id). Unless the backend is `ros2` (for library use and `--check_mode`: unless ROS 2 is installed), the registry build never imports `unilabos.client.host.ros2.*` or `unilabos.devices.ros_dev.*` and does not scan `devices/ros_dev`; the ROS 2 presets (`camera`, `serial`) stay registered so HostLink can mark such graph nodes unavailable (`registry.py:ros2_core_enabled`). Every JSON action (`@action()` without `action_type`, and `auto-` methods) gets one signature-derived schema (`registry/action_schema.py`: the AST scan builds a draft per parameter with the strict annotation parser, unknown annotations fall back to the registry's signature inference in `Registry._infer_annotation_schema`), carrying the `x-unilabos-action-contract` v2 envelope; the scheduler, run preflight and the Host validate arguments and results against it (`registry/typed_contract.py`). Resource semantics are one experimental decorator field, `@action(material_contract=MaterialRole.move(...) | [...])` (`registry/material_roles.py`; the factories live on the frozen `MaterialRole` dataclass they return, named apart from the runtime `unilabos.resources.materials`; any use warns once per definition; the old field name `material=`, the short-lived `materials=` and the old class name `Material` — still importable, but `Material.xxx(...)` fails at import and in the AST scan — are rejected with the new spelling): the material actions are `MaterialRole.move` / `pick` / `place` / `dispense` (sites are `SiteSlot` uuids whose owner the scheduler derives from the site, carriers are `DeviceSlot` parameters defaulting to the executing device and its `gripper` site); `load` / `unload` / `in_place` / `site_picker` / `order_sensitive` are the declarations that are not material actions. A site parameter is annotated `SiteSlot`; `MaterialRole.site_picker(...)` writes the selector hint into that field's `x-unilabos-site-selector` extension. `Material.transfer` / `aliquot` / `site` / `uses` and `pick` / `place` with `owner` / `site` / `carriers` are rejected with the new spelling. Parameters are locked by type: `ResourceSlot` material locks, `DeviceSlot` device locks, `SiteSlot` site locks. Frontend selectors: the entry's `placeholder_keys` is the type-derived set (`ResourceSlot` / `DeviceSlot` / `SiteSlot`) united with `@action(placeholder_keys={...})`, the hand-written kind winning per parameter (`registry/placeholder_keys.py`); it changes only the display. The material lock is a union: `ResourceSlot` parameters plus every parameter whose merged selector is `unilabos_resources`, which is how signature-less YAML and ROS / protocol entries mark their materials. `contract=`, `resource_contract=`, the old `material=` / `materials=`, JSON-action `goal=` / `result=` renames, the removed `Placeholder` / `SiteSelector` annotations and an `action_context` parameter without the `ActionContext` annotation are rejected by both the decorator and the scan (`registry/action_options.py`). The framework injects `ActionContext` by type: any parameter annotated `ActionContext`, `Optional[ActionContext]` or `ActionContext | None` gets it (the optional forms get `None` when there is no context, e.g. under ROS 2), and such parameters are excluded from the schema, handles, `placeholder_keys`, material locks and `goal_default` (`registry/action_context.py`, `client/host/runtime/action.py:bind_action_context`). Rules: `docs/developer_guide/action_standard.md`. **Resource Tracking** (`unilabos/resources/resource_tracker.py`): Pydantic-based `ResourceDict` → `ResourceDictInstance` → `ResourceTreeSet` hierarchy. `ResourceTreeSet` is the canonical in-memory representation of all devices and resources, used throughout the system, and it owns every resource conversion: flat dicts (`from_raw_dict_list`, `dump`/`load`) and PLR (`from_plr_resources`, `to_plr_resources`). PLR drafts from a registry resource class come from `resources/materials.py:instantiate_registry_resource`. There is no separate graph I/O module: device graphs are node-link JSON only (GraphML is not supported) and are turned into runtime structures by the Graph Authority (`server/services/materials/graph.py:load_graph_payload`). diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index ff0836562d..b9f8e7bb5e 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -17,7 +17,7 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) | `Annotated[X, Field(ge=, le=, min_length=, max_length=, title=, description=)]` | 带范围与说明 | 严格 | | `ResourceSlot` / `list[ResourceSlot]` | 物料引用 `{"uuid": ...}`(或按库位绑定的 `{"site_uuid": ...}`,准入时解析),加物料锁 | 严格;Host 解析成物料实例 | | `DeviceSlot` / `SiteSlot` | 设备 ID / 库位 UUID 字符串(字段带 `x-unilabos-slot: "device"` / `"site"`),加设备锁 / 库位锁 | 严格 | -| `SiteSlot` 且写了 `material_contract=Material.site_picker("site", of=...)` | 库位 UUID、所属方下的库位名(工作流里写死的工位,派发前解析成库位 uuid),或按所属物料选择的 `{"owner_uuid": ...}`(准入时选定);带库位关系(`x-unilabos-site-selector`),不限定 uuid 格式 | 严格;预检与派发前核对库位归属与占用 | +| `SiteSlot` 且写了 `material_contract=MaterialRole.site_picker("site", of=...)` | 库位 UUID、所属方下的库位名(工作流里写死的工位,派发前解析成库位 uuid),或按所属物料选择的 `{"owner_uuid": ...}`(准入时选定);带库位关系(`x-unilabos-site-selector`),不限定 uuid 格式 | 严格;预检与派发前核对库位归属与占用 | | `dict`、`Dict[str, Any]`、`Mapping` | 任意 JSON 对象 | 只校验是对象 | | 没写注解、`Any`、`object` | 任意 JSON 值(`{}`) | 不限值 | | 严格解析器不认识的注解(`Union[int, str]`、`List[Optional[float]]`、枚举、PLR / pydantic 类型……) | 退回注册表原来的签名类型推断 | 按推断结果;推断不出的部分接受任意值 | @@ -99,11 +99,11 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 以后可能调整」,装饰器(导入时)与注册表 AST 扫描共用同一身份,同一定义只告警一次。改名前的 `material=`(见「不兼容变更」) 与短暂出现过的 `materials=` 注册时都直接报错并提示改成 `material_contract=`,不会被静默忽略。 -`Material` 声明的是动作**真实的物料动作**:搬运一件容器、两步搬运、在容器之间转移内容物。调度器在派发前按它解析 +`MaterialRole` 声明的是动作**真实的物料动作**:搬运一件容器、两步搬运、在容器之间转移内容物。调度器在派发前按它解析 来源、目标与搬运设备,动作成功后由核心一次结算物料位置 / 内容物(`PhysicalMove` / 搬运回执、`AliquotReceipt`)。 不代表物料动作的声明(跨动作的设备独占、原位检查、库位选择器提示、顺序约束)也写在 `material_contract=` 里。 -一个动作的语义只用 `@action` 的这一个字段声明,值是 `Material` 的一个方法调用,多个语义写成列表。 +一个动作的语义只用 `@action` 的这一个字段声明,值是 `MaterialRole` 的一个方法调用,多个语义写成列表。 字符串参数都是动作的参数名,注册时对照签名检查参数存在、类型正确: | 角色 | 参数类型 | 值 | @@ -113,19 +113,19 @@ schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输 | 设备(`carrier_device`、`device`、`from_device`) | `DeviceSlot` | 设备 id;省略就是**执行设备** | ```python -from unilabos.registry.decorators import Material, action +from unilabos.registry.decorators import MaterialRole, action from unilabos.registry.placeholder_type import DeviceSlot, ResourceSlot, SiteSlot -@action(display_name="搬运板", material_contract=Material.move("plate", to_site="target_site")) +@action(display_name="搬运板", material_contract=MaterialRole.move("plate", to_site="target_site")) def move_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="抓取", material_contract=Material.pick("plate")) +@action(display_name="抓取", material_contract=MaterialRole.pick("plate")) def pick_plate(self, plate: ResourceSlot) -> dict: ... -@action(display_name="放下", material_contract=Material.place("plate", to_site="target_site")) +@action(display_name="放下", material_contract=MaterialRole.place("plate", to_site="target_site")) def place_plate(self, plate: ResourceSlot, target_site: SiteSlot) -> dict: ... -@action(display_name="移液", material_contract=Material.dispense(from_material="source", to_materials=["target"])) +@action(display_name="移液", material_contract=MaterialRole.dispense(from_material="source", to_materials=["target"])) def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: float) -> dict: ... ``` @@ -133,10 +133,10 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl | 写法 | 含义 | 内部合同字段 | | --- | --- | --- | -| `Material.move("plate", to_site="target_site", from_site=None, carrier_device=None)` | 一个动作把容器搬到 `to_site` | `transfer` | -| `Material.pick("plate", from_site=None, carrier_device=None)` | 两步搬运第一步:从来源库位抓到搬运设备的夹爪库位 | `transfer_step`(pick) | -| `Material.place("plate", to_site="target_site", carrier_device=None)` | 两步搬运第二步:从夹爪库位放到 `to_site` | `transfer_step`(place) | -| `Material.dispense(from_material="source", to_materials=["target", ...])` | 按驱动回报的实际量,在容器之间转移内容物 | `aliquot`(`AliquotReceipt`) | +| `MaterialRole.move("plate", to_site="target_site", from_site=None, carrier_device=None)` | 一个动作把容器搬到 `to_site` | `transfer` | +| `MaterialRole.pick("plate", from_site=None, carrier_device=None)` | 两步搬运第一步:从来源库位抓到搬运设备的夹爪库位 | `transfer_step`(pick) | +| `MaterialRole.place("plate", to_site="target_site", carrier_device=None)` | 两步搬运第二步:从夹爪库位放到 `to_site` | `transfer_step`(place) | +| `MaterialRole.dispense(from_material="source", to_materials=["target", ...])` | 按驱动回报的实际量,在容器之间转移内容物 | `aliquot`(`AliquotReceipt`) | - **所属方由库位决定**:`to_site` / `from_site` 是库位 uuid,调度器向物料权威读出库位的所属方——可以是载架 (仓库、板位……),也可以是设备根节点(设备自身的库位),不再单独写所属物料参数。 @@ -154,11 +154,11 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl (一个动作只能有一种搬运声明),`dispense` 可以与下面不代表物料动作的声明同时写。 - 物料的**消耗 / 新建**这次不做声明式写法:消耗仍然用工作流节点上的 `inventory=`,新建仍在驱动里调用 `materials.create`(见下节)。 -### 声明式 `Material` 与运行时 `materials` 的分工 +### 声明式 `MaterialRole` 与运行时 `materials` 的分工 两者都会改变物料权威里的事实,但时机和归属不同: -| | 声明式 `Material`(`registry/material_roles.py`) | 运行时 `materials`(`unilabos.resources.materials`) | +| | 声明式 `MaterialRole`(`registry/material_roles.py`) | 运行时 `materials`(`unilabos.resources.materials`) | | --- | --- | --- | | 写在哪里 | `@action(material_contract=...)` | 驱动代码里,动作执行时调用 | | 谁读 / 谁执行 | 调度器派发前读:解析来源、目标、搬运设备,加锁、预留库位;动作成功后**核心**结算 | 驱动直接调用,立即改权威 | @@ -166,7 +166,7 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl 规则: -- 用 `Material.move` / `pick` / `place` 声明了的搬运,物料位置由核心结算;驱动**不能**再对同一件物料调用 +- 用 `MaterialRole.move` / `pick` / `place` 声明了的搬运,物料位置由核心结算;驱动**不能**再对同一件物料调用 `materials.transfer` / `materials.assign`(会重复写位置,与核心的结算冲突)。驱动只负责物理动作:动作成功而结果里 没有 `material_transfer_receipts` 时,核心按派发前冻结的来源 / 目标结算;驱动给了搬运回执,就必须与冻结计划完全一致 (否则结算被拒绝,转人工核实)。人工补记结算(任务终止后)仍要逐条给出实际位置。 @@ -181,11 +181,11 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl | 写法 | 含义 | 内部合同字段 | | --- | --- | --- | -| `Material.load("sample", device=None, from_device=None)` | 装进设备,任务托管设备直到卸载;`from_device` 同时从另一台设备转出 | `device_tenancy`(取得设备,可同时释放 `from_device`) | -| `Material.unload("sample", device=None)` | 从设备取出,结束托管 | `device_tenancy`(释放设备) | -| `Material.in_place("sample")` | 物料必须仍在执行设备内(由之前的 `load` 托管着) | `operate_in_place` | -| `Material.site_picker("site", of=None, for_material=None, occupied="show")` | 前端库位选择器提示:库位参数 `site` 列出 `of` 的库位 | 不进资源合同:写进 `site` 参数 schema 的 `x-unilabos-site-selector` | -| `Material.order_sensitive()` | 同一资源上的兄弟动作必须显式排序(只约束计划) | `order_sensitive` | +| `MaterialRole.load("sample", device=None, from_device=None)` | 装进设备,任务托管设备直到卸载;`from_device` 同时从另一台设备转出 | `device_tenancy`(取得设备,可同时释放 `from_device`) | +| `MaterialRole.unload("sample", device=None)` | 从设备取出,结束托管 | `device_tenancy`(释放设备) | +| `MaterialRole.in_place("sample")` | 物料必须仍在执行设备内(由之前的 `load` 托管着) | `operate_in_place` | +| `MaterialRole.site_picker("site", of=None, for_material=None, occupied="show")` | 前端库位选择器提示:库位参数 `site` 列出 `of` 的库位 | 不进资源合同:写进 `site` 参数 schema 的 `x-unilabos-site-selector` | +| `MaterialRole.order_sensitive()` | 同一资源上的兄弟动作必须显式排序(只约束计划) | `order_sensitive` | - `load` / `unload` 的 `device` / `from_device` 是 `DeviceSlot` 参数,省略就是执行设备;语义与以前相同(设备间转移用 `from_device=`;`load` 与 `unload` 不能写在同一个动作上)。 @@ -199,22 +199,22 @@ def transfer_liquid(self, source: ResourceSlot, target: ResourceSlot, volume: fl | --- | --- | | `ResourceSlot` / `list[ResourceSlot]`(以及选择器为 `unilabos_resources` 的参数) | 物料锁(现状) | | `DeviceSlot` / `list[DeviceSlot]` | 设备锁:值是设备 id,派发前核对它是已登记的设备,与该设备上正在执行的动作互斥 | -| `SiteSlot` | 库位锁:值是库位 uuid,按「所属物料 + 库位」加锁;值是 `Material.site_picker` 所属方下的库位名时按解析出的库位加锁;两者都解析不出时不加锁 | +| `SiteSlot` | 库位锁:值是库位 uuid,按「所属物料 + 库位」加锁;值是 `MaterialRole.site_picker` 所属方下的库位名时按解析出的库位加锁;两者都解析不出时不加锁 | 空值(`None` / `""` / `[]`)不加锁。`always_free` 只免除执行设备自身的动作锁,按类型加的设备锁 / 库位锁照旧。 -### 库位参数:`SiteSlot` 与 `Material.site_picker` +### 库位参数:`SiteSlot` 与 `MaterialRole.site_picker` 库位参数只有一个类型 `SiteSlot`(值是库位 UUID,前端用库位选择器填写)。选择器列出哪个所属方的库位、放进去的是哪件物料、 -已占用的库位怎么处理,写在 `Material.site_picker`: +已占用的库位怎么处理,写在 `MaterialRole.site_picker`: ```python -from unilabos.registry.decorators import Material, action +from unilabos.registry.decorators import MaterialRole, action from unilabos.registry.placeholder_type import ResourceSlot, SiteSlot @action( display_name="放到库位", - material_contract=Material.site_picker("site", of="carrier", for_material="sample", occupied="show"), + material_contract=MaterialRole.site_picker("site", of="carrier", for_material="sample", occupied="show"), ) def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = None) -> None: ... ``` @@ -227,16 +227,16 @@ def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = No - 生成的 `x-unilabos-site-selector` 扩展形状不变:`{"version": 1, "owner": , "occupant": , "show_occupied": ..., "allow_occupied": ...}`;`of` 省略时 `owner` 为 `null`(执行设备根节点),`of` 是 `DeviceSlot` 参数时它的值是设备 id。 -- 只写 `SiteSlot`、不写 `Material.site_picker` 的参数照旧是库位选择器,只是没有这层关系的核对。 +- 只写 `SiteSlot`、不写 `MaterialRole.site_picker` 的参数照旧是库位选择器,只是没有这层关系的核对。 - **工作流里写死的工位**:库位 uuid 由物料权威在建树时发号,同一个设备图在不同部署里的库位 uuid 不同,工作流源码 - 不能写死库位 uuid。带 `Material.site_picker(of=...)` 关系的库位参数可以改给所属方下的**库位名**(或序号),例如 + 不能写死库位 uuid。带 `MaterialRole.site_picker(of=...)` 关系的库位参数可以改给所属方下的**库位名**(或序号),例如 `{"target_owner": {"uuid": <载架 uuid>}, "target_site": "position_x15_y01"}`:运行预检与派发前在 `of` 所属方下唯一 - 匹配,解析出的库位用于归属 / 占用核对、库位锁和 `Material.move` / `place` 的目标(`from_site` 同样)。所属方下匹配不到 + 匹配,解析出的库位用于归属 / 占用核对、库位锁和 `MaterialRole.move` / `place` 的目标(`from_site` 同样)。所属方下匹配不到 或不唯一时报错;没有 `site_picker` 关系的库位名无从解析,派发前报错。 #### 按所属物料选库位:`{"owner_uuid": ...}` -带 `Material.site_picker` 关系的库位参数(以及工作流入口参数里的 `SiteSlot`)可以不给库位 uuid,而给 +带 `MaterialRole.site_picker` 关系的库位参数(以及工作流入口参数里的 `SiteSlot`)可以不给库位 uuid,而给 `{"owner_uuid": "<所属物料 uuid>"}`,由调度器在**任务准入**时挑一个库位: - 候选是所属物料下(可见的)库位里,接收规则接受放入物料(`site_picker` 的 `for_material` 参数;它按库位绑定时先解析)的: @@ -251,7 +251,7 @@ def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = No (`stage=preflight`、`reason=no_acceptable_site`,`details` 带参数、节点、所属物料);运行预检给 `invalid_site_selection`。 接受的库位此刻都被占着或已被预留是临时条件:任务保持 `pending` 排队,attempt 的 `wait_reason.code=site_group_unavailable`, 有任务结束或 5 秒兜底重算时按创建先后重试;运行预检给 `site_selection_unavailable`(可以提交,提交后排队)。 -- 写法本身不对时建任务就拒绝(`error.code=site_selection_invalid`,`error.details.reason`):参数没有 `Material.site_picker` 关系 +- 写法本身不对时建任务就拒绝(`error.code=site_selection_invalid`,`error.details.reason`):参数没有 `MaterialRole.site_picker` 关系 (`no_site_relation`)、关系没有声明 `for_material`(`occupant_undeclared`)、放入物料在建任务时不确定(来自上游结果, `occupant_unknown`)、与 `of` 参数给的物料不一致(`owner_mismatch`)。 - 给精确的库位 uuid 照旧,不经过选择与预留。 @@ -306,25 +306,26 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | 删除的写法 | 新写法 | | --- | --- | | `@action(contract="typed")` / `contract="legacy"` | 去掉:所有 JSON 动作同一标准 | -| `@action(resource_contract={...})` | `@action(material_contract=Material.xxx(...))`,对照表见上 | -| `@action(material=Material.xxx(...))` / `material=[...]`(字段改名前的写法) | `@action(material_contract=Material.xxx(...))` / `material_contract=[...]`:只改字段名,值不变;`material_contract=` 是实验性功能,写了就按定义告警一次 | +| `@action(resource_contract={...})` | `@action(material_contract=MaterialRole.xxx(...))`,对照表见上 | +| `@action(material=Material.xxx(...))` / `material=[...]`(字段改名前的写法) | `@action(material_contract=MaterialRole.xxx(...))` / `material_contract=[...]`:字段名改为 `material_contract=`,声明类改为 `MaterialRole`(见下一行),方法与参数不变;`material_contract=` 是实验性功能,写了就按定义告警一次 | +| `Material.xxx(...)`(声明类 `Material`,`from unilabos.registry.decorators import Material`) | `MaterialRole.xxx(...)`(`from unilabos.registry.decorators import MaterialRole`):只改类名,方法与参数不变,与运行时物料操作模块 `unilabos.resources.materials` 区分开。`Material` 仍可导入,但 `Material.xxx(...)` 在导入时与 AST 扫描里都直接报错并给出新写法 | | `Annotated[T, Placeholder(PLACEHOLDER_...)]`(`unilabos.registry.annotations.Placeholder`) | `@action(placeholder_keys={"参数名": PLACEHOLDER_...})`,参数照常注解为 `T` | -| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(material_contract=Material.site_picker("参数名", of=..., for_material=..., occupied=...))`;生成的 schema 扩展与以前相同 | +| `Annotated[str, SiteSelector(owner=..., occupant=..., show_occupied=..., allow_occupied=...)]`(`unilabos.registry.annotations.SiteSelector`) | 参数注解为 `SiteSlot`,关系写成 `@action(material_contract=MaterialRole.site_picker("参数名", of=..., for_material=..., occupied=...))`;生成的 schema 扩展与以前相同 | | JSON 动作的 `@action(goal={...})` / `result={...}` 重命名 | 去掉:字段名就是参数名 / 返回 TypedDict 的字段名(要改名就改参数名) | | 按名字注入的动作上下文:参数叫 `action_context` 但没有 `ActionContext` 注解 | 注解为 `Optional[ActionContext]`(`from unilabos.client.host.runtime.action import ActionContext`),名字随意;没有注解的 `action_context` 参数注册时报错(自动动作同样) | -### `Material` 辅助 API 重做(一次性不兼容) +### 资源语义辅助 API 重做(一次性不兼容) -`Material` 改为声明真实的物料动作(见「资源语义」)。下面的旧写法在装饰器(导入时)与注册表 AST 扫描里都直接报错, +资源语义改为声明真实的物料动作(见「资源语义」),声明类改名为 `MaterialRole`。下面的旧写法在装饰器(导入时)与注册表 AST 扫描里都直接报错, 错误信息给出新写法;不做转换。 | 删除的写法 | 新写法 | | --- | --- | -| `Material.transfer("plate", to="owner", site="site" \| site_name="site", gripper="arm.gripper", source=..., source_site=..., source_site_name=..., motion=..., tools=...)` | `Material.move("plate", to_site="site", from_site=None, carrier_device=None)`:库位参数改成 `SiteSlot`(值是库位 uuid),所属方由库位决定,不写 `to` / `source`;搬运设备的夹爪库位角色统一为 `gripper`,不写 `gripper=`;`motion` / `tools` 去掉(设备参数按类型加锁) | -| `Material.pick("plate", owner="owner", site="site", carriers=["carrier"])` | `Material.pick("plate", from_site=None, carrier_device=None)`:搬运设备是 `DeviceSlot` 参数,省略即执行设备 | -| `Material.place("plate", owner="owner", site="site", carriers=["carrier"])` | `Material.place("plate", to_site="site", carrier_device=None)` | -| `Material.aliquot(source="source", targets=["target"])` | `Material.dispense(from_material="source", to_materials=["target"])`(语义不变) | -| `Material.site("site", owner="carrier", occupant="sample", show_occupied=..., allow_occupied=...)` | `Material.site_picker("site", of="carrier", for_material="sample", occupied="hide" \| "show" \| "allow")`(`show_occupied=False` → `"hide"`;`allow_occupied=True` → `"allow"`;其余 → `"show"`) | +| `Material.transfer("plate", to="owner", site="site" \| site_name="site", gripper="arm.gripper", source=..., source_site=..., source_site_name=..., motion=..., tools=...)` | `MaterialRole.move("plate", to_site="site", from_site=None, carrier_device=None)`:库位参数改成 `SiteSlot`(值是库位 uuid),所属方由库位决定,不写 `to` / `source`;搬运设备的夹爪库位角色统一为 `gripper`,不写 `gripper=`;`motion` / `tools` 去掉(设备参数按类型加锁) | +| `Material.pick("plate", owner="owner", site="site", carriers=["carrier"])` | `MaterialRole.pick("plate", from_site=None, carrier_device=None)`:搬运设备是 `DeviceSlot` 参数,省略即执行设备 | +| `Material.place("plate", owner="owner", site="site", carriers=["carrier"])` | `MaterialRole.place("plate", to_site="site", carrier_device=None)` | +| `Material.aliquot(source="source", targets=["target"])` | `MaterialRole.dispense(from_material="source", to_materials=["target"])`(语义不变) | +| `Material.site("site", owner="carrier", occupant="sample", show_occupied=..., allow_occupied=...)` | `MaterialRole.site_picker("site", of="carrier", for_material="sample", occupied="hide" \| "show" \| "allow")`(`show_occupied=False` → `"hide"`;`allow_occupied=True` → `"allow"`;其余 → `"show"`) | | `Material.uses(device=[...], tool=[...], motion=[...], site=[...], material=[...])` | 删除:参数按类型加锁(`ResourceSlot` 物料锁、`DeviceSlot` 设备锁、`SiteSlot` 库位锁),把参数注解成对应类型即可 | | `Material.load("sample", device="vessel")`(`vessel` 是 `str` / `ResourceSlot`) | `vessel` 注解为 `DeviceSlot`;装进执行设备本身时省略 `device=` | diff --git a/docs/developer_guide/add_device.md b/docs/developer_guide/add_device.md index f86a5f1c67..535126cc20 100644 --- a/docs/developer_guide/add_device.md +++ b/docs/developer_guide/add_device.md @@ -339,7 +339,7 @@ async def async_operation(self, duration: float) -> Dict[str, Any]: 参数与返回值只有一个标准:注册表按方法签名生成 schema,调度端与 Host 调用前按它校验参数(没有默认值的参数必填, 缺了直接报错),调用后按返回注解校验返回值(注解 `-> bool` 却返回字典会按失败处理)。没写类型的参数接受任意值。 -物料托管、搬运、分装等资源语义写在 `@action(material_contract=Material.xxx(...))` 一个字段里(实验性:写了就按定义告警一次)。完整规则、资源语义写法和 +物料托管、搬运、分装等资源语义写在 `@action(material_contract=MaterialRole.xxx(...))` 一个字段里(实验性:写了就按定义告警一次)。完整规则、资源语义写法和 已删除的旧写法见 [动作的参数、返回值与资源语义](action_standard.md)。 ### 超时:`timeout` 与 `execution_timeout` diff --git a/docs/developer_guide/scheduling_and_execution.md b/docs/developer_guide/scheduling_and_execution.md index 91ccbcfc55..b79bbaee79 100644 --- a/docs/developer_guide/scheduling_and_execution.md +++ b/docs/developer_guide/scheduling_and_execution.md @@ -319,7 +319,7 @@ attempt 和新 `job_uuid`(与 4.1 本机调度器的 retry 语义相同,只 一个 Job 不会只持有部分锁;等待顺序由持久准入决定(5.0)。 **临时资源条件只排队、不失败**(V1 `resource_wait_policy`,`scheduler/resource_wait_policy.py`):解析动作参数与 -物理合同时(`Material.site_picker` 关系的库位被占、搬运来源暂时不在库位、夹爪库位有物),或物料权威准备物理动作时 +物理合同时(`MaterialRole.site_picker` 关系的库位被占、搬运来源暂时不在库位、夹爪库位有物),或物料权威准备物理动作时 (`prepare_material_execution` 发现目标库位刚被占、另一作业的物理动作尚未结算),attempt 不记 `dispatch_not_sent`, 而是撤回已取得的 Claim、区间准入与内存锁,回到等待集合,下一次资源变化(任一作业释放资源、5 秒兜底重算)时 按首次排队先后重试;排队原因写在 attempt 的 `control_data.wait_reason`(`{code, message, waiting_since}`,作业 diff --git a/docs/developer_guide/v1_file_index/rest.md b/docs/developer_guide/v1_file_index/rest.md index 4039a74773..ac4bd611c5 100644 --- a/docs/developer_guide/v1_file_index/rest.md +++ b/docs/developer_guide/v1_file_index/rest.md @@ -117,11 +117,11 @@ | unilabos/registry/action_resource_contract.py | 643 | PORTED | `registry/action_resource_contract.py` | 已在调度器托管下启用(A03) | | unilabos/registry/action_result_schema.py | 376 | PORTED | `registry/action_result_schema.py` | 逐字相同 | | unilabos/registry/action_template_projection.py | 492 | PORTED | `registry/action_template_projection.py` | 逐字相同;`node_templates.py` 调它的 `compile_action_template_handles` | -| unilabos/registry/annotation_rendering.py | 190 | PORTED | `registry/annotation_rendering.py` | 去掉 `SiteSelector(...)` 的回写(库位关系改为 `Material.site_picker`),其余相同 | +| unilabos/registry/annotation_rendering.py | 190 | PORTED | `registry/annotation_rendering.py` | 去掉 `SiteSelector(...)` 的回写(库位关系改为 `MaterialRole.site_picker`),其余相同 | | unilabos/registry/annotation_schema.py | 760 | PORTED | `registry/annotation_schema.py` | 逐字相同 | -| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(material_contract=Material.site_picker(...))`,导入时报错并给出新写法),其余相同 | +| unilabos/registry/annotations.py | 65 | PORTED | `registry/annotations.py` | `SiteSelector` 已删除(与 `SiteSlot` 合一,关系写 `@action(material_contract=MaterialRole.site_picker(...))`,导入时报错并给出新写法),其余相同 | | unilabos/registry/ast_registry_scanner.py | 1311 | PORTED | `registry/ast_registry_scanner.py`(文件级缓存、`_collect_literal_constants`、`available_sites` 常量解析) | 跟随装饰器差异:不再提取 `metadata`、`displayname`、`ExecutorKind`、`exception_handling`、`action_name`(见 decorators);与 V1 一样对每个 JSON 动作做 AST 解析(统一 schema 草稿,不认识的注解退回签名推断) | -| unilabos/registry/decorators.py | 882 | PARTIAL | `registry/decorators.py`(`device` / `action` / `resource` / `topic_config` / `always_free` / `not_action`) | V1 作者接口里有六个参数统一分支运行时装饰器不接受,驱动传了会在导入时 TypeError:`@action(action_name=…)`(对外动作名与方法名不同;AST 注册路径 `registry.py:1060` 却仍按它登记公开名、不记方法名,派发按公开名找方法,见 base_device_node 行)、`exception_handling=False`(异常不进人工决策)、`executor_kind`、`default_on_user_timeout`、`displayname`;`@device(metadata=…)`(供应商 / 规格等扩展元数据)。`legacy_action` / `contract=` 已删除(所有 JSON 动作同一标准,写了报错);资源语义用 `material_contract=Material.xxx(...)`。`display_name` 只认新拼写是统一分支文档里的明确决定。统一分支另加了 `material_contract`(实验性)、`supported_backends`、`SiteSlot`;曾加的 `materials_need_lock` / `materials_free` 已按负责人 2026-11-17 决定移除(每个物料入参默认加共享资源锁),旧驱动传了照常加载、忽略并告警 | +| unilabos/registry/decorators.py | 882 | PARTIAL | `registry/decorators.py`(`device` / `action` / `resource` / `topic_config` / `always_free` / `not_action`) | V1 作者接口里有六个参数统一分支运行时装饰器不接受,驱动传了会在导入时 TypeError:`@action(action_name=…)`(对外动作名与方法名不同;AST 注册路径 `registry.py:1060` 却仍按它登记公开名、不记方法名,派发按公开名找方法,见 base_device_node 行)、`exception_handling=False`(异常不进人工决策)、`executor_kind`、`default_on_user_timeout`、`displayname`;`@device(metadata=…)`(供应商 / 规格等扩展元数据)。`legacy_action` / `contract=` 已删除(所有 JSON 动作同一标准,写了报错);资源语义用 `material_contract=MaterialRole.xxx(...)`。`display_name` 只认新拼写是统一分支文档里的明确决定。统一分支另加了 `material_contract`(实验性)、`supported_backends`、`SiteSlot`;曾加的 `materials_need_lock` / `materials_free` 已按负责人 2026-11-17 决定移除(每个物料入参默认加共享资源锁),旧驱动传了照常加载、忽略并告警 | | unilabos/registry/in_memory_template_projection_store.py | 348 | DROPPED | 第 4 条 | V1 给不开 SQLite 的纯 Authoring Web 进程用的进程内模板代际存储。统一分支只把模板投影写进 runtime.db(`services/runtime/workflow/node_templates.py`) | | unilabos/registry/init_enforce.py | 86 | PORTED | `registry/init_enforce.py` | 逐字相同 | | unilabos/registry/local_template_identity.py | 548 | PORTED | `resources/adapters/registry_materials.py:sync_registry_resources` / `register_resource_definitions`(启动时 `app/backend_main.py:158`、`server/startup.py:150`) | 注册表资源按 `definition_hash` 幂等同步成物料模板,UUID 稳定。没有 V1 的库位 `initial_material_template` 短名 → UUID 二次解析(见 site_definition) | @@ -131,7 +131,7 @@ | unilabos/registry/placeholder_type.py | 59 | PORTED | `registry/placeholder_type.py` | 统一分支另加 `SiteSlot` / `PLACEHOLDER_SITES`,`ResourceSlotRawInput` 也接受 str | | unilabos/registry/registry.py | 2783 | PORTED | `registry/registry.py:Registry` | 去掉了 `publish_package_snapshot` / `resolve_definition` / `package_snapshot`(第 1 条)和 `_apply_action_execution_metadata`(见 decorators)。旧锁字段处理与预计时长默认值由 `material_locks` 和 A01 的 `action_duration` 承担 | | unilabos/registry/runtime_device_catalog.py | 217 | PARTIAL | 设备身份:Registry Authority 条目(`services/runtime/registry.py`)+ `services/runtime/devices.py`(`/devices`,动作模板 UUID 用 `template_identity`) | V1 在内存里为包内每个设备建模板目录:用确定性的 `device_template_uuid`,并在 `GET /resource-templates`(`resource_type` 为空或 device)里列出。统一分支只在设备进图建实例时懒创建设备模板(`materials/core.py` 约 2302 行,`uuid4()` 随机 UUID),没进图的包设备不出现在 `/resource-templates`。影响:前端从模板列表放置设备,或跨实例 / Backend 按设备模板 UUID 对账时对不上 | -| unilabos/registry/site_selector_schema.py | 251 | PORTED | `registry/site_selector_schema.py`(+ `site_selector_value_schema.py`) | 只保留 owner / occupant 关系校验(供 `Material.site_picker` 用);注解解析与回写随 `SiteSelector` 删除,生成的 `x-unilabos-site-selector` 扩展不变 | +| unilabos/registry/site_selector_schema.py | 251 | PORTED | `registry/site_selector_schema.py`(+ `site_selector_value_schema.py`) | 只保留 owner / occupant 关系校验(供 `MaterialRole.site_picker` 用);注解解析与回写随 `SiteSelector` 删除,生成的 `x-unilabos-site-selector` 扩展不变 | | unilabos/registry/template_delta.py | 431 | PORTED | `server/services/runtime/registry.py:RegistryService.report_entries`(条目级不可变版本;每批统计新增 / 更新 / 挂起 / 移除 / 复活 / 不变 / 自动接受;新增 / 变化 / 消失先挂起,单机部署或驱动包版本升高时自动接受;软移除可 restore)+ `node_templates.py`(不再生效的模板软删除) | 做法是 dev 的条目版本,不是 V1 的投影成员 manifest,行为等价;接受规则是 dev 自己的(V1 每个进程本地加载注册表,没有这一步) | | unilabos/registry/template_identity.py | 146 | PORTED | `registry/template_identity.py` | 逐字相同;`node_templates.py`、`devices.py` 在用 | | unilabos/registry/template_projection.py | 1215 | PORTED | `server/services/runtime/workflow/node_templates.py:NodeTemplateCatalog.sync_registry_templates` / `project_registry_templates` | 注册表动作投影进 runtime.db 的 `workflow_node_template` / `workflow_handle_template`(`authority_id=registry-template-projection`,V1 的确定性 UUID,指纹不变不重算)。结构节点模板(dev 的 condition / loop / group / material_io)总挂在 host_node 资源模板下投影,不依赖 host_node 条目是否已上报。资源模板「源码别名 → UUID」映射只服务 V1 的创作内核,随第 7 条一起去掉 | diff --git a/docs/developer_guide/v1_file_index/scheduler.md b/docs/developer_guide/v1_file_index/scheduler.md index 699e910ca5..17301633ea 100644 --- a/docs/developer_guide/v1_file_index/scheduler.md +++ b/docs/developer_guide/v1_file_index/scheduler.md @@ -85,7 +85,7 @@ DROPPED 的依据分布:#4 / D05(可替换引擎宿主、插件传输与协 | `unilabos/app/scheduler/inventory/schemas.py` | 804 | PORTED | 命令载荷校验在 `inventory_commands.py` 各处理器 + `unilabos/protocol/materials.py`(`InventoryMutation`、`InventoryLotRead`、`InventoryStocktake` 等);读 DTO 见 `server/api/materials/inventory.py` | 差异:V1 命令边界是 `extra="forbid"` + strict int/float,统一分支在处理器内宽松取值,未知字段不报错;`inventory.reconcile_count` 的 `mount_uuid` / `evidence_job_uuid`(可信计数测量证据)被忽略,按人工盘点 `stocktake_inventory_lot` 执行——对应 I03 开放项(按测量作业证据自动盘点未实现)。云端响应 / 回调 DTO(`CloudResponse`、`CloudInventoryCommandResult*`)不需要,V1 产品没接云 | | `unilabos/app/scheduler/inventory/service.py` | 2825 | PORTED | `server/services/materials/core.py:MaterialsService`(`put_template/delete_template`、`inbound_inventory_lot`、`reserve_inventory` / `reserve_task_inventory`、`consume/release/quarantine_inventory_reservation`、`correct_inventory_lot`、`move_material`)+ `services/materials/inventory_commands.py`(V1 全部命令类型:`inventory.inbound` kind=instance、`material.deploy/move/detach/set_parent/consume/mark_used/discard/adjust`、`material.content.set/clear`);工站异常人工修正 `services/runtime/station_handling.py` | 对账表 I01 / I02;`api_v1_route_map.md` p7-c / p7-d。`admit_material_sources` / `resolve_shared_workflow_materials`(物料来源准入、共享来源)属 #6,dev 仅保留 `source.bind/release` 命令(`contents.py:bind_material_source`),调度器不调用;`describe_wait_resources` → 任务 `wait_reason` / `resource_waiters.py` | | `unilabos/app/scheduler/inventory/settled_quantity.py` | 78 | PARTIAL | 分装结算 `materials/execution.py:MaterialExecutions._aliquot`;分装消耗读模型 `materials/consumption.py:_aliquot_facts`(`/inventory-consumptions` 列出已结算分装,`tests/server/test_inventory_seam_v1.py::test_settled_aliquot_is_a_consumption_of_the_source_contents`);批次实际量结算与人工核对去重 `execution.py:apply_actual_lot_quantity`(effect `physical.inventory:`) | V1 用已提交的分装来源台账作为该作业 `current_substance` 预留的实际扣量,防止通用消费再扣一次。统一分支内容物预留在动作开始按计划量扣(`core.py` 预留 consume → `contents.finish_content_reservation`),分装回执又按实际量扣来源(`_aliquot`),两处之间没找到去重(grep `aliquot` 于 contents / core / scheduler / server/inventory 无交叉)。影响:同一节点既声明分装来源的 content 需求又是 aliquot 动作时会重复扣量;不声明则分装来源不受多任务数量预留保护(需实测确认) | -| `unilabos/app/scheduler/inventory/site_selection.py` | 237 | PARTIAL | 精确库位引用:`runtime/workflow/site_bindings.py:SiteBindingIndex.resolve` / `resolve_workflow_sites`(图保存 `site_binding_mode=resolve` 时按 owner 范围把 label 冻结为 site_uuid,UUID 失效不按标签回退);派发时 `physical_contract.py:site()`(uuid / label / index 唯一可见)、`run_preflight.py:validate_resource_values`(`Material.site_picker` 库位关系的归属 / 占用) | 缺命名库位组:V1 `site_group("组键", exact=...)` 读 Site `meta_data.unilab.site_groups`,任务创建时冻结有序候选 + 部署指纹(`sha256`),所属物料未定时记 `deferred_site_group` 到派发再解析,并按 `sort_order` 取第一个可放的空位;统一分支 grep `site_groups/group_key/target_site_group/deferred_site` 均无,编译器也无 `site_group()`。影响:V1 依赖“放到这组孔里任一空位”的转运工作流无法表达,只能写死具体库位 | +| `unilabos/app/scheduler/inventory/site_selection.py` | 237 | PARTIAL | 精确库位引用:`runtime/workflow/site_bindings.py:SiteBindingIndex.resolve` / `resolve_workflow_sites`(图保存 `site_binding_mode=resolve` 时按 owner 范围把 label 冻结为 site_uuid,UUID 失效不按标签回退);派发时 `physical_contract.py:site()`(uuid / label / index 唯一可见)、`run_preflight.py:validate_resource_values`(`MaterialRole.site_picker` 库位关系的归属 / 占用) | 缺命名库位组:V1 `site_group("组键", exact=...)` 读 Site `meta_data.unilab.site_groups`,任务创建时冻结有序候选 + 部署指纹(`sha256`),所属物料未定时记 `deferred_site_group` 到派发再解析,并按 `sort_order` 取第一个可放的空位;统一分支 grep `site_groups/group_key/target_site_group/deferred_site` 均无,编译器也无 `site_group()`。影响:V1 依赖“放到这组孔里任一空位”的转运工作流无法表达,只能写死具体库位 | | `unilabos/app/scheduler/inventory/source_selection.py` | 122 | DROPPED | 已定 #6 / 对账表 I02(material_source 物料来源准入不做);统一分支的近似是 `InventoryRequirement` kind=`material` 按 `template_uuid` + `parent_material_uuid`(仅直接父)或 `site_uuid` 选料(`materials/core.py:_select_inventory_material`) | `search_descendants`(沿各层 Site 实际占位遍历挂载物料子树选料)没有对应;`claimed_by_other_task`(被他任务占用 → 等待而非缺料)在统一分支变成缺料失败,见 domain.py 行 | | `unilabos/app/scheduler/inventory/station_resource.py` | 1241 | PARTIAL | 转运 / 原位 / 分装资源事实与结算:`scheduler/physical_contract.py:resolve_physical_contract`、`tenancy_contract.py`、`materials/execution.py:prepare/settle`、`physical_recovery.py`;异常处置库存:`services/runtime/station_handling.py`(inventory、inventory-corrections)、`api/runtime/stations.py`(resource-usage);Permit 系列见 dispatch_admission 行;`is_device_material` → `resource_type == "device"` | 缺 `resolve_named_site_group` 与 `resolve_target_site` 的“候选组 + 当前不可用集合 → 选一个能接收该模板物料的空位”(`allowed_resource_template_uuids` 也参与);统一分支目标库位必须由参数唯一给定。与 site_selection.py 同一缺口 | | `unilabos/app/scheduler/inventory/stocktake.py` | 68 | PARTIAL | `materials/core.py:stocktake_inventory_lot`(人工计数盘点:操作人、理由、期望版本,预留 / 隔离 / 已登记实物差异拒绝);`inventory.reconcile_count` 命令映射到它(`inventory_commands.py:_reconcile_count`) | 对账表 I03“部分”属实。缺测量证据盘点:V1 `reconcile_count` 要求 `evidence_job_uuid`(成功的测量作业)与 `mount_uuid`(批次必须归属被测容器)、容器正被物理动作占用时拒绝,并由工作流原生命令 `read_count` → 测量 → `reconcile_count` 冻结测量前版本;统一分支命令丢弃这些字段,按人工盘点处理。影响:设备计数测量后无法自动修正库存 | diff --git a/docs/developer_guide/workflow_resource_custody.md b/docs/developer_guide/workflow_resource_custody.md index 5eef7d19dd..62dbd75652 100644 --- a/docs/developer_guide/workflow_resource_custody.md +++ b/docs/developer_guide/workflow_resource_custody.md @@ -11,13 +11,13 @@ v1.0 的 `task_while_loaded` 表示样品装入后设备持续归该任务托管 在 `@action(material_contract=...)` 声明参数名(写法对照见 [动作的参数、返回值与资源语义](action_standard.md)): ```python -@action(material_contract=Material.load("sample", device="vessel")) +@action(material_contract=MaterialRole.load("sample", device="vessel")) def load_sample(self, sample: ResourceSlot, vessel: str) -> CustodyResult: ... ``` -卸载使用 `Material.unload("sample", device="vessel")`;设备间转移写 -`Material.load("sample", device="b", from_device="a")`(同时取得 b、释放 a)。 -原位处理使用 `Material.in_place("sample")`。注册表把它们规范化成动作 schema 里的资源合同 +卸载使用 `MaterialRole.unload("sample", device="vessel")`;设备间转移写 +`MaterialRole.load("sample", device="b", from_device="a")`(同时取得 b、释放 a)。 +原位处理使用 `MaterialRole.in_place("sample")`。注册表把它们规范化成动作 schema 里的资源合同 (`device_tenancy` / `operate_in_place`),调度器按合同执行。 样品字段为 ResourceSlot;设备参数使用字符串 ID,也可解析旧 ResourceSlot 设备身份为可读 `resource_id`, 例如 `reactor`。设备字符串经过物料权威校验,避免把设备当作 PLR 物料实例装配;旧 ResourceSlot 的实际装配仍受其 PLR 配置约束。Python 定义默认设备 ID 和过程,前端负责样品、设备绑定。 diff --git a/docs/developer_guide/workflow_static_conditions.md b/docs/developer_guide/workflow_static_conditions.md index 1809db22b9..61013ad3fd 100644 --- a/docs/developer_guide/workflow_static_conditions.md +++ b/docs/developer_guide/workflow_static_conditions.md @@ -336,7 +336,7 @@ def parallel_check(ctx): 计划的拓扑序先按它排);用同一台设备的成员因此按书写顺序依次执行。这只是同时就绪时的先后, 不是顺序保证:分支里前面有别的步骤、某个成员在等库存或另一项资源、失败重试时,后写的成员可能先做。 `parallel` 的意思是「顺序无所谓」,先后有影响就写成顺序执行。动作可以声明 -`@action(material_contract=Material.order_sensitive())`(V1 同名合同 `order_sensitive`): +`@action(material_contract=MaterialRole.order_sensitive())`(V1 同名合同 `order_sensitive`): 同一资源上没有先后关系的两个兄弟动作只要有一方声明,就在发布和创建任务时被拒绝, 报错指出是哪两步,提示改成顺序执行或用依赖明确先后。这里的「同一资源」只有两类:动作节点自己的设备 (`execution_policy.always_free` 的动作不算),以及工作流 `meta_data.unilab.resource_scopes` 显式声明的资源作用域; From 3a155303a887d41e7893dabce7d1d3a68dd9b02e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:12:27 +0800 Subject: [PATCH 27/27] test(e2e): pin LabDeviceComplexWorkflowDemo to its MaterialRole main c84ca2a declares the reactor actions with MaterialRole.xxx(...). The commit has to be on the demo's origin before the pinned clone can fetch it. --- tests/e2e/readme_demos.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/readme_demos.py b/tests/e2e/readme_demos.py index fc32f81f2e..f12291b45a 100644 --- a/tests/e2e/readme_demos.py +++ b/tests/e2e/readme_demos.py @@ -184,7 +184,7 @@ def runtime_timeout(self) -> float: DemoSpec( repo="LabDeviceComplexWorkflowDemo", url="https://github.com/Xuwznln/LabDeviceComplexWorkflowDemo", - ref="d25221c1e11104581dc323bd677bed99ca855c9f", + ref="c84ca2a5628d873e40d937527c4ba96484b44db8", package="complex_workflow_demo", host_graph="graph/complex_workflow_demo.json", # 循环容器:循环体节点每轮一个 attempt(trigger=loop_iteration),循环节点自身 1 个 attempt;