From e2305df68b0a3df46383b2b356070876a6baef9e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:01:14 +0800 Subject: [PATCH 01/59] feat(materials): place new materials atomically and keep device subtrees PLR-only Drivers create materials through one path: the client materials service serializes the PLR tree (ResourceTreeSet) and the authority creates and places it in a single transaction. - MaterialTreeCreate.placement: the authority mounts the new root on its parent / Site inside the create transaction, using the same rules as a move; any failure rolls back the whole tree. - materials.create(..., node=, parent=, site=, display_name=): resolves the Site (ResourceSite instance, uuid, label or index), creates and places atomically, then projects the material onto the device through the transfer load path and returns the tracker's instance. - materials.assign onto device-own Sites (site=ResourceSite / uuid, or slot=label); the Host append_resource device branch moves onto the Site, resolving the selector before the commit point. One material per Site. - The authority rejects non-PLR materials (no config.type) entering a device subtree, on every move/transfer/settlement/mount and when a device is created with held materials. Such materials made the device fail to restart, because device children are rebuilt as PLR resources. - Legacy non-PLR children already under a device are skipped (named in an error log) instead of taking the whole device down. --- .../test_attach_legacy_non_plr_children.py | 67 +++++ .../resources/test_device_available_sites.py | 5 +- .../test_materials_create_and_place.py | 224 +++++++++++++++++ tests/server/test_material_io_inventory.py | 4 +- tests/server/test_material_links.py | 2 + .../test_materials_device_subtree_plr_only.py | 231 ++++++++++++++++++ .../client/host/runtime/driver_creator.py | 22 +- unilabos/client/host/runtime/node.py | 41 +++- unilabos/protocol/materials.py | 16 ++ unilabos/resources/adapters/plr_materials.py | 19 +- unilabos/resources/materials.py | 163 +++++++++++- unilabos/server/services/materials/core.py | 95 +++++++ 12 files changed, 867 insertions(+), 22 deletions(-) create mode 100644 tests/client/host/runtime/test_attach_legacy_non_plr_children.py create mode 100644 tests/resources/test_materials_create_and_place.py create mode 100644 tests/server/test_materials_device_subtree_plr_only.py diff --git a/tests/client/host/runtime/test_attach_legacy_non_plr_children.py b/tests/client/host/runtime/test_attach_legacy_non_plr_children.py new file mode 100644 index 000000000..e1d1082d5 --- /dev/null +++ b/tests/client/host/runtime/test_attach_legacy_non_plr_children.py @@ -0,0 +1,67 @@ +"""旧数据里设备下遗留的非 PLR 物料:不挂到本地、点名报错,整台设备照常启动。 + +权威已在落位时拒绝新的非 PLR 物料进入设备子树;这里只处理升级前留下的旧数据(如旧版 +虚拟加热平台经网关手写、没有 ``config.type`` 的样品)——以前它让设备在重启时直接起不来。 +""" + +from __future__ import annotations + +import logging +from uuid import uuid4 + +from pylabrobot.resources import Resource + +from unilabos.client.host.runtime.driver_creator import DeviceClassCreator +from unilabos.resources.resource_tracker import ( + DeviceNodeResourceTracker, + ResourceDict, + ResourceDictInstance, + ResourceTreeSet, +) + + +class _Driver: + def __init__(self, **_kwargs) -> None: + pass + + +def _legacy_sample(device_uuid: str) -> ResourceDictInstance: + return ResourceDictInstance( + ResourceDict.model_validate( + { + "id": "heater-sample-1", + "uuid": str(uuid4()), + "name": "heater-sample-1", + "type": "resource", + "class": "Resource", + "template_name": "virtual_heating_sample", + "parent_uuid": device_uuid, + "config": {}, + "data": {"temperature_c": 25.0}, + "extra": {}, + } + ) + ) + + +def _plr_child(device_uuid: str) -> ResourceDictInstance: + source = Resource("legacy_neighbour", size_x=10, size_y=10, size_z=10) + tree = ResourceTreeSet.from_plr_resources([source], known_random_uuid=True).trees[0] + tree.root_node.res_content.parent_uuid = device_uuid + return tree.root_node + + +def test_legacy_non_plr_child_is_skipped_and_named(caplog) -> None: + device_uuid = str(uuid4()) + legacy = _legacy_sample(device_uuid) + neighbour = _plr_child(device_uuid) + tracker = DeviceNodeResourceTracker() + creator = DeviceClassCreator(_Driver, [legacy, neighbour], tracker) + + with caplog.at_level(logging.ERROR): + creator.create_instance({}) + + assert legacy.res_content.uuid not in tracker.uuid_to_resources + # 同一设备下的 PLR 物料照常挂上 + assert neighbour.res_content.uuid in tracker.uuid_to_resources + assert any("heater-sample-1" in record.getMessage() for record in caplog.records) diff --git a/tests/resources/test_device_available_sites.py b/tests/resources/test_device_available_sites.py index 64fcb1540..64266bbe4 100644 --- a/tests/resources/test_device_available_sites.py +++ b/tests/resources/test_device_available_sites.py @@ -536,7 +536,8 @@ def test_device_created_with_held_materials_subtree(authority): "class": "Deck", "template_name": "Deck", "parent_uuid": owner_uuid, - "config": {}, + # 设备子树只收 PLR 物料:config.type 是 PLR 类型名 + "config": {"type": "Deck"}, "data": {}, "extra": {}, } @@ -917,7 +918,7 @@ def material(template_name: str) -> str: created = service.create_tree(mutation("create_material_tree"), MaterialTreeCreate(nodes=[MaterialNodeCreate( client_ref="m", identity=MaterialIdentityWrite( resource_id=f"{template_name}-{uuid4().hex[:6]}", name=template_name, resource_type="container", - class_name="Container", template_name=template_name), + class_name="Container", template_name=template_name, config={"type": "Container"}), )])) return created.data.root_material_uuid diff --git a/tests/resources/test_materials_create_and_place.py b/tests/resources/test_materials_create_and_place.py new file mode 100644 index 000000000..b0b6a67e8 --- /dev/null +++ b/tests/resources/test_materials_create_and_place.py @@ -0,0 +1,224 @@ +"""物料创建即落位(原子)与挂到设备自身库位:``materials.create(site=)`` / ``materials.assign(site=)``。 + +驱动创建物料只走一条路:client 物料服务(``ResourceTreeSet`` 序列化)发给权威,权威在建树的 +同一事务里把根物料挂到父物料、占用库位;任一步不满足整体回滚,不留没落位的根物料。 +本地按 transfer 的 load 投影挂上,返回 tracker 里那一份实例(uuid → 实例唯一)。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +import pytest + +from unilabos.client.host.hostlink.local_runtime import HostLinkDriverSpec, HostLinkLocalRuntime +from unilabos.client.host.runtime.resource import AuthorityResourceService +from unilabos.client.materials import LocalMaterialsClient +from unilabos.resources import materials +from unilabos.resources.adapters.device_site import apply_device_authority_state +from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance +from unilabos.server.services.materials import MaterialsService +from tests.plr_fixtures import plate + +DEVICE_TEMPLATE = "create_and_place_test_device" +DEVICE_SITES = [ + {"index": 1, "label": "slot_a"}, + {"index": 2, "label": "slot_b"}, +] + + +class _Device: + def __init__(self, **_kwargs) -> None: + pass + + +def _device_config(device_uuid: str) -> ResourceDictInstance: + return ResourceDictInstance( + ResourceDict.model_validate( + { + "id": "placer", + "uuid": device_uuid, + "name": "placer", + "type": "device", + "class": DEVICE_TEMPLATE, + "template_name": DEVICE_TEMPLATE, + "config": {}, + "data": {}, + "extra": {}, + "sites": None, + "sites_initialized": False, + } + ) + ) + + +@pytest.fixture +def device(tmp_path): + service = MaterialsService(tmp_path / "materials.db") + gateway = LocalMaterialsClient(service) + device_uuid = str(uuid4()) + config = _device_config(device_uuid) + apply_device_authority_state( + config, {"available_sites": DEVICE_SITES}, DEVICE_TEMPLATE, gateway=gateway + ) + runtime = HostLinkLocalRuntime() + node = runtime.add_driver( + HostLinkDriverSpec("placer", _Device, {}, resource_uuid=device_uuid) + ) + runtime.set_resource_service(AuthorityResourceService(gateway)) + runtime.start() + try: + yield { + "service": service, + "gateway": gateway, + "node": node, + "device_uuid": device_uuid, + "sites": {site.label: site for site in config.res_content.sites}, + } + finally: + runtime.stop() + service.close() + + +def _site(service, device_uuid: str, label: str): + return next( + site for site in service.get_material(device_uuid).sites if site.label == label + ) + + +def test_create_places_the_root_on_a_device_site_in_one_transaction(device) -> None: + service, node = device["service"], device["node"] + + created = materials.create( + plate("plate_a"), node=node, site="slot_a", gateway=device["gateway"] + ) + + material_uuid = created.unilabos_uuid + assert _site(service, device["device_uuid"], "slot_a").occupied_material_uuid == material_uuid + stored = service.get_material(material_uuid).material + assert stored.parent_material_uuid == device["device_uuid"] + # 返回的就是 tracker 登记的那一份实例 + assert node.resource_tracker.uuid_to_resources[material_uuid] is created + # 建树与落位同一条变更命令:账本里没有一个「建好了还没落位」的中间版本 + site_uuid = _site(service, device["device_uuid"], "slot_a").site_uuid + ledger = service.list_ledger(limit=100_000) + created_by = next(entry.command_uuid for entry in ledger if entry.aggregate_uuid == material_uuid) + occupied_by = [ + entry.command_uuid + for entry in ledger + if entry.aggregate_uuid == site_uuid + and entry.delta_json.get("occupied_material_uuid") == material_uuid + ] + assert occupied_by == [created_by] + + +def test_create_accepts_the_site_instance_from_post_init(device) -> None: + service, node = device["service"], device["node"] + + created = materials.create( + plate("plate_b"), node=node, site=device["sites"]["slot_b"], gateway=device["gateway"] + ) + + assert ( + _site(service, device["device_uuid"], "slot_b").occupied_material_uuid + == created.unilabos_uuid + ) + + +def test_create_rolls_back_when_the_site_is_occupied(device) -> None: + service, node, gateway = device["service"], device["node"], device["gateway"] + first = materials.create(plate("first"), node=node, site="slot_a", gateway=gateway) + before = {item.material.material_uuid for item in service.list_materials()} + + with pytest.raises(Exception, match="occupied"): + materials.create(plate("second"), node=node, site="slot_a", gateway=gateway) + + # 整体回滚:没有留下没落位的新根物料,库位仍是原占用者,本地也没多出实例 + assert {item.material.material_uuid for item in service.list_materials()} == before + assert _site(service, device["device_uuid"], "slot_a").occupied_material_uuid == first.unilabos_uuid + assert [res.name for res in node.resource_tracker.resources] == ["first"] + + +def test_create_rejects_an_unknown_site_before_anything_is_written(device) -> None: + service, node = device["service"], device["node"] + before = len(service.list_materials()) + + with pytest.raises(ValueError, match="slot_z"): + materials.create(plate("lost"), node=node, site="slot_z", gateway=device["gateway"]) + + assert len(service.list_materials()) == before + assert node.resource_tracker.resources == [] + + +def test_create_with_placement_requires_a_node(device) -> None: + with pytest.raises(ValueError, match="node"): + materials.create(plate("orphan"), site="slot_a", gateway=device["gateway"]) + + +def test_assign_occupies_a_device_site_by_instance_and_by_label(device) -> None: + service, node, gateway = device["service"], device["node"], device["gateway"] + by_instance = materials.create(plate("by_instance"), gateway=gateway) + by_label = materials.create(plate("by_label"), gateway=gateway) + + materials.assign(node, by_instance, site=device["sites"]["slot_a"]) + materials.assign(node, by_label.unilabos_uuid, slot="slot_b") + + assert ( + _site(service, device["device_uuid"], "slot_a").occupied_material_uuid + == by_instance.unilabos_uuid + ) + assert ( + _site(service, device["device_uuid"], "slot_b").occupied_material_uuid + == by_label.unilabos_uuid + ) + for material in (by_instance, by_label): + stored = service.get_material(material.unilabos_uuid).material + assert stored.parent_material_uuid == device["device_uuid"] + assert material.unilabos_uuid in node.resource_tracker.uuid_to_resources + + +def test_assign_moves_between_device_sites(device) -> None: + service, node = device["service"], device["node"] + created = materials.create(plate("mover"), node=node, site="slot_a", gateway=device["gateway"]) + + materials.assign(node, created, slot="slot_b") + + assert _site(service, device["device_uuid"], "slot_a").occupied_material_uuid is None + assert ( + _site(service, device["device_uuid"], "slot_b").occupied_material_uuid + == created.unilabos_uuid + ) + assert node.resource_tracker.uuid_to_resources[created.unilabos_uuid] is created + + +def test_assign_to_the_device_without_a_site_only_sets_the_parent(device) -> None: + service, node = device["service"], device["node"] + loose = materials.create(plate("loose"), gateway=device["gateway"]) + + materials.assign(node, loose) + + assert service.get_material(loose.unilabos_uuid).material.parent_material_uuid == device["device_uuid"] + assert all( + site.occupied_material_uuid is None + for site in service.get_material(device["device_uuid"]).sites + ) + + +def test_assign_rejects_an_unknown_device_site_without_mounting(device) -> None: + service, node = device["service"], device["node"] + loose = materials.create(plate("stray"), gateway=device["gateway"]) + + with pytest.raises(ValueError, match="slot_z"): + materials.assign(node, loose, slot="slot_z") + + assert loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources + assert service.get_material(loose.unilabos_uuid).material.parent_material_uuid is None + + +def test_assign_puts_at_most_one_material_on_a_site(device) -> None: + gateway = device["gateway"] + first = materials.create(plate("one"), gateway=gateway) + second = materials.create(plate("two"), gateway=gateway) + + with pytest.raises(ValueError, match="一个库位只能放一个物料"): + materials.assign(device["node"], [first, second], slot="slot_a") diff --git a/tests/server/test_material_io_inventory.py b/tests/server/test_material_io_inventory.py index d25beda91..419e9764c 100644 --- a/tests/server/test_material_io_inventory.py +++ b/tests/server/test_material_io_inventory.py @@ -46,8 +46,10 @@ def _identity(template: str, name: str) -> MaterialIdentityWrite: + # config.type 是 PLR 类型名:这些容器 / 台面会挂进设备子树(设备子树只收 PLR 物料) return MaterialIdentityWrite(resource_id=f"{name}-{uuid4().hex[:6]}", name=f"{name}-{uuid4().hex[:6]}", - template_name=template, resource_type="container", class_name="Container") + template_name=template, resource_type="container", class_name="Container", + config={"type": "Container"}) def _ensure_template(materials: MaterialsService, template_uuid: str, name: str) -> None: diff --git a/tests/server/test_material_links.py b/tests/server/test_material_links.py index f92540456..c75c3cfe9 100644 --- a/tests/server/test_material_links.py +++ b/tests/server/test_material_links.py @@ -48,6 +48,8 @@ def _create_root(service: MaterialsService, ref: str) -> str: resource_type="container", class_name="Container", template_name="tube", + # PLR 类型名:设备子树只收 PLR 物料 + config={"type": "Container"}, ), data=MaterialDataWrite(), ) diff --git a/tests/server/test_materials_device_subtree_plr_only.py b/tests/server/test_materials_device_subtree_plr_only.py new file mode 100644 index 000000000..318d26b3c --- /dev/null +++ b/tests/server/test_materials_device_subtree_plr_only.py @@ -0,0 +1,231 @@ +"""设备子树只收 PLR 物料(权威在每一次落位上把关)。 + +设备启动时按 ``ResourceTreeSet`` 把设备子树整棵反序列化成 PLR 实例,靠每个节点的 +``config.type``(PLR 自己的类型名)找类。只有身份的物料(网关手写、模板实例化不了)一旦挂进 +设备子树,设备重启就起不来;所以 move / transfer / 结算 / 设备挂载 / 建树即落位都走 +``_apply_material_move`` 的同一道检查,在落位时就拒绝。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +import pytest + +from unilabos.client.materials import LocalMaterialsClient +from unilabos.protocol.materials import ( + InventoryMutation, + MaterialIdentityWrite, + MaterialMove, + MaterialNodeCreate, + MaterialPlacement, + MaterialTreeCreate, + ResourceTemplateWrite, +) +from unilabos.resources.adapters.device_site import apply_device_authority_state +from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance +from unilabos.server.services.materials import MaterialsService +from unilabos.server.services.materials.core import MaterialValidationError + +DEVICE_TEMPLATE = "plr_only_test_device" + + +def _mutation(operation: str) -> InventoryMutation: + command = str(uuid4()) + return InventoryMutation( + command_uuid=command, + effect_key=f"{operation}:{command}", + operation=operation, + actor_type="test", + actor_uuid="device-subtree-plr-only", + ) + + +@pytest.fixture +def service(tmp_path): + materials = MaterialsService(tmp_path / "materials.db") + materials.put_template( + _mutation("put_template"), + ResourceTemplateWrite(name="sample_tpl", display_name="sample", class_name="Resource"), + ) + try: + yield materials + finally: + materials.close() + + +@pytest.fixture +def device(service): + device_uuid = str(uuid4()) + config = ResourceDictInstance( + ResourceDict.model_validate( + { + "id": "plr-only-device", + "uuid": device_uuid, + "name": "plr-only-device", + "type": "device", + "class": DEVICE_TEMPLATE, + "template_name": DEVICE_TEMPLATE, + "config": {}, + "data": {}, + "extra": {}, + "sites": None, + "sites_initialized": False, + } + ) + ) + apply_device_authority_state( + config, + {"available_sites": [{"index": 1, "label": "s1"}, {"index": 2, "label": "s2"}]}, + DEVICE_TEMPLATE, + gateway=LocalMaterialsClient(service), + ) + return { + "uuid": device_uuid, + "sites": {site.label: site.site_uuid for site in service.get_material(device_uuid).sites}, + } + + +def _node(ref: str, *, plr_type: str | None, parent_ref: str | None = None) -> MaterialNodeCreate: + return MaterialNodeCreate( + client_ref=ref, + parent_client_ref=parent_ref, + identity=MaterialIdentityWrite( + resource_id=f"{ref}-{uuid4().hex[:8]}", + template_name="sample_tpl", + config={"type": plr_type} if plr_type else {}, + ), + ) + + +def _create(service, *nodes: MaterialNodeCreate, placement: MaterialPlacement | None = None) -> str: + created = service.create_tree( + _mutation("create_material_tree"), + MaterialTreeCreate(nodes=list(nodes), placement=placement), + ) + return created.data.root_material_uuid + + +def _move(service, material_uuid: str, **target) -> None: + service.move_material(_mutation("move_material"), MaterialMove(material_uuid=material_uuid, **target)) + + +def test_identity_only_material_cannot_be_placed_on_a_device_site(service, device) -> None: + bare = _create(service, _node("bare", plr_type=None)) + + with pytest.raises(MaterialValidationError, match="config.type"): + _move(service, bare, destination_site_uuid=device["sites"]["s1"]) + + assert service.get_material(bare).material.parent_material_uuid is None + assert all(site.occupied_material_uuid is None for site in service.get_material(device["uuid"]).sites) + + +def test_identity_only_material_cannot_be_mounted_on_the_device_itself(service, device) -> None: + bare = _create(service, _node("bare", plr_type=None)) + + with pytest.raises(MaterialValidationError, match="只收 PLR 物料"): + _move(service, bare, parent_material_uuid=device["uuid"]) + + +def test_plr_material_is_placed_on_a_device_site(service, device) -> None: + plate = _create(service, _node("plate", plr_type="Plate")) + + _move(service, plate, destination_site_uuid=device["sites"]["s1"]) + + assert service.get_material(plate).material.parent_material_uuid == device["uuid"] + + +def test_every_node_of_the_moved_tree_must_be_plr(service, device) -> None: + rack = _create( + service, + _node("rack", plr_type="TubeRack"), + _node("tube", plr_type=None, parent_ref="rack"), + ) + + with pytest.raises(MaterialValidationError, match="tube"): + _move(service, rack, destination_site_uuid=device["sites"]["s1"]) + + +def test_rule_applies_below_the_device_not_only_on_it(service, device) -> None: + carrier = _create(service, _node("carrier", plr_type="Resource")) + _move(service, carrier, destination_site_uuid=device["sites"]["s1"]) + bare = _create(service, _node("bare", plr_type=None)) + + with pytest.raises(MaterialValidationError, match="plr-only-device"): + _move(service, bare, parent_material_uuid=carrier) + + +def test_identity_only_material_still_goes_on_plain_shelves(service) -> None: + shelf = _create(service, _node("shelf", plr_type=None)) + bare = _create(service, _node("bare", plr_type=None)) + + _move(service, bare, parent_material_uuid=shelf) + + assert service.get_material(bare).material.parent_material_uuid == shelf + + +def test_device_created_with_identity_only_children_is_rejected(service) -> None: + service.put_template( + _mutation("put_template"), + ResourceTemplateWrite(name="bench_tpl", display_name="bench", resource_type="device", class_name="bench_tpl"), + ) + before = len(service.list_materials()) + device = MaterialNodeCreate( + client_ref="bench", + identity=MaterialIdentityWrite( + resource_id=f"bench-{uuid4().hex[:8]}", + resource_type="device", + class_name="bench_tpl", + template_name="bench_tpl", + ), + ) + + with pytest.raises(MaterialValidationError, match="config.type"): + _create(service, device, _node("bare", plr_type=None, parent_ref="bench")) + + assert len(service.list_materials()) == before + + +def test_device_created_with_plr_children_is_accepted(service) -> None: + service.put_template( + _mutation("put_template"), + ResourceTemplateWrite(name="bench_tpl", display_name="bench", resource_type="device", class_name="bench_tpl"), + ) + device = MaterialNodeCreate( + client_ref="bench", + identity=MaterialIdentityWrite( + resource_id=f"bench-{uuid4().hex[:8]}", + resource_type="device", + class_name="bench_tpl", + template_name="bench_tpl", + ), + ) + + bench = _create(service, device, _node("plate", plr_type="Plate", parent_ref="bench")) + + assert service.get_material(bench).material.resource_type == "device" + + +def test_create_and_place_on_a_device_rolls_back_identity_only_trees(service, device) -> None: + before = {item.material.material_uuid for item in service.list_materials()} + + with pytest.raises(MaterialValidationError, match="config.type"): + _create( + service, + _node("bare", plr_type=None), + placement=MaterialPlacement(parent_material_uuid=device["uuid"], site=device["sites"]["s2"]), + ) + + assert {item.material.material_uuid for item in service.list_materials()} == before + + +def test_create_and_place_on_a_device_site_commits_plr_trees(service, device) -> None: + plate = _create( + service, + _node("plate", plr_type="Plate"), + placement=MaterialPlacement(parent_material_uuid=device["uuid"], site=device["sites"]["s2"]), + ) + + sites = {site.label: site for site in service.get_material(device["uuid"]).sites} + assert sites["s2"].occupied_material_uuid == plate + assert service.get_material(plate).material.parent_material_uuid == device["uuid"] diff --git a/unilabos/client/host/runtime/driver_creator.py b/unilabos/client/host/runtime/driver_creator.py index c7feac41c..b997b0379 100644 --- a/unilabos/client/host/runtime/driver_creator.py +++ b/unilabos/client/host/runtime/driver_creator.py @@ -58,9 +58,25 @@ def attach_resource(self) -> None: # 再实例化一份会让同一权威物料有两个实例,uuid 索引指向驱动手里没有的副本。 if str(child.res_content.uuid or "") in self.resource_tracker.uuid_to_resources: continue - resource = ResourceTreeSet( - [ResourceTreeInstance(child)] - ).to_plr_resources()[0] + tree = ResourceTreeInstance(child) + missing = [ + node.res_content.id + for node in tree.get_all_nodes() + if node.res_content.type != "device" + and not str((node.res_content.config or {}).get("type") or "").strip() + ] + if missing: + # 设备子树只收 PLR 物料(权威在落位时拒绝新的);旧数据里遗留的非 PLR 物料 + # 反序列化不了:不挂到本地,整台设备照常启动,日志点名让人处理。 + logger.error( + "设备 %s 下的物料 %s 不是 PLR 物料(%s 没有 config.type),没有挂到设备本地;" + "请移走或删除它,再按注册表资源类经 materials.create 重新创建", + getattr(self.device_cls, "__name__", self.device_cls), + child.res_content.id, + "、".join(missing[:5]), + ) + continue + resource = ResourceTreeSet([tree]).to_plr_resources()[0] self.resource_tracker.add_resource(resource) def create_instance(self, data: Dict[str, Any]) -> T: diff --git a/unilabos/client/host/runtime/node.py b/unilabos/client/host/runtime/node.py index f5162226e..368ea4bc3 100644 --- a/unilabos/client/host/runtime/node.py +++ b/unilabos/client/host/runtime/node.py @@ -824,6 +824,29 @@ async def _attach_root_to_device(self, material_uuid: str) -> None: except Exception as exc: # noqa: BLE001 - 设备不是权威物料时(未登记)保持原样 self.lab_logger().debug(f"[AR:{material_uuid}] 设备挂载未落 parent({exc}),按根树保留") + async def _device_site_uuid(self, selector: Any | None) -> Optional[str]: + """设备自身库位的选择器解析成权威 Site uuid。 + + 与 ``materials.create(site=...)`` 同一套规则:按 Site uuid、label 或 Site 自己的 + ``index``(设备库位声明里的编号,不是列表序号)匹配,必须唯一命中。 + 未指定返回 None;指定了却找不到(或不唯一)直接报错,不退回「只落父子关系」。 + """ + + if selector is None or str(selector).strip() == "": + return None + normalized = str(selector).strip() + tree_set = await self.get_resource(resources_uuid=[self.resource_uuid], with_children=False) + sites = list(tree_set.trees[0].root_node.res_content.sites or []) if tree_set.trees else [] + matches = [ + site for site in sites if normalized in {str(site.uuid), str(site.label), str(site.index)} + ] + if len(matches) != 1: + raise ValueError( + f"设备 {self.device_id!r} 的库位 {selector!r} {'不存在' if not matches else '不唯一'};" + f"可用: {[site.label for site in sites]}" + ) + return str(matches[0].uuid) + @staticmethod def _occupied_site_uuid( tree_set: Any, owner_uuid: str, occupant_uuid: str @@ -932,6 +955,13 @@ async def append_resource( parent_uuid = bind_parent_id else: parent_uuid = self.resource_tracker.figure_resource({"name": bind_parent_id}).unilabos_uuid + device_site_uuid: Optional[str] = None + if parent_uuid == self.resource_uuid and self.resource_uuid: + # 设备自身的库位在提交点之前解析:选择器无效时什么都不改 + stage = "解析设备库位" + device_site_uuid = site_uuid or await self._device_site_uuid(additional_params.get("slot")) + if device_site_uuid is not None and len(resource_uuids) != 1: + raise ValueError("一个库位只能放一个物料:指定设备库位时一次只能挂一个物料") drafts = tree_set.to_plr_resources() # 提交点:此后本地 PLR 挂载、权威 move 与快照回报必须一起走完 if commit_point is not None and not commit_point.enter(): @@ -997,8 +1027,17 @@ async def append_resource( ), ) elif self.resource_uuid: + # 设备自身的库位:给了 site/slot 就经权威 move 占用设备库位;否则只落父子关系 for material_uuid in resource_uuids: - await self._attach_root_to_device(material_uuid) + if device_site_uuid is None: + await self._attach_root_to_device(material_uuid) + continue + await self._require_resource_service().move_resource( + self.device_id, + self.resource_uuid, + material_uuid, + destination_site_uuid=device_site_uuid, + ) # 4. 同步:挂载后的父树经 update_resource 直连权威(权威已有 create 记录,严禁 add) stage = "快照回报" for tree in report_tree_set.trees: diff --git a/unilabos/protocol/materials.py b/unilabos/protocol/materials.py index d4a300f3d..f1b53fc84 100644 --- a/unilabos/protocol/materials.py +++ b/unilabos/protocol/materials.py @@ -386,8 +386,23 @@ class MaterialNodeCreate(ServerObject): sites: list[SiteCreate] = Field(default_factory=list) +class MaterialPlacement(ServerObject): + """新建根物料的落位:挂到哪个父物料、占哪个库位,在建树的同一事务里提交。 + + 与 ``MaterialTransferItem`` 同形:``site`` 是父物料上的库位选择器(Site uuid、label 或 + 数字索引),由权威按父物料解析;省略时只落父子关系、不占库位。落位规则与 move 完全一致 + (库位占用、模板类别、入口预留、环检测、设备子树只收 PLR 物料),任何一条不满足时 + 整棵树连同落位一起回滚,不留下没有落位的根物料。 + """ + + parent_material_uuid: NonEmptyStr + site: Optional[Union[int, NonEmptyStr]] = None + + class MaterialTreeCreate(ServerObject): nodes: list[MaterialNodeCreate] + #: 根物料建好后在同一事务里落位;省略时根物料不挂任何父物料。 + placement: Optional[MaterialPlacement] = None @model_validator(mode="after") def _validate_tree(self) -> "MaterialTreeCreate": @@ -963,6 +978,7 @@ class MaterialDeltaResult(ServerObject): "MaterialIdentityRead", "MaterialIdentityWrite", "MaterialMove", + "MaterialPlacement", "MaterialNodeCreate", "MaterialPatch", "MaterialPosition", diff --git a/unilabos/resources/adapters/plr_materials.py b/unilabos/resources/adapters/plr_materials.py index a73ff22eb..afed939bd 100644 --- a/unilabos/resources/adapters/plr_materials.py +++ b/unilabos/resources/adapters/plr_materials.py @@ -23,6 +23,7 @@ MaterialMove, MaterialNodeCreate, MaterialNodeDelta, + MaterialPlacement, MaterialPosition, MaterialSnapshot, MaterialSnapshotDiff, @@ -626,18 +627,28 @@ def create_plr_materials( resources: Sequence[Any], *, root_extra: dict[str, Any] | None = None, + placement: MaterialPlacement | None = None, + display_name: str = "", ) -> CreatedPLRMaterials: """把 PLR 草稿发给权威创建;``root_extra`` 合并进根节点 identity.extra。 根 extra 是树级元数据的落点(如所属设备 ``unilabos_bound_device_id``); 在 create 请求上合并可保证入库即带元数据,且不修改调用方的输入实例。 + ``placement`` 让权威在建树的同一事务里把根物料落到父物料 / 库位上(原子)。 + ``display_name`` 是根物料的人读标签(省略时取 PLR 名);PLR 运行时不承载展示名, + 之后的快照也不会改写它。 """ request = plr_resources_to_create(resources) - if root_extra: - for node in request.nodes: - if node.parent_client_ref is None: - node.identity.extra = {**node.identity.extra, **root_extra} + for node in request.nodes: + if node.parent_client_ref is not None: + continue + if root_extra: + node.identity.extra = {**node.identity.extra, **root_extra} + if display_name.strip(): + node.identity.display_name = display_name.strip() + if placement is not None: + request.placement = placement result = gateway.create_tree(mutation, request) tree = material_tree_to_resource_tree(result.data) return CreatedPLRMaterials( diff --git a/unilabos/resources/materials.py b/unilabos/resources/materials.py index f3b6eb7fb..7f25c7c83 100644 --- a/unilabos/resources/materials.py +++ b/unilabos/resources/materials.py @@ -22,6 +22,7 @@ from __future__ import annotations import asyncio +import dataclasses import json from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from uuid import UUID, uuid4 @@ -42,6 +43,7 @@ ACTOR_DEVICE, ACTOR_EDGE, MaterialMove, + MaterialPlacement, MaterialTransfer, MaterialTransferItem, MaterialTreeRead, @@ -666,11 +668,106 @@ def instantiate_registry_resource(class_name: str, name: str) -> PLRResource: return draft +def _parent_material_uuid(node: Any | None, parent: Any | None) -> str: + """落位的父物料归一成权威 uuid。 + + ``parent`` 省略或就是设备节点本身时表示「设备自身」(设备物料,需要 ``node``); + 否则接受 PLR 实例、资源 dict 或 uuid 字符串。 + """ + + if parent is None or parent is node: + if node is None: + raise ValueError("落位需要 parent,或传入 node 表示放到设备自身") + device_uuid = str(getattr(node, "resource_uuid", "") or "").strip() + if not device_uuid: + raise ValueError( + f"设备 {getattr(node, 'device_id', node)!r} 在物料权威里没有设备物料,不能放到设备自身" + ) + return device_uuid + return material_uuid(parent, "父") + + +def _site_instance_uuid(site: Any) -> str | None: + """库位实例的 uuid(``ResourceSite.uuid`` / ``SiteRead.site_uuid``);不是库位实例时返回 None。""" + + for attribute in ("site_uuid", "uuid"): + value = getattr(site, attribute, None) + if isinstance(value, str) and value.strip(): + return value.strip() + return None + + +def _site_uuid(site: Any, parent_uuid: str, gateway: MaterialGateway) -> str: + """库位参数归一成权威 Site uuid。 + + 库位实例(``ResourceSite.uuid`` / ``SiteRead.site_uuid``)直接取 uuid;字符串或数字按父物料的 + 库位解析(uuid、label 或 ``site_index``,必须唯一命中)。 + """ + + direct = _site_instance_uuid(site) + if direct is not None: + return direct + selector = str(site).strip() + if not selector: + raise ValueError("库位不能为空") + sites = list(gateway.get_material(parent_uuid).sites) + matches = [ + item + for item in sites + if selector in {str(item.site_uuid), str(item.label), str(item.site_index)} + ] + if len(matches) != 1: + raise ValueError( + f"父物料 {parent_uuid} 上的库位 {site!r} " + f"{'不存在' if not matches else '不唯一'};可用: {[item.label for item in sites]}" + ) + return str(matches[0].site_uuid) + + +def _attach_placed( + node: Any, + created: CreatedPLRMaterials, + site_uuid: str | None, + command_uuid: str, + timeout: float, +) -> CreatedPLRMaterials: + """权威已在同一事务里建好并落位:本地按 transfer 的 load 投影挂上,返回 tracker 里的实例。 + + 与跨设备转运落到目标设备走同一条投影(``node.material_sync``),本地不另起一条挂载 + 逻辑;投影期间不回写快照。返回值里的实例就是设备 tracker 登记的那一份(uuid → 实例唯一)。 + """ + + from unilabos.client.host.runtime.async_utils import run_node_coroutine + + root_uuid = str(created.tree.trees[0].root_node.res_content.uuid) + run_node_coroutine( + node, + node.material_sync( + { + "transfer_uuid": f"create:{command_uuid}", + "device_id": str(node.device_id), + "action": "load", + "material_uuids": [root_uuid], + "destination_site_uuids": [site_uuid], + } + ), + timeout, + ) + instance = node.resource_tracker.uuid_to_resources.get(root_uuid) + if instance is None: + raise RuntimeError(f"物料 {root_uuid} 已在权威创建并落位,但本地挂载后 tracker 里没有它") + return dataclasses.replace(created, resources=[instance]) + + def create( plr_resource: Any | Sequence[Any] | str, *, name: str = "", + display_name: str = "", node: Any | None = None, + parent: Any | None = None, + site: Any | None = None, + timeout: float = 30.0, unwrap_single: bool = True, mutation: InventoryMutation | None = None, gateway: MaterialGateway | None = None, @@ -696,6 +793,18 @@ def create( 一次 create 只允许一个根;根的所有 children 仍属于同一棵创建树。 + ``display_name`` 是根物料的人读标签(前端展示名,省略时取 PLR 名)。PLR 名是物料的 + 业务键(根物料的 ``resource_id``,要全局唯一),展示名可以重名、可以是中文。 + + 落位(原子):给 ``parent`` / ``site`` 时,权威在建树的同一事务里把根物料挂到父物料、 + 占用库位,任何一步不满足(库位已占、类别不符、设备子树只收 PLR 物料……)整体回滚, + 不会留下没落位的根物料。 + + - ``parent``:父物料(PLR 实例或 uuid);省略或传设备节点本身表示设备自身; + - ``site``:库位实例(``post_init`` 给的 ``ResourceSite``)、Site uuid、label 或数字索引; + - 落位成功后本地按 transfer 的 load 投影挂上(需要 ``node``,且不能在节点执行器线程里 + 调用,同 :func:`assign`),返回 tracker 里的那一份实例;``timeout`` 约束本地挂载。 + 变更来源(账本 ``actor_type`` / ``actor_uuid``,前端据此渲染来源 tag): 未显式给出时,带 ``node=`` 视为设备创建(``device`` + 设备 id),否则 落 ``edge`` 兜底;传入 ``mutation=`` 时以其自带的 actor 为准。 @@ -736,8 +845,18 @@ def create( actor_uuid=resolved_actor_uuid or None, ) request = mutation + resolved_gateway = gateway or resolve_materials_gateway() + placement: MaterialPlacement | None = None + site_uuid: str | None = None + if parent is not None or site is not None: + if node is None: + raise ValueError("带落位的 create 需要 node:落位后要在设备本地挂上同一份实例") + parent_uuid = _parent_material_uuid(node, parent) + if site is not None: + site_uuid = _site_uuid(site, parent_uuid, resolved_gateway) + placement = MaterialPlacement(parent_material_uuid=parent_uuid, site=site_uuid) created = create_plr_materials( - gateway or resolve_materials_gateway(), + resolved_gateway, request, resources, root_extra=( @@ -745,10 +864,15 @@ def create( if node is not None else None ), + placement=placement, + display_name=display_name, ) if node is not None: - for resource in created.resources: - node.resource_tracker.add_resource(resource) + if placement is None: + for resource in created.resources: + node.resource_tracker.add_resource(resource) + else: + created = _attach_placed(node, created, site_uuid, request.command_uuid, timeout) if not unwrap_single: return created if len(created.resources) != 1: @@ -765,7 +889,7 @@ def assign( *, parent: Any | None = None, slot: Any | None = None, - site: str | None = None, + site: Any | None = None, location: Optional[Dict[str, float]] = None, timeout: float = 30.0, ) -> Dict[str, Any]: @@ -777,10 +901,14 @@ def assign( 执行并阻塞等待完成。 - ``resources``:PLR 实例(带权威 uuid)或 uuid 字符串,单个或列表; - - ``parent``:目标父物料(实例、uuid 或 PLR 键);None 表示挂到设备自身 - (只登记进 tracker,不做 assign); + - ``parent``:目标父物料(实例、uuid 或 PLR 键);省略或传设备节点本身表示挂到设备自身 + (本地是 tracker 根物料,不做 PLR assign;权威 parent 落设备物料); + - ``site``:库位实例(``post_init`` 给的 ``ResourceSite``)或权威 Site uuid; + label / 数字索引按 ``slot`` 处理; - ``slot``:label 或 0-based 数字字符串(如 ``"A1"`` / ``"0"``); - - ``site``:权威 ``ResourceSite`` uuid(与 slot 二选一,机器路径直传); + - 设备自身的库位同样适用:``assign(node, sample, site=sites["site_1"])`` 或 + ``slot="site_1"``,权威 move 占用设备库位;不给库位时只落父子关系; + - 一个库位只放一个物料:给了 ``site`` / ``slot`` 时一次只能挂一个物料; - ``timeout``:只约束提交点之前(等锁、从权威拉取物料),超时取消挂载、什么都不改; 本地挂上之后,权威 move 与快照回报一定走完再返回(大台面的整树快照要几十秒), 不会在提交之后被取消(见 ``DeviceNode.append_resource_blocking``)。 @@ -791,7 +919,7 @@ def assign( items = resources if isinstance(resources, (list, tuple)) else [resources] resource_uuids = [material_uuid(item) for item in items] - if parent is None: + if parent is None or parent is node: bind_parent_id = str(node.device_id) else: bind_parent_id = str( @@ -799,9 +927,22 @@ def assign( ) other: Dict[str, Any] = {} if slot is not None and str(slot).strip() != "": - other["slot"] = str(slot) - if site: - other["site"] = str(site) + other["slot"] = str(slot).strip() + if site is not None: + site_uuid = _site_instance_uuid(site) + selector = str(site).strip() + if site_uuid is None and _looks_like_uuid(selector): + site_uuid = selector + if site_uuid is not None: + other["site"] = site_uuid + elif selector: + if other.get("slot", selector) != selector: + raise ValueError(f"site={site!r} 与 slot={slot!r} 指向不同库位") + other["slot"] = selector + if ("site" in other or "slot" in other) and len(resource_uuids) != 1: + raise ValueError( + f"一个库位只能放一个物料:指定库位时一次只能挂一个物料,实际 {len(resource_uuids)} 个" + ) payload: Dict[str, Any] = { "device_id": str(node.device_id), "resource_uuid": resource_uuids, diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index f6a39be14..0bdad2f88 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import sqlite3 import threading import time @@ -54,6 +55,7 @@ MaterialDeviceSync, MaterialIdentityRead, MaterialMove, + MaterialPlacement, MaterialNodeCreate, MaterialPatch, MaterialDelta, @@ -2706,6 +2708,14 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: for node in value.nodes if node.parent_client_ref is None ) + # 设备连同下挂物料一起建(开机图对齐):与挂进设备子树同一条规则 + self._assert_device_subtree_accepts(client_map[root_ref], client_map[root_ref]) + if value.placement is not None: + placed = self._place_created_root( + mutation, client_map[root_ref], value.placement, timestamp + ) + affected.extend(placed.affected) + sequences.extend(placed.sequences) tree = self.get_tree(client_map[root_ref], client_ref_map=client_map) return _Applied(data=tree, affected=affected, sequences=sequences) @@ -2713,6 +2723,31 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: mutation, value, MutationResult[MaterialTreeRead], apply ) + def _place_created_root( + self, + mutation: InventoryMutation, + root_uuid: str, + placement: MaterialPlacement, + timestamp: int, + ) -> _Applied[MaterialAggregateRead]: + """建树事务里把新根物料落到 ``placement``:解析库位后按 move 的同一套规则提交。 + + 库位选择器按父物料解析(uuid / label / 数字索引,与 transfer 一致);落位失败时抛出, + 由外层事务把整棵新树一起回滚。 + """ + + parent = self._aggregate(placement.parent_material_uuid) + site = self._transfer_destination_site(parent, placement.site) + return self._apply_material_move( + mutation, + MaterialMove( + material_uuid=root_uuid, + destination_site_uuid=site.site_uuid if site is not None else None, + parent_material_uuid=None if site is not None else placement.parent_material_uuid, + ), + timestamp, + ) + def _new_substance_records( self, material_uuid: str, @@ -3190,6 +3225,65 @@ def _assert_site_template_allowed(self, site: SiteRecord, *, template_uuid: str, conflict="site_template", ) + def _device_ancestor(self, material_uuid: Optional[str]) -> Optional[MaterialRecord]: + """``material_uuid`` 自身或沿权威 parent 链最近的设备物料;不在任何设备子树里返回 None。""" + + cursor, seen = material_uuid, set() + while cursor is not None and cursor not in seen: + seen.add(cursor) + record = MaterialsRepository.get_material(self, cursor) + if record is None: + return None + if record.resource_type == "device": + return record + cursor = record.parent_material_uuid + return None + + def _assert_device_subtree_accepts(self, material_uuid: str, parent_uuid: Optional[str]) -> None: + """设备子树只收 PLR 物料:设备启动时按 ``ResourceTreeSet`` 把整棵子树反序列化成 PLR 实例。 + + 新父物料是设备或设备的后代时,挂进来的整棵树里每个物料节点都要有 ``config.type`` + (PLR 自己的类型名,反序列化靠它找类);子设备本身不受限。只有身份的物料(网关手写、 + 模板实例化不了)在这里被拒绝,而不是等设备重启时整台设备起不来。 + """ + + device = self._device_ancestor(parent_uuid) + if device is None: + return + rows = self.connection.execute( + """ + WITH RECURSIVE subtree(material_uuid) AS ( + SELECT ? + UNION ALL + SELECT m.material_uuid FROM material m + JOIN subtree s ON m.parent_material_uuid = s.material_uuid + WHERE m.deleted_at_ms IS NULL + ) + SELECT m.resource_id, m.resource_type, m.config_json + FROM material m JOIN subtree s ON m.material_uuid = s.material_uuid + """, + (material_uuid,), + ).fetchall() + missing: list[str] = [] + for resource_id, resource_type, config_json in rows: + if resource_type == "device": + continue + try: + config = json.loads(config_json or "{}") + except (TypeError, ValueError): + config = {} + plr_type = config.get("type") if isinstance(config, dict) else None + if not isinstance(plr_type, str) or not plr_type.strip(): + missing.append(str(resource_id)) + if missing: + shown = "、".join(missing[:5]) + (f" 等 {len(missing)} 个" if len(missing) > 5 else "") + raise MaterialValidationError( + f"设备 {device.resource_id} 的子树只收 PLR 物料:{shown} 没有 config.type" + "(PLR 类型名),设备启动时无法反序列化。请按注册表资源类经 materials.create" + "(ResourceTreeSet)创建物料再放上设备", + subject="material", + ) + def _assert_no_parent_cycle(self, material_uuid: str, parent_uuid: Optional[str]) -> None: """新父物料不能是物料自己或它的后代(V1 6004);库位所属物料是新父物料时同样适用。""" @@ -3295,6 +3389,7 @@ def _apply_material_move( and material.parent_material_uuid == parent_uuid ): raise MaterialNoChangeError("material is already at destination") + self._assert_device_subtree_accepts(value.material_uuid, parent_uuid) affected: list[AggregateVersion] = [] sequences: list[int] = [] From 8c106e0515073a695c0e468d1faf266d1782f3f0 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:01:21 +0800 Subject: [PATCH 02/59] fix(devices): virtual heating platform keeps PLR samples on its own sites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The heater used to write its samples straight into the materials authority (class Resource, no PLR serialization) and move them onto the device's Sites. After a restart the device rebuilds its children as PLR resources, so those samples made the whole device fail to start. - VirtualHeatingSample is a registered PLR resource (virtual_heating_sample); temperature and heating progress are its own state and round-trip through serialize_state / load_state. - Samples are created with materials.create(..., node=, site=) on the device's own Sites (atomic create-and-place, display name 加热样品 N). - On restart the driver adopts the instances the framework re-attached, mapping each Site's occupant uuid to the tracker instance; no duplicates. - Each heating step reports the sample through materials.update; no direct gateway writes and no private platform material remain. --- .../host/hostlink/test_materials_proxy.py | 7 + .../test_virtual_heating_platform_dispatch.py | 11 +- .../devices/test_virtual_heating_platform.py | 262 +++++--- tests/heating_fixtures.py | 50 ++ unilabos/devices/virtual/heating_platform.py | 627 ++++++++++-------- 5 files changed, 592 insertions(+), 365 deletions(-) create mode 100644 tests/heating_fixtures.py diff --git a/tests/client/host/hostlink/test_materials_proxy.py b/tests/client/host/hostlink/test_materials_proxy.py index bc9664d65..489270f04 100644 --- a/tests/client/host/hostlink/test_materials_proxy.py +++ b/tests/client/host/hostlink/test_materials_proxy.py @@ -19,6 +19,7 @@ ) from unilabos.server.execution_composition import set_materials_gateway from unilabos.server.services.materials import MaterialsService +from tests.heating_fixtures import heating_device_config def _mutation(operation: str) -> InventoryMutation: @@ -213,6 +214,10 @@ def test_remote_heating_demo_provisions_after_connect_and_writes_host_materials( HostLinkConfig.port = host.server.port BasicConfig.is_host_mode = False + # Slave 启动时 Host 可达:设备物料在 Host 权威里装配好(与启动时 definition 同一步) + heater_config = heating_device_config( + "remote-virtual-heater", LocalMaterialsClient(service) + ) local = HostLinkLocalRuntime() local.add_driver( HostLinkDriverSpec( @@ -220,6 +225,8 @@ def test_remote_heating_demo_provisions_after_connect_and_writes_host_materials( driver_class=VirtualHeatingPlatform, config={"update_interval_s": 0.05}, registry_name="virtual_heating_platform", + resource_uuid=heater_config.res_content.uuid, + device_config=heater_config, action_names=("heat_site",), status_names=( "site_1_temperature_c", diff --git a/tests/client/host/hostlink/test_virtual_heating_platform_dispatch.py b/tests/client/host/hostlink/test_virtual_heating_platform_dispatch.py index 03d6b876f..ce9623181 100644 --- a/tests/client/host/hostlink/test_virtual_heating_platform_dispatch.py +++ b/tests/client/host/hostlink/test_virtual_heating_platform_dispatch.py @@ -16,6 +16,7 @@ from unilabos.server.execution_composition import set_materials_gateway from unilabos.server.services.materials import MaterialsService from unilabos.server.services.telemetry import TelemetryService +from tests.heating_fixtures import heating_device_config class PhysicalHeater: @@ -80,6 +81,10 @@ def test_test_mode_executes_only_explicit_virtual_simulator_and_records_status_h action_names=("heat",), ) ) + # 设备物料按注册表 available_sites 在权威里装配(与启动时 definition 同一步) + heater_config = heating_device_config( + "virtual-heater", LocalMaterialsClient(material_service) + ) local.add_driver( HostLinkDriverSpec( device_id="virtual-heater", @@ -87,6 +92,8 @@ def test_test_mode_executes_only_explicit_virtual_simulator_and_records_status_h # 按真实时长加热:遥测里要留下升温过程的多个点 config={"update_interval_s": 0.05, "time_scale": 1.0}, registry_name="virtual_heating_platform", + resource_uuid=heater_config.res_content.uuid, + device_config=heater_config, action_names=("heat_site",), status_names=( "status", @@ -180,7 +187,9 @@ def test_test_mode_executes_only_explicit_virtual_simulator_and_records_status_h "device_id": "virtual-heater", "property": "site_1_temperature_c", } - assert material.data.source_job_uuid == virtual.job_id + # 样品是设备上的 PLR 物料:温度经设备的物料回报写入(来源是设备,不是手写的数据写入) + assert material.material.parent_material_uuid == heater_config.res_content.uuid + assert material.material.config["type"] == "VirtualHeatingSample" finally: backend.stop() if adapter is not None: diff --git a/tests/devices/test_virtual_heating_platform.py b/tests/devices/test_virtual_heating_platform.py index edf8f35f5..251729a64 100644 --- a/tests/devices/test_virtual_heating_platform.py +++ b/tests/devices/test_virtual_heating_platform.py @@ -3,19 +3,28 @@ import inspect import json from pathlib import Path +from uuid import uuid4 +import pytest + +from unilabos.client.host.hostlink.local_runtime import HostLinkDriverSpec, HostLinkLocalRuntime +from unilabos.client.host.runtime.action import ActionContext +from unilabos.client.host.runtime.resource import AuthorityResourceService from unilabos.client.materials import LocalMaterialsClient from unilabos.config.config import BasicConfig -from unilabos.client.host.runtime.action import ActionContext from unilabos.devices.virtual.heating_platform import ( SAMPLE_DISPLAY_COLORS, + SAMPLE_TEMPLATE, VirtualHeatingPlatform, + VirtualHeatingSample, ) from unilabos.registry.ast_registry_scanner import _parse_file from unilabos.registry.decorators import get_device_meta from unilabos.resources.objects.resource import ResourceDict +from unilabos.resources.resource_tracker import ResourceDictInstance from unilabos.server.execution_composition import set_materials_gateway from unilabos.server.services.materials import MaterialsService +from tests.heating_fixtures import heating_device_config def test_virtual_heating_platform_is_registry_discoverable_and_demo_graph_is_strict() -> ( @@ -32,9 +41,13 @@ def test_virtual_heating_platform_is_registry_discoverable_and_demo_graph_is_str source = Path(inspect.getfile(VirtualHeatingPlatform)).resolve() repository_root = Path(__file__).resolve().parents[2] - devices, _resources, _workflows = _parse_file(source, repository_root) + devices, resources, _workflows = _parse_file(source, repository_root) assert devices[0]["device_id"] == "virtual_heating_platform" assert "serialized_state" in devices[0]["status_properties"] + # 样品是注册表里的 PLR 资源类:权威里的模板名就是这个资源 id + sample_entry = next(item for item in resources if item["resource_id"] == SAMPLE_TEMPLATE) + assert sample_entry["module"] == "unilabos.devices.virtual.heating_platform:VirtualHeatingSample" + assert sample_entry["category"] == ["heating_sample"] graph_path = ( repository_root @@ -51,87 +64,188 @@ def test_virtual_heating_platform_is_registry_discoverable_and_demo_graph_is_str assert [site.label for site in device.sites or []] == ["site_1", "site_2", "site_3"] -def test_virtual_heating_platform_creates_places_and_heats_real_materials( - tmp_path, monkeypatch -) -> None: - service = MaterialsService(tmp_path / "materials.db") - monkeypatch.setattr(BasicConfig, "is_host_mode", True) - set_materials_gateway(LocalMaterialsClient(service)) - try: - platform = VirtualHeatingPlatform("heater-demo", {"update_interval_s": 0.05}) - - assert platform.initialize() is True - root = service.get_material_by_resource_id("heater-demo") - assert len(root.sites) == 3 - assert all(site.occupied_material_uuid for site in root.sites) - assert len(service.list_materials()) == 4 - samples = [ - service.get_material(site.occupied_material_uuid) - for site in root.sites - if site.occupied_material_uuid - ] - assert [item.material.meta_data["display_color"] for item in samples] == list( - SAMPLE_DISPLAY_COLORS - ) +def test_sample_state_round_trips_through_plr_serialization() -> None: + sample = VirtualHeatingSample("probe") + sample.record_temperature( + site_id=2, + source={"device_id": "heater", "property": "site_2_temperature_c"}, + temperature_c=61.23456, + target_temperature_c=80.0, + progress=50.0, + state="heating", + observed_at_ms=1234, + ) + + restored = VirtualHeatingSample.deserialize(sample.serialize()) + restored.load_state(sample.serialize_state()) + + assert restored.serialize_state() == sample.serialize_state() + assert restored.temperature_c == 61.235 + assert restored.state == "heating" - result = platform.heat_site( - site_id=2, - target_temperature_c=72.5, - duration_seconds=0.1, - action_context=ActionContext(action_id="demo-job-1"), + +class _Heater: + """一台跑在 HostLink 本地运行时上的加热平台:设备物料按注册表 available_sites 在权威里装配。""" + + def __init__(self, service: MaterialsService, device_id: str, config: dict | None = None) -> None: + self.service = service + self.gateway = LocalMaterialsClient(service) + self.device_id = device_id + self.config = dict(config or {"update_interval_s": 0.05}) + self.device_uuid = str(uuid4()) + self.runtime: HostLinkLocalRuntime | None = None + self.node = None + + def _device_config(self) -> ResourceDictInstance: + # 权威优先装配:已有设备时取权威的 Site 与下挂物料(重启时样品从这里挂回) + return heating_device_config(self.device_id, self.gateway, device_uuid=self.device_uuid) + + def start(self) -> VirtualHeatingPlatform: + self.runtime = HostLinkLocalRuntime() + self.node = self.runtime.add_driver( + HostLinkDriverSpec( + self.device_id, + VirtualHeatingPlatform, + self.config, + registry_name="virtual_heating_platform", + resource_uuid=self.device_uuid, + device_config=self._device_config(), + ) ) + self.runtime.set_resource_service(AuthorityResourceService(self.gateway)) + self.runtime.start() + return self.node.driver - material = service.get_material(result["material_uuid"]) - assert material.data.data["temperature_c"] == 72.5 - assert material.data.data["serialized_state"] == { - "site_id": 2, - "temperature_c": 72.5, - "target_temperature_c": 72.5, - "progress": 100.0, - "state": "completed", - "observed_at_ms": material.data.data["serialized_state"]["observed_at_ms"], - } - assert "temperature_history" not in material.data.data - assert material.data.data["temperature_source"] == { - "device_id": "heater-demo", - "property": "site_2_temperature_c", - } - assert material.data.source_job_uuid == "demo-job-1" - - serialized = platform.serialize() - assert serialized["platform_material_uuid"] == root.material.material_uuid - assert [site["material_uuid"] for site in serialized["sites"]] == [ - site.occupied_material_uuid for site in root.sites - ] - assert serialized["sites"][1]["temperature_c"] == 72.5 - finally: - set_materials_gateway(None) - service.close() + def stop(self) -> None: + if self.runtime is not None: + self.runtime.stop() + self.runtime = None + def sites(self) -> dict[str, object]: + return {site.label: site for site in self.service.get_material(self.device_uuid).sites} -def test_material_temperature_is_latest_passive_device_projection( - tmp_path, monkeypatch -) -> None: + +@pytest.fixture +def heater(tmp_path, monkeypatch): service = MaterialsService(tmp_path / "materials.db") monkeypatch.setattr(BasicConfig, "is_host_mode", True) set_materials_gateway(LocalMaterialsClient(service)) + rig = _Heater(service, "heater-demo") try: - platform = VirtualHeatingPlatform("heater-history", {"update_interval_s": 0.05}) - platform.initialize() - for index in range(3): - platform._write_material_temperature( - 1, - temperature_c=25.0 + index, - target_temperature_c=150.0, - state="heating", - progress=float(index), - job_uuid="history-job", - ) - material = service.get_material_by_resource_id("heater-history-sample-1") - assert material.data.data["temperature_c"] == 27.0 - assert "temperature_history" not in material.data.data - assert material.data.data["temperature_observed_at_ms"] > 0 - assert platform.site_1_temperature_c == 27.0 + yield rig finally: + rig.stop() set_materials_gateway(None) service.close() + + +def test_heater_creates_plr_samples_on_its_own_sites_and_heats_them(heater) -> None: + platform = heater.start() + service = heater.service + + sites = heater.sites() + assert len(sites) == 3 and all(site.occupied_material_uuid for site in sites.values()) + # 只有设备物料和三个样品;没有私有的"平台物料" + assert len(service.list_materials()) == 4 + tracker = heater.node.resource_tracker + for index, label in enumerate(("site_1", "site_2", "site_3"), start=1): + sample = service.get_material(sites[label].occupied_material_uuid) + assert sample.material.parent_material_uuid == heater.device_uuid + assert sample.material.config["type"] == "VirtualHeatingSample" + assert sample.material.template_name == SAMPLE_TEMPLATE + assert sample.material.resource_id == f"heater-demo-sample-{index}" + assert sample.material.display_name == f"加热样品 {index}" + assert sample.material.barcode == f"OPENLAB-HEAT-{index}" + assert sample.material.meta_data["display_color"] == SAMPLE_DISPLAY_COLORS[index - 1] + # uuid → 实例唯一:驱动拿着的就是设备 tracker 登记的那一份 + instance = tracker.uuid_to_resources[sample.material.material_uuid] + assert isinstance(instance, VirtualHeatingSample) + assert platform._samples[index] is instance + + result = platform.heat_site( + site_id=2, + target_temperature_c=72.5, + duration_seconds=0.1, + action_context=ActionContext(action_id="demo-job-1"), + ) + + material = service.get_material(result["material_uuid"]) + assert material.data.data["temperature_c"] == 72.5 + assert material.data.data["serialized_state"] == { + "site_id": 2, + "temperature_c": 72.5, + "target_temperature_c": 72.5, + "progress": 100.0, + "state": "completed", + "observed_at_ms": material.data.data["serialized_state"]["observed_at_ms"], + } + assert "temperature_history" not in material.data.data + assert material.data.data["temperature_source"] == { + "device_id": "heater-demo", + "property": "site_2_temperature_c", + } + + serialized = platform.serialize() + assert serialized["platform_material_uuid"] == heater.device_uuid + assert [site["material_uuid"] for site in serialized["sites"]] == [ + sites[label].occupied_material_uuid for label in ("site_1", "site_2", "site_3") + ] + assert serialized["sites"][1]["temperature_c"] == 72.5 + assert serialized["sites"][1]["material_name"] == "加热样品 2" + + +def test_heater_restart_adopts_the_same_samples_with_their_temperature(heater) -> None: + """二次启动:样品由框架从权威反序列化成 PLR 实例挂回设备,驱动接管同一批,不重复创建。""" + + first = heater.start() + first.heat_site( + site_id=1, + target_temperature_c=60.0, + duration_seconds=0.1, + action_context=ActionContext(action_id="first-run"), + ) + before = {label: site.occupied_material_uuid for label, site in heater.sites().items()} + heater.stop() + + second = heater.start() + + assert {label: site.occupied_material_uuid for label, site in heater.sites().items()} == before + assert len(heater.service.list_materials()) == 4 + sample = second._samples[1] + assert isinstance(sample, VirtualHeatingSample) + assert sample.unilabos_uuid == before["site_1"] + assert heater.node.resource_tracker.uuid_to_resources[sample.unilabos_uuid] is sample + assert sample.temperature_c == 60.0 + assert second.site_1_temperature_c == 60.0 + assert second.serialize()["sites"][0]["material_name"] == "加热样品 1" + + result = second.heat_site( + site_id=1, + target_temperature_c=70.0, + duration_seconds=0.1, + action_context=ActionContext(action_id="second-run"), + ) + assert result["material_uuid"] == before["site_1"] + assert heater.service.get_material(before["site_1"]).data.data["temperature_c"] == 70.0 + + +def test_material_temperature_is_latest_passive_device_projection(heater) -> None: + platform = heater.start() + for index in range(3): + platform._write_material_temperature( + 1, + temperature_c=25.0 + index, + target_temperature_c=150.0, + state="heating", + progress=float(index), + ) + material = heater.service.get_material_by_resource_id("heater-demo-sample-1") + assert material.data.data["temperature_c"] == 27.0 + assert "temperature_history" not in material.data.data + assert material.data.data["temperature_observed_at_ms"] > 0 + assert platform.site_1_temperature_c == 27.0 + + +def test_heater_needs_its_device_node() -> None: + with pytest.raises(RuntimeError, match="post_init"): + VirtualHeatingPlatform("orphan-heater").initialize() diff --git a/tests/heating_fixtures.py b/tests/heating_fixtures.py new file mode 100644 index 000000000..22cf57f7e --- /dev/null +++ b/tests/heating_fixtures.py @@ -0,0 +1,50 @@ +"""虚拟加热平台的测试装配:设备物料按注册表 available_sites 在物料权威里装配。 + +与启动时 ``runtime/definition.py`` 同一步(``apply_device_authority_state``):权威没有该设备时 +以图中 uuid 创建设备物料与三个工位;已有时采用权威的工位与下挂物料(重启时样品从这里挂回)。 +""" + +from __future__ import annotations + +from typing import Any, Optional +from uuid import uuid4 + +from unilabos.devices.virtual.heating_platform import VirtualHeatingPlatform +from unilabos.registry.decorators import get_device_meta +from unilabos.resources.adapters.device_site import apply_device_authority_state +from unilabos.resources.objects.resource import ResourceDict +from unilabos.resources.resource_tracker import ResourceDictInstance + +HEATER_REGISTRY_NAME = "virtual_heating_platform" + + +def heating_device_config( + device_id: str, gateway: Any, *, device_uuid: Optional[str] = None +) -> ResourceDictInstance: + """加热平台的设备节点(图中形状),并在权威里装配好它的设备物料。""" + + config = ResourceDictInstance( + ResourceDict.model_validate( + { + "id": device_id, + "uuid": device_uuid or str(uuid4()), + "name": device_id, + "type": "device", + "class": HEATER_REGISTRY_NAME, + "template_name": HEATER_REGISTRY_NAME, + "config": {}, + "data": {}, + "extra": {}, + "sites": None, + "sites_initialized": False, + } + ) + ) + meta = get_device_meta(VirtualHeatingPlatform, HEATER_REGISTRY_NAME) + apply_device_authority_state( + config, + {"available_sites": meta["available_sites"]}, + HEATER_REGISTRY_NAME, + gateway=gateway, + ) + return config diff --git a/unilabos/devices/virtual/heating_platform.py b/unilabos/devices/virtual/heating_platform.py index e158908ea..e1e21eca2 100644 --- a/unilabos/devices/virtual/heating_platform.py +++ b/unilabos/devices/virtual/heating_platform.py @@ -5,7 +5,13 @@ * 动作经 HostLink 派发; * 标量状态走常规的设备状态通道发布; * 平台是温度的测量来源,按工位发布遥测; -* 物料身份、工位占用与最新温度投影都通过 ``materials.v1`` 写入物料权威,没有私有的演示存储。 +* 样品是 PLR 物料(:class:`VirtualHeatingSample`),经 client 物料服务创建并原子地放上设备自己的 + 工位(``materials.create(..., node=, site=)``);温度是样品自己的 PLR 状态,经 + ``serialize_state`` / ``load_state`` 往返权威,每次变化经 ``materials.update`` 回报。驱动不直接写 + 物料权威,也没有私有的演示存储。 + +设备重启时,工位上的样品由框架按权威反序列化成 PLR 实例挂回设备;驱动按权威的工位占用 +(Site uuid → 物料 uuid)在 tracker 里找到同一份实例接管,不重复创建。 加热时长是模拟时间:真实等待 = ``duration_seconds`` × 时间倍率(图节点 ``config.time_scale``, 没配时取设备类自带的默认值 0.001,很快);示例图把倍率设为 1,按真实时长画出升温曲线。 @@ -16,35 +22,30 @@ from copy import deepcopy import time from threading import RLock -from typing import Any -from uuid import uuid4 +from typing import Any, Mapping, Optional + +from pylabrobot.resources import Resource +from pylabrobot.resources.barcode import Barcode from unilabos.client.host.runtime.action import ActionContext from unilabos.client.host.hostlink.protocol import LinkError from unilabos.devices.virtual.simulation import DEFAULT_TIME_SCALE, resolve_time_scale -from unilabos.registry.decorators import action, device, not_action, topic_config +from unilabos.registry.decorators import action, device, not_action, resource, topic_config from unilabos.resources.objects.pose import ( ResourceDictPosition, ResourceDictPositionObject, ResourceDictPositionSize, ) +from unilabos.resources.objects.resource import EXTRA_RESOURCE_META_DATA from unilabos.resources.objects.site import SiteDefinition -from unilabos.protocol.materials import InventoryMutation -from unilabos.protocol.materials import ( - MaterialDataWrite, - MaterialIdentityWrite, - MaterialMove, - MaterialNodeCreate, - MaterialPosition, - MaterialTreeCreate, - ResourceTemplateWrite, - SiteCreate, -) from unilabos.utils import logger AMBIENT_TEMPERATURE_C = 25.0 SAMPLE_DISPLAY_COLORS = ("#2F80ED", "#9B51E0", "#27AE60") +#: 样品的注册表资源 id,也是它在物料权威里的资源模板名 +SAMPLE_TEMPLATE = "virtual_heating_sample" +SITE_IDS = (1, 2, 3) VIRTUAL_HEATING_PLATFORM_SITES = [ @@ -90,6 +91,122 @@ ] +def _site_label(site_id: int) -> str: + return f"site_{site_id}" + + +@resource( + # 注册表 AST 扫描只认字面量:与 SAMPLE_TEMPLATE 保持一致 + id="virtual_heating_sample", + category=["heating_sample"], + display_name="虚拟加热样品", + description="三工位虚拟加热平台上的样品;温度与加热进度是它自己的 PLR 状态", +) +class VirtualHeatingSample(Resource): + """虚拟加热平台上的样品。 + + 温度、目标温度与加热进度是样品自己的状态:``serialize_state`` 输出的就是物料权威里的 + ``data``(``temperature_c`` / ``target_temperature_c`` / ``temperature_observed_at_ms`` / + ``temperature_source`` / ``serialized_state``),``load_state`` 原样读回,设备重启后温度不丢。 + """ + + def __init__( + self, + name: str, + size_x: float = 60.0, + size_y: float = 60.0, + size_z: float = 40.0, + rotation: Any = None, + category: Optional[str] = "heating_sample", + model: Optional[str] = None, + barcode: Optional[Barcode] = None, + preferred_pickup_location: Any = None, + metadata: Optional[Mapping[str, Any]] = None, + ) -> None: + super().__init__( + name=name, + size_x=size_x, + size_y=size_y, + size_z=size_z, + rotation=rotation, + category=category, + model=model, + barcode=barcode, + preferred_pickup_location=preferred_pickup_location, + metadata=metadata, + ) + self.temperature_c = AMBIENT_TEMPERATURE_C + self.target_temperature_c = AMBIENT_TEMPERATURE_C + self.temperature_observed_at_ms = 0 + self.temperature_source: dict[str, Any] = {} + self.heating_state: dict[str, Any] = { + "temperature_c": AMBIENT_TEMPERATURE_C, + "state": "idle", + } + + @property + def state(self) -> str: + return str(self.heating_state.get("state", "idle")) + + def serialize_state(self) -> dict[str, Any]: + state = { + **super().serialize_state(), + "temperature_c": self.temperature_c, + "target_temperature_c": self.target_temperature_c, + "temperature_source": deepcopy(self.temperature_source), + "serialized_state": deepcopy(self.heating_state), + } + if self.temperature_observed_at_ms: + state["temperature_observed_at_ms"] = self.temperature_observed_at_ms + return state + + def load_state(self, state: dict[str, Any]) -> None: + super().load_state(state) + self.temperature_c = float(state.get("temperature_c", AMBIENT_TEMPERATURE_C)) + self.target_temperature_c = float( + state.get("target_temperature_c", self.temperature_c) + ) + self.temperature_observed_at_ms = int(state.get("temperature_observed_at_ms") or 0) + source = state.get("temperature_source") + self.temperature_source = dict(source) if isinstance(source, Mapping) else {} + heating = state.get("serialized_state") + self.heating_state = ( + dict(heating) + if isinstance(heating, Mapping) + else {"temperature_c": self.temperature_c, "state": "idle"} + ) + + def record_temperature( + self, + *, + site_id: int, + source: Mapping[str, Any], + temperature_c: float, + target_temperature_c: float, + progress: float, + state: str, + observed_at_ms: int, + ) -> None: + """记一次测量:被动投影最新值(遥测历史由设备状态通道负责,这里不攒历史)。 + + 只改实例状态,不触发 PLR 状态回调:平台随即经 ``materials.update`` 同步回报这份 + 状态(失败直接让动作失败),再排一份观察者快照只会是重复写入。 + """ + + self.temperature_c = round(float(temperature_c), 3) + self.target_temperature_c = round(float(target_temperature_c), 3) + self.temperature_observed_at_ms = int(observed_at_ms) + self.temperature_source = dict(source) + self.heating_state = { + "site_id": site_id, + "temperature_c": self.temperature_c, + "target_temperature_c": self.target_temperature_c, + "progress": round(float(progress), 3), + "state": state, + "observed_at_ms": int(observed_at_ms), + } + + @device( id="virtual_heating_platform", display_name="三工位虚拟加热平台", @@ -123,7 +240,12 @@ def __init__( self.time_scale = resolve_time_scale(self.config.get("time_scale"), self.default_time_scale) self._lock = RLock() self._provision_lock = RLock() + self._node: Any = None self._platform_uuid = "" + #: 工位号 → 设备库位(``post_init`` 给的 ``ResourceSite``) + self._device_sites: dict[int, Any] = {} + #: 工位号 → 工位上的样品实例(与设备 tracker 里登记的是同一份) + self._samples: dict[int, VirtualHeatingSample] = {} self._sites: dict[int, dict[str, Any]] = { index: { "site_id": index, @@ -135,9 +257,35 @@ def __init__( "progress": 0.0, "state": "idle", } - for index in range(1, 4) + for index in SITE_IDS } + # ------------------------------------------------------------------ + # 生命周期 + # ------------------------------------------------------------------ + + @not_action + def post_init( + self, + node: Any, + sites: Mapping[str, Any] | None = None, + site_resources: Mapping[str, Any] | None = None, + ) -> None: + """接住设备节点、设备自己的工位与工位上已有的样品(重启时由框架从权威挂回)。""" + + self._node = node + self._platform_uuid = str(getattr(node, "resource_uuid", "") or "") + for index in SITE_IDS: + label = _site_label(index) + site = (sites or {}).get(label) + if site is not None: + self._device_sites[index] = site + with self._lock: + self._sites[index]["site_uuid"] = str(site.uuid) + occupant = (site_resources or {}).get(label) + if occupant is not None: + self._adopt(index, occupant) + @not_action def initialize(self) -> bool: try: @@ -148,34 +296,23 @@ def initialize(self) -> bool: logger.info("[HeatingDemo] 物料初始化等待 HostLink 重连:%s", exc) return True - @not_action - def _provision_materials(self) -> None: - with self._provision_lock: - self._ensure_demo_materials() - self._refresh_material_state() - @not_action def on_hostlink_connected(self) -> None: """Idempotently materialize the demo after every HostLink reconnect.""" self._provision_materials() - @staticmethod - def _mutation( - operation: str, - effect_key: str, - *, - job_uuid: str | None = None, - ) -> InventoryMutation: - return InventoryMutation( - command_uuid=str(uuid4()), - effect_key=effect_key, - operation=operation, - actor_type="virtual_device", - actor_uuid="virtual_heating_platform", - job_uuid=job_uuid, - observed_at_ms=int(time.time() * 1000), - ) + # ------------------------------------------------------------------ + # 样品:uuid ↔ 实例 + # ------------------------------------------------------------------ + + @not_action + def _require_node(self) -> Any: + if self._node is None: + raise RuntimeError( + f"虚拟加热平台 {self.device_id} 还没有设备节点(post_init 未调用):样品要建在设备自己的工位上" + ) + return self._node @staticmethod def _gateway() -> Any: @@ -184,206 +321,154 @@ def _gateway() -> Any: return resolve_materials_gateway() @not_action - def _ensure_template( - self, - name: str, - *, - category: list[str], - available_sites: list[dict[str, Any]] | None = None, - ) -> None: - gateway = self._gateway() - # 存在性检查交给权威按 name 筛,只回目录字段 - if gateway.list_templates(name=name): - return - value = ResourceTemplateWrite( - name=name, - display_name=( - "三工位虚拟加热平台" - if name == "virtual_heating_platform" - else "虚拟加热样品" - ), - class_name=( - "VirtualHeatingPlatform" - if name == "virtual_heating_platform" - else "Resource" - ), - module_name=( - "unilabos.devices.virtual.heating_platform" - if name == "virtual_heating_platform" - else None - ), - category=category, - available_sites=list(available_sites or []), - definition={"demo": "openlab-heating", "schema_version": 1}, - ) - gateway.create_template( - self._mutation("put_template", f"ensure-template:{name}"), value - ) - - @not_action - def _material_by_resource_id(self, resource_id: str) -> Any | None: + def _display_name(self, material_uuid: str, fallback: str) -> str: try: - return self._gateway().get_material_by_resource_id(resource_id) - except ( - Exception - ) as exc: # different local/HTTP clients expose different 404 types - if ( - "not found" in str(exc).lower() - or getattr(exc, "status_code", None) == 404 - ): - return None - raise + return str(self._gateway().get_material(material_uuid).material.display_name or fallback) + except Exception: # noqa: BLE001 - 展示名只用于状态投影,读不到就用 PLR 名 + return fallback @not_action - def _ensure_demo_materials(self) -> None: - gateway = self._gateway() - site_definitions = [ - { - "schema_version": 1, - "template_name": "virtual_heating_platform", - "site_index": item.index, - "label": item.label, - "visible": item.visible, - "pose": item.pose.model_dump(mode="json"), - "allowed_resource_categories": item.allowed_resource_categories, - "parent_link": item.parent_link, - "description": item.description, - "meta_data": item.meta_data, - "extra": {}, - } - for item in VIRTUAL_HEATING_PLATFORM_SITES - ] - self._ensure_template( - "virtual_heating_platform", - category=["virtual_device", "heating"], - available_sites=site_definitions, - ) - self._ensure_template("virtual_heating_sample", category=["heating_sample"]) - - platform = self._material_by_resource_id(self.device_id) - if platform is None: - created = gateway.create_tree( - self._mutation("create_material_tree", "create-platform"), - MaterialTreeCreate( - nodes=[ - MaterialNodeCreate( - client_ref="platform", - identity=MaterialIdentityWrite( - resource_id=self.device_id, - display_name="三工位虚拟加热平台", - description="OpenLab HostLink heating demo", - resource_type="resource", - class_name="VirtualHeatingPlatform", - template_name="virtual_heating_platform", - meta_data={"demo": "openlab-heating", "site_count": 3}, - ), - data=MaterialDataWrite( - data={"serialized_state": {"site_count": 3}}, - sites_initialized=True, - state_status="ready", - ), - sites=[ - SiteCreate.model_validate(item) - for item in site_definitions - ], - ) - ] - ), + def _adopt(self, site_id: int, occupant: Any, *, display_name: str = "") -> None: + """登记工位上的物料;只有 :class:`VirtualHeatingSample` 能加热。""" + + material_uuid = str(getattr(occupant, "unilabos_uuid", "") or "") + with self._lock: + state = self._sites[site_id] + state["material_uuid"] = material_uuid + state["material_name"] = display_name or ( + self._display_name(material_uuid, occupant.name) if material_uuid else occupant.name ) - platform = created.data.nodes[0] - self._platform_uuid = platform.material.material_uuid - - platform = gateway.get_material(self._platform_uuid) - sites = sorted(platform.sites, key=lambda item: int(item.site_index)) - if len(sites) != 3: - raise RuntimeError("virtual heating platform requires exactly three sites") - - for index, site in enumerate(sites, start=1): - sample_resource_id = f"{self.device_id}-sample-{index}" - sample = self._material_by_resource_id(sample_resource_id) - if sample is None: - created = gateway.create_tree( - self._mutation( - "create_material_tree", f"create-sample:{sample_resource_id}" - ), - MaterialTreeCreate( - nodes=[ - MaterialNodeCreate( - client_ref="sample", - identity=MaterialIdentityWrite( - resource_id=sample_resource_id, - display_name=f"加热样品 {index}", - description=f"虚拟加热工位 {index} 的真实 materials.v1 物料", - resource_type="resource", - class_name="Resource", - template_name="virtual_heating_sample", - barcode=f"OPENLAB-HEAT-{index}", - barcode_symbology="CODE128", - meta_data={ - "demo": "openlab-heating", - "site_id": index, - "display_color": SAMPLE_DISPLAY_COLORS[index - 1], - }, - ), - data=MaterialDataWrite( - data={ - "temperature_c": AMBIENT_TEMPERATURE_C, - "target_temperature_c": AMBIENT_TEMPERATURE_C, - "temperature_source": { - "device_id": self.device_id, - "property": f"site_{index}_temperature_c", - }, - "serialized_state": { - "temperature_c": AMBIENT_TEMPERATURE_C, - "state": "idle", - }, - }, - state_status="ready", - ), - position=MaterialPosition(), - ) - ] - ), - ) - sample = created.data.nodes[0] - if site.occupied_material_uuid != sample.material.material_uuid: - if site.occupied_material_uuid is not None: - raise RuntimeError(f"heating site {index} is already occupied") - gateway.move_material( - self._mutation("move_material", f"place-sample:{index}"), - MaterialMove( - material_uuid=sample.material.material_uuid, - destination_site_uuid=site.site_uuid, - ), + if not isinstance(occupant, VirtualHeatingSample): + self._samples.pop(site_id, None) + logger.warning( + "[HeatingDemo] %s 工位 %s 上的 %s 不是加热样品(%s),不能加热", + self.device_id, + site_id, + occupant.name, + type(occupant).__name__, ) + return + self._samples[site_id] = occupant + state.update( + { + "temperature_c": occupant.temperature_c, + "target_temperature_c": occupant.target_temperature_c, + "progress": float(occupant.heating_state.get("progress", 0.0) or 0.0), + "state": occupant.state, + } + ) @not_action - def _refresh_material_state(self) -> None: + def _refresh_sites(self) -> None: + """按权威的工位占用(Site uuid → 物料 uuid)在设备 tracker 里找到同一份实例。 + + 样品被转运走(不在本设备 tracker 里)就不再登记;别处转运进来的物料按占用接管。 + """ + + node = self._require_node() if not self._platform_uuid: return - gateway = self._gateway() - platform = gateway.get_material(self._platform_uuid) - with self._lock: - for index, site in enumerate( - sorted(platform.sites, key=lambda item: int(item.site_index)), start=1 - ): - state = self._sites[index] - state["site_uuid"] = site.site_uuid - state["material_uuid"] = site.occupied_material_uuid or "" - if site.occupied_material_uuid: - material = gateway.get_material(site.occupied_material_uuid) - state["material_name"] = material.material.display_name - state["temperature_c"] = float( - material.data.data.get("temperature_c", AMBIENT_TEMPERATURE_C) + platform = self._gateway().get_material(self._platform_uuid) + by_label = {str(site.label): site for site in platform.sites} + tracker = node.resource_tracker + for index in SITE_IDS: + site = by_label.get(_site_label(index)) + occupied = str(getattr(site, "occupied_material_uuid", "") or "") if site is not None else "" + occupant = tracker.uuid_to_resources.get(occupied) if occupied else None + current = self._samples.get(index) + if occupant is not None: + if occupant is not current: + self._adopt(index, occupant) + continue + self._samples.pop(index, None) + with self._lock: + self._sites[index]["material_uuid"] = occupied + self._sites[index]["material_name"] = "" + if occupied: + logger.warning( + "[HeatingDemo] %s 工位 %s 被物料 %s 占用,但设备本地没有它的 PLR 实例", + self.device_id, + index, + occupied, + ) + + @not_action + def _new_sample(self, site_id: int) -> VirtualHeatingSample: + from unilabos.resources.resource_tracker import set_plr_template_name + + sample = VirtualHeatingSample( + f"{self.device_id}-sample-{site_id}", + barcode=Barcode( + data=f"OPENLAB-HEAT-{site_id}", + symbology="CODE128", + position_on_resource="front", + ), + ) + set_plr_template_name(sample, SAMPLE_TEMPLATE) + sample.unilabos_extra = { + **(getattr(sample, "unilabos_extra", None) or {}), + EXTRA_RESOURCE_META_DATA: { + "demo": "openlab-heating", + "site_id": site_id, + "display_color": SAMPLE_DISPLAY_COLORS[site_id - 1], + }, + } + sample.temperature_source = self._temperature_source(site_id) + return sample + + @not_action + def _provision_materials(self) -> None: + """空工位放上演示样品:建树与占用工位在权威的同一事务里完成(失败整体回滚)。""" + + from unilabos.resources import materials + + with self._provision_lock: + node = self._require_node() + self._refresh_sites() + for index in SITE_IDS: + if index in self._samples or self._sites[index]["material_uuid"]: + continue + site = self._device_sites.get(index) or _site_label(index) + display_name = f"加热样品 {index}" + try: + created = materials.create( + self._new_sample(index), + node=node, + site=site, + display_name=display_name, ) - state["target_temperature_c"] = float( - material.data.data.get( - "target_temperature_c", state["temperature_c"] - ) + except LinkError: + raise + except Exception as exc: # noqa: BLE001 - 一个工位放不上不影响其它工位与设备启动 + logger.warning( + "[HeatingDemo] %s 工位 %s 放置演示样品失败:%s", self.device_id, index, exc ) - serialized = material.data.data.get("serialized_state", {}) - if isinstance(serialized, dict): - state["state"] = str(serialized.get("state", state["state"])) + continue + self._adopt(index, created, display_name=display_name) + + # ------------------------------------------------------------------ + # 加热 + # ------------------------------------------------------------------ + + @not_action + def _temperature_source(self, site_id: int) -> dict[str, Any]: + return {"device_id": self.device_id, "property": f"site_{site_id}_temperature_c"} + + @not_action + def _sample(self, site_id: int) -> VirtualHeatingSample: + sample = self._samples.get(site_id) + node = self._require_node() + if sample is not None and node.resource_tracker.uuid_to_resources.get(sample.unilabos_uuid) is sample: + return sample + self._provision_materials() + sample = self._samples.get(site_id) + if sample is None: + occupied = self._sites[site_id]["material_uuid"] + raise RuntimeError( + f"site {site_id} has no heating sample" + + (f" (occupied by {occupied})" if occupied else "") + ) + return sample @not_action def _write_material_temperature( @@ -394,18 +479,12 @@ def _write_material_temperature( target_temperature_c: float, state: str, progress: float, - job_uuid: str, ) -> None: - gateway = self._gateway() - material_uuid = str(self._sites[site_id]["material_uuid"]) - aggregate = gateway.get_material(material_uuid) - now_ms = int(time.time() * 1000) - rounded_temperature = round(float(temperature_c), 3) - rounded_target = round(float(target_temperature_c), 3) - - # First update the simulated instrument measurement. Device telemetry - # samples these scalar properties; the material write below is only a - # passive latest-value projection and is not the chart history source. + """先更新模拟仪器的测量值(遥测按设备状态采样),再把最新值投影到样品并回报权威。""" + + from unilabos.resources import materials + + sample = self._sample(site_id) with self._lock: self._sites[site_id].update( { @@ -415,45 +494,16 @@ def _write_material_temperature( "state": state, } ) - data = deepcopy(aggregate.data.data) - data.pop("temperature_history", None) - data.update( - { - "temperature_c": rounded_temperature, - "target_temperature_c": rounded_target, - "temperature_observed_at_ms": now_ms, - "temperature_source": { - "device_id": self.device_id, - "property": f"site_{site_id}_temperature_c", - }, - "serialized_state": { - "site_id": site_id, - "temperature_c": rounded_temperature, - "target_temperature_c": rounded_target, - "progress": round(float(progress), 3), - "state": state, - "observed_at_ms": now_ms, - }, - } - ) - gateway.put_data( - self._mutation( - "put_data", - f"temperature:{site_id}:{now_ms}:{uuid4().hex}", - job_uuid=job_uuid, - ), - material_uuid, - MaterialDataWrite( - data=data, - substances=aggregate.data.substances, - sites_initialized=aggregate.data.sites_initialized, - unknown_counter=aggregate.data.unknown_counter, - state_status=state, - source_event_uuid=aggregate.data.source_event_uuid, - source_job_uuid=job_uuid, - observed_at_ms=now_ms, - ), + sample.record_temperature( + site_id=site_id, + source=self._temperature_source(site_id), + temperature_c=temperature_c, + target_temperature_c=target_temperature_c, + progress=progress, + state=state, + observed_at_ms=int(time.time() * 1000), ) + materials.update(self._node, sample) @action( display_name="工位加热", @@ -479,14 +529,11 @@ def heat_site( if not 0.05 <= float(duration_seconds) <= 3600.0: raise ValueError("duration_seconds must be between 0.05 and 3600") - if not self._platform_uuid: - self._provision_materials() - else: - self._refresh_material_state() - material_uuid = str(self._sites[site_id]["material_uuid"]) - if not material_uuid: - raise RuntimeError(f"site {site_id} has no material") - start_temperature = float(self._sites[site_id]["temperature_c"]) + with self._provision_lock: + self._refresh_sites() + sample = self._sample(site_id) + material_uuid = str(sample.unilabos_uuid) + start_temperature = float(sample.temperature_c) wall_seconds = float(duration_seconds) * self.time_scale steps = max(1, min(120, int(wall_seconds / self.update_interval_s) + 1)) delay = wall_seconds / steps @@ -504,7 +551,6 @@ def heat_site( target_temperature_c=float(target_temperature_c), state=state, progress=ratio * 100.0, - job_uuid=action_context.action_id, ) action_context.publish_feedback( { @@ -529,17 +575,16 @@ def heat_site( def serialize(self) -> dict[str, Any]: """Return the complete JSON-safe simulated state. - Material temperature remains authoritative in ``materials.v1``. This - serialized projection is copied into each material's - ``data.serialized_state`` during actions and is useful to adapters that - need a complete device snapshot. + Material temperature remains authoritative in ``materials.v1`` (each + sample's own PLR state). This serialized projection mirrors it per site + and is useful to adapters that need a complete device snapshot. """ with self._lock: return { "device_id": self.device_id, "platform_material_uuid": self._platform_uuid, - "sites": [deepcopy(self._sites[index]) for index in range(1, 4)], + "sites": [deepcopy(self._sites[index]) for index in SITE_IDS], } @property @@ -593,6 +638,8 @@ def serialized_state(self) -> dict[str, Any]: __all__ = [ "AMBIENT_TEMPERATURE_C", "SAMPLE_DISPLAY_COLORS", + "SAMPLE_TEMPLATE", "VIRTUAL_HEATING_PLATFORM_SITES", "VirtualHeatingPlatform", + "VirtualHeatingSample", ] From ee023f965cc0ef5dac11aace6a93268532d64913 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:28:34 +0800 Subject: [PATCH 03/59] test(workflow): site-binding fixture deck carries its PLR type The fixture mounts an identity-only deck under the bench device, which the authority now rejects (device subtrees only hold PLR materials). --- tests/server/test_workflow_site_bindings.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/server/test_workflow_site_bindings.py b/tests/server/test_workflow_site_bindings.py index 82800f571..b044bb374 100644 --- a/tests/server/test_workflow_site_bindings.py +++ b/tests/server/test_workflow_site_bindings.py @@ -183,8 +183,9 @@ def mutation(operation): tree = mat.create_tree(mutation("create_material_tree"), MaterialTreeCreate(nodes=[ MaterialNodeCreate(client_ref="bench", identity=MaterialIdentityWrite( resource_id="bench", name="bench", template_name="bench", resource_type="device")), + # 设备子树只收 PLR 物料:台面带 PLR 类型名(config.type) MaterialNodeCreate(client_ref="deck", parent_client_ref="bench", identity=MaterialIdentityWrite( - resource_id="deck", name="deck", template_name="deck"), + resource_id="deck", name="deck", template_name="deck", config={"type": "Resource"}), sites=[SiteCreate(template_name="deck", site_index=0, label="T1")]), ])).data template = {"id": "test:site", "uuid": str(uuid4()), "registry_type": "workflow", "display_name": "Site demo", From cfa6ce30b86ec38ec5d3e8aef28ce186e2fb1f1c Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:10:08 +0800 Subject: [PATCH 04/59] fix(host): split non-PLR materials out of device subtrees at init Every driver creator takes the device's children through one split (split_plr_material_tree in DeviceClassCreator.__init__): each material subtree keeps the part that deserializes as PLR, and a node without config.type is cut off together with what hangs under it; parent Site occupancy pointing at it is cleared in the local copy (authority untouched). This covers materials attached after construction and the ones a device is built with (a liquid handler's deck, a workstation deck): a deck with one legacy material on it still initializes with the device. Each cut material is named in an error log. Previously a single legacy node failed the whole subtree (or the whole device). --- .../test_attach_legacy_non_plr_children.py | 138 +++++++++++++----- .../client/host/runtime/driver_creator.py | 53 ++++--- unilabos/resources/resource_tracker.py | 49 +++++++ 3 files changed, 186 insertions(+), 54 deletions(-) diff --git a/tests/client/host/runtime/test_attach_legacy_non_plr_children.py b/tests/client/host/runtime/test_attach_legacy_non_plr_children.py index e1d1082d5..53c801bd4 100644 --- a/tests/client/host/runtime/test_attach_legacy_non_plr_children.py +++ b/tests/client/host/runtime/test_attach_legacy_non_plr_children.py @@ -1,23 +1,29 @@ -"""旧数据里设备下遗留的非 PLR 物料:不挂到本地、点名报错,整台设备照常启动。 +"""设备初始化拿到的子树先拆一遍:旧数据里的非 PLR 物料拆下来点名报错,其余照常初始化。 -权威已在落位时拒绝新的非 PLR 物料进入设备子树;这里只处理升级前留下的旧数据(如旧版 -虚拟加热平台经网关手写、没有 ``config.type`` 的样品)——以前它让设备在重启时直接起不来。 +权威已在落位时拒绝新的非 PLR 物料进入设备子树;这里只处理升级前留下的旧数据(如旧版虚拟加热 +平台经网关手写、没有 ``config.type`` 的样品)——以前它让设备在重启时直接起不来。拆的粒度是节点: +台面上放着一个旧物料时,台面(连同其它 PLR 物料)仍和设备一起初始化,比如液体工作站构造时 +要带上的 deck。 """ from __future__ import annotations import logging +from typing import Any from uuid import uuid4 from pylabrobot.resources import Resource -from unilabos.client.host.runtime.driver_creator import DeviceClassCreator +from unilabos.client.host.runtime.driver_creator import DeviceClassCreator, PyLabRobotCreator from unilabos.resources.resource_tracker import ( DeviceNodeResourceTracker, ResourceDict, ResourceDictInstance, + ResourceTreeInstance, ResourceTreeSet, + split_plr_material_tree, ) +from tests.plr_fixtures import SiteDeck, site_deck class _Driver: @@ -25,43 +31,107 @@ def __init__(self, **_kwargs) -> None: pass -def _legacy_sample(device_uuid: str) -> ResourceDictInstance: - return ResourceDictInstance( - ResourceDict.model_validate( - { - "id": "heater-sample-1", - "uuid": str(uuid4()), - "name": "heater-sample-1", - "type": "resource", - "class": "Resource", - "template_name": "virtual_heating_sample", - "parent_uuid": device_uuid, - "config": {}, - "data": {"temperature_c": 25.0}, - "extra": {}, - } - ) - ) +class _Handler: + """构造时要带上 deck 的驱动(液体工作站的形状)。""" + + def __init__(self, deck: Any = None, **_kwargs) -> None: + self.deck = deck + +def _legacy_node(device_uuid: str, *, parent_uuid: str | None = None, uuid: str | None = None) -> dict: + return { + "id": "legacy_bottle", + "uuid": uuid or str(uuid4()), + "name": "legacy_bottle", + "type": "container", + "class": "Resource", + "template_name": "legacy_bottle", + "parent_uuid": parent_uuid or device_uuid, + "config": {}, + "data": {"volume_ml": 5}, + "extra": {}, + } -def _plr_child(device_uuid: str) -> ResourceDictInstance: - source = Resource("legacy_neighbour", size_x=10, size_y=10, size_z=10) - tree = ResourceTreeSet.from_plr_resources([source], known_random_uuid=True).trees[0] - tree.root_node.res_content.parent_uuid = device_uuid - return tree.root_node +def _deck_with_legacy_occupant(device_uuid: str) -> tuple[ResourceDictInstance, str, str]: + """T1 上一个 PLR 盒子、T2 上一个旧版非 PLR 物料的台面(挂在设备下)。""" -def test_legacy_non_plr_child_is_skipped_and_named(caplog) -> None: + deck_uuid = str(uuid4()) + deck = site_deck(deck_uuid, "bench_deck", ("T1", "T2")) + box = Resource("keep_box", size_x=20, size_y=20, size_z=20) + box.unilabos_uuid = str(uuid4()) + deck.assign_child_resource(box, spot=0) + dumped = ResourceTreeSet.from_plr_resources([deck], known_random_uuid=True).dump()[0] + dumped[0]["parent_uuid"] = device_uuid + legacy_uuid = str(uuid4()) + dumped.append(_legacy_node(device_uuid, parent_uuid=deck_uuid, uuid=legacy_uuid)) + for site in dumped[0]["sites"]: + if site["label"] == "T2": + site["occupied_material_uuid"] = legacy_uuid + tree = ResourceTreeSet.load([dumped]).trees[0] + return tree.root_node, box.unilabos_uuid, legacy_uuid + + +def test_split_keeps_the_plr_part_and_frees_the_legacy_site() -> None: device_uuid = str(uuid4()) - legacy = _legacy_sample(device_uuid) - neighbour = _plr_child(device_uuid) + root, box_uuid, legacy_uuid = _deck_with_legacy_occupant(device_uuid) + + kept, pruned = split_plr_material_tree(root) + + assert [content.uuid for content in pruned] == [legacy_uuid] + assert kept is not None + assert [node.res_content.uuid for node in kept.children] == [box_uuid] + sites = {site.label: site.occupied_material_uuid for site in kept.res_content.sites} + assert sites == {"T1": box_uuid, "T2": None} + # 输入不改:拆的是副本 + assert len(root.children) == 2 + # 剩下的部分能按 PLR 反序列化 + (deck,) = ResourceTreeSet([ResourceTreeInstance(kept)]).to_plr_resources() + assert [child.name for child in deck.children] == ["keep_box"] + + +def test_split_returns_plr_trees_unchanged() -> None: + root, _box, _legacy = _deck_with_legacy_occupant(str(uuid4())) + kept, _pruned = split_plr_material_tree(root) + + again, pruned = split_plr_material_tree(kept) + + assert again is kept and pruned == [] + + +def test_attach_skips_only_the_legacy_nodes(caplog) -> None: + device_uuid = str(uuid4()) + deck, box_uuid, legacy_uuid = _deck_with_legacy_occupant(device_uuid) + loose = ResourceDictInstance(ResourceDict.model_validate(_legacy_node(device_uuid))) tracker = DeviceNodeResourceTracker() - creator = DeviceClassCreator(_Driver, [legacy, neighbour], tracker) + creator = DeviceClassCreator(_Driver, [deck, loose], tracker) with caplog.at_level(logging.ERROR): creator.create_instance({}) - assert legacy.res_content.uuid not in tracker.uuid_to_resources - # 同一设备下的 PLR 物料照常挂上 - assert neighbour.res_content.uuid in tracker.uuid_to_resources - assert any("heater-sample-1" in record.getMessage() for record in caplog.records) + assert deck.res_content.uuid in tracker.uuid_to_resources + assert box_uuid in tracker.uuid_to_resources + assert legacy_uuid not in tracker.uuid_to_resources + assert loose.res_content.uuid not in tracker.uuid_to_resources + messages = [record.getMessage() for record in caplog.records] + assert sum("legacy_bottle" in message for message in messages) == 2 + + +def test_device_built_with_its_deck_still_initializes_when_a_legacy_material_sits_on_it(caplog) -> None: + """液体工作站的形状:deck 是构造参数,台面上的旧物料拆下来,设备与台面照常初始化。""" + + device_uuid = str(uuid4()) + deck, box_uuid, legacy_uuid = _deck_with_legacy_occupant(device_uuid) + tracker = DeviceNodeResourceTracker() + creator = PyLabRobotCreator(_Handler, [deck], tracker) + + with caplog.at_level(logging.ERROR): + handler = creator.create_instance( + {"deck": {"_resource_child_name": "bench_deck", "_resource_type": "tests.plr_fixtures:SiteDeck"}} + ) + + assert handler is not None and isinstance(handler.deck, SiteDeck) + assert [child.name for child in handler.deck.children] == ["keep_box"] + assert handler.deck.unilabos_uuid == deck.res_content.uuid + assert box_uuid in tracker.uuid_to_resources and legacy_uuid not in tracker.uuid_to_resources + assert any("legacy_bottle" in record.getMessage() for record in caplog.records) diff --git a/unilabos/client/host/runtime/driver_creator.py b/unilabos/client/host/runtime/driver_creator.py index b997b0379..a097bbccd 100644 --- a/unilabos/client/host/runtime/driver_creator.py +++ b/unilabos/client/host/runtime/driver_creator.py @@ -20,6 +20,7 @@ ResourceDictInstance, ResourceTreeInstance, ResourceTreeSet, + split_plr_material_tree, ) from unilabos.utils import logger from unilabos.utils.cls_creator import create_instance_from_config @@ -34,6 +35,36 @@ def create_instance(self, *args: Any, **kwargs: Any) -> T: raise NotImplementedError +def _plr_children( + device_cls: Type[Any], children: List[ResourceDictInstance] +) -> List[ResourceDictInstance]: + """设备初始化拿到的子树先拆一遍:每棵物料子树只留能按 PLR 反序列化的部分。 + + 挂载用的物料、构造设备要一起带上的物料(液体工作站的台面、工作站的 deck)都从这里取, + 同一套拆法。拆下来的非 PLR 物料(升级前遗留,没有 ``config.type``)连同挂在它下面的物料 + 不挂到设备本地,逐个点名报错;整台设备照常初始化。子设备由它自己的构造器处理,不在这里拆。 + """ + + device_name = getattr(device_cls, "__name__", str(device_cls)) + result: List[ResourceDictInstance] = [] + for child in children: + if child.res_content.type == "device": + result.append(child) + continue + tree, pruned = split_plr_material_tree(child) + for content in pruned: + logger.error( + "设备 %s 下的物料 %s(%s)不是 PLR 物料(没有 config.type),连同挂在它下面的物料" + "没有挂到设备本地;请移走或删除它,再按注册表资源类经 materials.create 重新创建", + device_name, + content.id, + content.uuid, + ) + if tree is not None: + result.append(tree) + return result + + class DeviceClassCreator(Generic[T]): """Create a Python driver and attach its non-device child resources.""" @@ -45,7 +76,7 @@ def __init__( ) -> None: self.device_cls = cls self.device_instance: Optional[T] = None - self.children = list(children) + self.children = _plr_children(cls, children) self.resource_tracker = resource_tracker def attach_resource(self) -> None: @@ -58,25 +89,7 @@ def attach_resource(self) -> None: # 再实例化一份会让同一权威物料有两个实例,uuid 索引指向驱动手里没有的副本。 if str(child.res_content.uuid or "") in self.resource_tracker.uuid_to_resources: continue - tree = ResourceTreeInstance(child) - missing = [ - node.res_content.id - for node in tree.get_all_nodes() - if node.res_content.type != "device" - and not str((node.res_content.config or {}).get("type") or "").strip() - ] - if missing: - # 设备子树只收 PLR 物料(权威在落位时拒绝新的);旧数据里遗留的非 PLR 物料 - # 反序列化不了:不挂到本地,整台设备照常启动,日志点名让人处理。 - logger.error( - "设备 %s 下的物料 %s 不是 PLR 物料(%s 没有 config.type),没有挂到设备本地;" - "请移走或删除它,再按注册表资源类经 materials.create 重新创建", - getattr(self.device_cls, "__name__", self.device_cls), - child.res_content.id, - "、".join(missing[:5]), - ) - continue - resource = ResourceTreeSet([tree]).to_plr_resources()[0] + resource = ResourceTreeSet([ResourceTreeInstance(child)]).to_plr_resources()[0] self.resource_tracker.add_resource(resource) def create_instance(self, data: Dict[str, Any]) -> T: diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index e66ff0e5f..20281af23 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -1752,6 +1752,55 @@ def load(cls, data: List[List[Dict[str, Any]]]) -> "ResourceTreeSet": return cls(trees) +def split_plr_material_tree( + root: ResourceDictInstance, +) -> Tuple[Optional[ResourceDictInstance], List[ResourceDict]]: + """把一棵物料树拆成能按 PLR 反序列化的部分与拆下来的非 PLR 物料,不改输入。 + + 设备子树只收 PLR 物料(权威在每次落位时拒绝新的),升级前的旧数据里仍可能挂着没有 + ``config.type`` 的物料:它连同挂在它下面的物料整枝拆下,其余照常反序列化——比如液体工作站 + 的台面上放着一个旧物料时,台面仍和设备一起初始化。父物料库位上指向被拆物料的占用在副本里 + 清空(权威不动)。设备节点不拆。 + + 返回 ``(剩下的树, 拆下的各枝的根)``:没有要拆的时原样返回输入;根本身不是 PLR 物料时剩下的树 + 为 None。 + """ + + def is_plr(node: ResourceDictInstance) -> bool: + content = node.res_content + return content.type == "device" or bool( + str((content.config or {}).get("type") or "").strip() + ) + + pruned: List[ResourceDict] = [] + dropped: set[str] = set() + + def visit(node: ResourceDictInstance, inside_pruned: bool) -> None: + if not inside_pruned and not is_plr(node): + pruned.append(node.res_content) + inside_pruned = True + if inside_pruned: + dropped.add(str(node.res_content.uuid)) + for child in node.children: + visit(child, inside_pruned) + + visit(root, False) + if not pruned: + return root, [] + if str(root.res_content.uuid) in dropped: + return None, pruned + kept = [] + for node in ResourceTreeInstance(root).get_all_nodes(): + if str(node.res_content.uuid) in dropped: + continue + dumped = node.res_content.model_dump(by_alias=True) + for site in dumped.get("sites") or []: + if site.get("occupied_material_uuid") in dropped: + site["occupied_material_uuid"] = None + kept.append(dumped) + return ResourceTreeSet.load([kept]).trees[0].root_node, pruned + + def prepare_resource_creation_payloads( resources: List[Dict[str, Any]], ) -> Tuple[ResourceTreeSet, List[Dict[str, Any]]]: From ca7252abee4359a27827257cad64c05891613eab Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:21:29 +0800 Subject: [PATCH 05/59] feat(materials): material class is the registry name it was initialized from Contract (unilabos.resources.material_class), field name kept as class / class_name and documented where it is defined: - class records what the material was initialized from: the registry resource name (e.g. container, virtual_heating_sample), equal to its template name. The implementation module (class.module) can be looked up in the registry by that name; it is not stored again. - children without a registry entry (wells, tip spots, ad-hoc PLR resources) fall back to the PLR class name; devices keep their registry device name. - config.type is the PLR class name. Rebuilding PLR instances (device restart) deserializes by config.type directly; class is a record only. Changes: - from_plr_resources / resource_tree_to_create derive class by the contract; instantiate_registry_resource stamps the registry name on the draft; registry sync writes class_name = registry name for entries that declare an implementation (module_name keeps class.module); the legacy graph upgrade and example graphs use the registry name. - The authority resolves the stored class against the template: a registry template not yet re-synced (class still the PLR name) accepts the registry name, and a client that could not reach the registry (class fell back to config.type) is normalized to the template's registry name. - materials.db stays on the v1 baseline (no migration). - Visualization and the mesh manager look the registry up by template_name. --- .../examples/materials_tutorial.md | 2 +- docs/user_guide/graph_files.md | 25 +-- .../devices/test_virtual_devices_hostlink.py | 4 +- .../resources/test_material_class_contract.py | 149 ++++++++++++++++++ .../test_registry_material_adapter.py | 3 +- tests/server/test_legacy_graph_compat.py | 5 +- .../test_legacy_graph_registry_upgrade.py | 17 +- tests/server/test_material_io_inventory.py | 4 +- .../host/legacy_adaptor/legacy/graph.py | 8 +- .../ros2/presets/resource_mesh_manager.py | 10 +- unilabos/device_mesh/resource_visalization.py | 3 +- unilabos/protocol/materials.py | 3 + unilabos/resources/adapters/plr_materials.py | 11 +- .../resources/adapters/registry_materials.py | 11 +- unilabos/resources/material_class.py | 101 ++++++++++++ unilabos/resources/materials.py | 9 +- unilabos/resources/objects/resource.py | 9 +- unilabos/resources/resource_tracker.py | 20 ++- unilabos/server/mcp/guide.py | 3 +- unilabos/server/services/materials/core.py | 24 ++- .../services/materials/inventory_commands.py | 2 +- .../server/services/materials/material_io.py | 10 +- .../services/materials/resource_contract.py | 2 +- .../add_protocol_test_station.json | 22 +-- .../centrifuge_protocol_test_station.json | 16 +- .../clean_vessel_protocol_test_station.json | 14 +- .../dual_valve_pump_test_station.json | 14 +- .../evacuateandrefill_test_station.json | 14 +- .../evaporate_protocol_test_station.json | 18 +-- .../filter_protocol_test_station.json | 20 +-- .../heatchill_protocol_test_station.json | 24 +-- ...mptransfer_filterthrough_test_station.json | 38 ++--- .../pumptransfer_test_station.json | 14 +- .../run_column_protocol_test_station.json | 20 +-- .../simple_stir_heatchill_test_station.json | 4 +- .../comprehensive_station.json | 28 ++-- .../experiments/mock_devices/mock_all.json | 2 +- .../mock_protocol/addteststation.json | 16 +- .../mock_protocol/centrifugeteststation.json | 10 +- .../mock_protocol/cleanvesselteststation.json | 16 +- .../mock_protocol/dissolveteststation.json | 12 +- .../mock_protocol/filterteststation.json | 10 +- .../filterthroughteststation.json | 18 +-- .../mock_protocol/heatchillteststation.json | 10 +- .../mock_protocol/runcolumnteststation.json | 18 +-- .../mock_protocol/stirteststation.json | 12 +- .../mock_protocol/transferteststation.json | 14 +- .../mock_protocol/washsolidteststation.json | 18 +-- unilabos/test/experiments/mock_reactor.json | 2 +- 49 files changed, 587 insertions(+), 252 deletions(-) create mode 100644 tests/resources/test_material_class_contract.py create mode 100644 unilabos/resources/material_class.py diff --git a/docs/developer_guide/examples/materials_tutorial.md b/docs/developer_guide/examples/materials_tutorial.md index befb9ee74..0b0f9366d 100644 --- a/docs/developer_guide/examples/materials_tutorial.md +++ b/docs/developer_guide/examples/materials_tutorial.md @@ -336,7 +336,7 @@ plate = materials.create("my_plate_class", name="plate_1") - **children 形态不一致**:`ResourceTreeSet` 只按 `parent_uuid` / `parent` 建立层级,`children` 列表会被忽略;旧格式图(`children` id 列表、根级 `position` 等)在 `-g` / `unilab graph upload` 读取边界由 legacy 适配层统一转换。 - **UUID**:`from_raw_dict_list` / `load` / `from_plr_resources` 都要求每个节点带权威 UUID(或 `data.unilabos_uuid`),不会随机生成。 -- **PLR 类型**:`to_plr_resources` 只按 `config.type` 查找 PLR 类,不回退到 `class` / `template_name`。 +- **PLR 类型**:`to_plr_resources` 只按 `config.type`(PLR 类名)反序列化;物料的 `class` 是初始化它用的注册表名,只做记录,不参与反序列化。 - **按注册表创建**:`materials.instantiate_registry_resource` 只支持 `class.type == "pylabrobot"` 的注册表资源类。 参考代码: diff --git a/docs/user_guide/graph_files.md b/docs/user_guide/graph_files.md index 39f0df925..3fc24993a 100644 --- a/docs/user_guide/graph_files.md +++ b/docs/user_guide/graph_files.md @@ -69,7 +69,7 @@ JSON 顶层包含 `nodes` 和可选的 `links`: | `name` | 物料名,恒等于 `uuid`(见下文「物料命名」)。可以省略 | | `display_name` | 面向界面的人读标签,可重名、可编辑 | | `type` | 节点类型;图导入缺省值为 `device` | -| `class` | 设备填 Registry 设备名;物料填 PLR 类名(如 `RegularContainer`),须与模板的类名一致 | +| `class` | 初始化它用的 Registry 名:设备填 Registry 设备名;物料填 Registry 资源名(如 `container`,与 `template_name` 相同,实现模块按这个名字在 Registry 里查);没有 Registry 条目的 PLR 物料(孔位等)填 PLR 类名 | | `parent` | 父节点的 `id` | | `parent_uuid` | 父节点 UUID;同时提供时优先按 UUID 建立关系 | | `config` | 驱动构造参数和设备配置;非设备物料的 `config.name` 是 PLR 键 | @@ -109,16 +109,20 @@ ordering 标识。 ### 物料节点的类与模板 -物料节点(`type` 不是 `device`)要同时写清三处:`template_name` 是 Registry 资源名,`class` 与 -`config.type` 是该模板实例化出的 PLR 类名。开机时 Host 把图中物料对齐到物料权威,权威按模板校验 -`class`,PLR 按 `config.type` 反序列化;`config` 里只能放 PLR 构造参数,其他业务字段放 `data`。 +物料节点(`type` 不是 `device`)要同时写清三处:`template_name` 是 Registry 资源名;`class` 是初始化它 +用的 Registry 名——按 Registry 资源初始化的物料就是这个资源名(与 `template_name` 相同,实现模块即条目的 +`class.module` 按名字在 Registry 里查,不另写),没有 Registry 条目的 PLR 物料(孔位、枪头位等随父物料 +一起建出来的孩子)是 PLR 类名;`config.type` 是 PLR 类名。开机时 Host 把图中物料对齐到物料权威,权威 +按模板校验 `class`,重建 PLR 实例时直接按 `config.type` 反序列化(`class` 只做记录); +`config` 里只能放 PLR 构造参数,其他业务字段放 `data`。`class` 写成 PLR 类名的旧写法在入库时按模板 +换成 Registry 名。 最常见的通用容器写法(与 `/api/v1/graphs/live/payload` 导出的形状一致): ```json { "id": "flask_DMF", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "parent": "workstation_1", "config": {"type": "RegularContainer", "max_volume": 1000.0}, @@ -126,11 +130,10 @@ ordering 标识。 } ``` -旧图里容器常写成 `"class": null` 或 `"class": "container"`、没有 `config.type`,`config` 里还可能混着 +旧图里容器常写成 `"class": null`、没有 `config.type`,`config` 里还可能混着 `filter_type` 这类业务字段。这样的图不用手改:`-g` 与 `unilab graph upload` 读图时按注册表补齐 (见下文「规范化与校验」第 1 步),文件本身不动。不经读图边界、直接交给 Graph Authority 的 -payload 不做这一步,权威会按模板拒绝(`class_name ... does not match template 'container' -class_name 'RegularContainer'`)。 +payload 不做这一步,缺 `config.type` 的物料没法按 PLR 反序列化,设备子树里的物料权威直接拒绝。 `children` 是资源树的递归容器,不属于 `ResourceDict` 领域字段。平铺 JSON 图应在 子节点上使用 `parent_uuid`,必要时同时提供便于阅读的 `parent`。 @@ -206,9 +209,9 @@ I/O 和 PLC 等通信适配器;物理流路使用 `fluid`。 - 模板依次取 `template_name`、`class`、`type`(`class` 为空的 dev 时代容器写 `"type": "container"`,即同名注册表模板),写回 `template_name`; - - PLR 类名只从注册表查:该模板注册表条目的 `config_info[0].config.type`(物料权威登记模板时 - 用的同一规则;条目没有 `config_info` 时按条目的 `class.module` 实例化一次取类名),写进 - `class`,`config.type` 缺失时一并补上; + - PLR 类名只从注册表查:该模板注册表条目的 `config_info[0].config.type`(条目没有 + `config_info` 时按条目的 `class.module` 实例化一次取类名),`config.type` 缺失时补上; + `class` 写成模板名(初始化它用的 Registry 名); - 补上 `config.type` 的节点,`config` 里该 PLR 类构造器不接受的键(如 `filter_type`)挪进 `data`; - 模板不在注册表、条目不是 PLR 资源类、或节点已有的 `config.type` 与注册表的类不一致时报错, diff --git a/tests/devices/test_virtual_devices_hostlink.py b/tests/devices/test_virtual_devices_hostlink.py index 54f13c915..9056a466e 100644 --- a/tests/devices/test_virtual_devices_hostlink.py +++ b/tests/devices/test_virtual_devices_hostlink.py @@ -735,7 +735,9 @@ def test_example_graph_materials_build_as_their_template_class(graph: Path, tmp_ ] for node in materials: (resource,) = ResourceTreeSet([ResourceTreeInstance(node)]).to_plr_resources() - assert node.res_content.klass == type(resource).__name__, node.res_content.id + # class 是初始化它用的注册表名(即模板名),config.type 是 PLR 类名:建出来的就是它的类 + assert node.res_content.klass == node.res_content.template_name, node.res_content.id + assert type(resource).__name__ == node.res_content.config["type"], node.res_content.id if node.res_content.type == "container": assert node.res_content.template_name == "container", node.res_content.id for node in loaded.resource_tree_set.all_nodes: diff --git a/tests/resources/test_material_class_contract.py b/tests/resources/test_material_class_contract.py new file mode 100644 index 000000000..85c6810db --- /dev/null +++ b/tests/resources/test_material_class_contract.py @@ -0,0 +1,149 @@ +"""物料 ``class`` 的约定:初始化它用的注册表名;``config.type`` 是 PLR 类名(反序列化靠它)。 + +- 按注册表资源初始化的物料:class 是注册表资源名(与模板名相同),实现模块按名字在注册表里查; +- 没有注册表条目的孩子(孔位等):class 是 PLR 类名; +- 设备:注册表设备名不变。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +import pytest + +from unilabos.protocol.materials import ( + InventoryMutation, + MaterialIdentityWrite, + MaterialNodeCreate, + MaterialTreeCreate, + ResourceTemplateWrite, +) +from unilabos.registry.registry import lab_registry +from unilabos.resources import materials +from unilabos.resources.adapters.plr_materials import plr_resources_to_create +from unilabos.resources.material_class import material_class, resolve_material_class +from unilabos.resources.resource_tracker import ResourceTreeSet +from unilabos.server.services.materials import MaterialsService +from unilabos.server.services.materials.core import MaterialValidationError +from tests.plr_fixtures import PLATE_MODULE, plate, registry_entry + +PLATE_REGISTRY_NAME = "class_contract_plate" + + +@pytest.fixture +def plate_entry(monkeypatch): + monkeypatch.setitem(lab_registry.resource_type_registry, PLATE_REGISTRY_NAME, registry_entry(PLATE_MODULE)) + return PLATE_REGISTRY_NAME + + +def _mutation(operation: str) -> InventoryMutation: + command = str(uuid4()) + return InventoryMutation(command_uuid=command, effect_key=f"{operation}:{command}", operation=operation, actor_type="test") + + +def test_registry_material_class_is_its_registry_name_and_children_keep_the_plr_class(plate_entry) -> None: + draft = materials.instantiate_registry_resource(plate_entry, "plate_a") + + tree = ResourceTreeSet.from_plr_resources([draft], known_random_uuid=True).trees[0] + + root = tree.root_node.res_content + assert (root.klass, root.template_name, root.config["type"]) == (plate_entry, plate_entry, "Plate") + well = tree.root_node.children[0].res_content + assert (well.klass, well.config["type"]) == ("Well", "Well") + + +def test_plr_resource_without_registry_entry_falls_back_to_its_plr_class() -> None: + tree = ResourceTreeSet.from_plr_resources([plate("loose")], known_random_uuid=True).trees[0] + + assert tree.root_node.res_content.klass == tree.root_node.res_content.config["type"] == "Plate" + + +def test_device_class_stays_the_registry_device_name() -> None: + assert material_class(resource_type="device", klass="virtual_stirrer", template_name="x") == "virtual_stirrer" + + +def test_graph_nodes_written_with_the_plr_class_are_normalized_to_the_registry_name(plate_entry) -> None: + """旧写法:class 写成 PLR 类名(= config.type),模板是注册表资源;入库时按模板换成注册表名。""" + + assert material_class(klass="Plate", template_name=plate_entry, plr_type="Plate") == plate_entry + + +@pytest.mark.parametrize( + ("template_class", "identity_class", "plr_type", "stored"), + [ + ("container", "container", "RegularContainer", "container"), + # 升级前登记的注册表模板 class 还是 PLR 类名:物料带来注册表名照收 + ("RegularContainer", "container", "RegularContainer", "container"), + # 查不到注册表的一方把 class 退回成了 PLR 类名:落模板的注册表名 + ("container", "RegularContainer", "RegularContainer", "container"), + ("container", "Plate", "RegularContainer", None), + (None, "anything", "Plate", "anything"), + ], +) +def test_resolve_material_class(template_class, identity_class, plr_type, stored) -> None: + assert ( + resolve_material_class( + template_name="container", template_class=template_class, identity_class=identity_class, plr_type=plr_type + ) + == stored + ) + + +def test_authority_stores_the_registry_name_for_a_registry_template(tmp_path) -> None: + service = MaterialsService(tmp_path / "materials.db") + try: + service.put_template( + _mutation("put_template"), + ResourceTemplateWrite(name="container", class_name="container", module_name="m.n:get_container"), + ) + + def create(class_name: str, plr_type: str) -> str: + created = service.create_tree( + _mutation("create_material_tree"), + MaterialTreeCreate( + nodes=[ + MaterialNodeCreate( + client_ref="c", + identity=MaterialIdentityWrite( + resource_id=f"c-{uuid4().hex[:6]}", + class_name=class_name, + template_name="container", + config={"type": plr_type}, + ), + ) + ] + ), + ).data + return created.client_ref_map["c"] + + assert service.get_material(create("container", "RegularContainer")).material.class_name == "container" + assert service.get_material(create("RegularContainer", "RegularContainer")).material.class_name == "container" + with pytest.raises(MaterialValidationError, match="does not match template"): + create("Plate", "RegularContainer") + finally: + service.close() + + +def test_registry_sync_writes_the_registry_name_as_the_template_class() -> None: + from unilabos.resources.adapters.registry_materials import registry_definition_to_template + + template = registry_definition_to_template({"id": "container", **registry_entry("m.n:get_container")}) + + assert (template.class_name, template.module_name) == ("container", "m.n:get_container") + + +def test_registry_entry_without_an_implementation_does_not_constrain_the_class() -> None: + """条目没有 class.module 就没法按它初始化:模板不约束物料的 class。""" + + from unilabos.resources.adapters.registry_materials import registry_definition_to_template + + template = registry_definition_to_template({"id": "rack", "registry_type": "resource"}) + + assert template.class_name is None + + +def test_create_request_carries_the_registry_name(plate_entry) -> None: + request = plr_resources_to_create([materials.instantiate_registry_resource(plate_entry, "plate_b")]) + + root = next(node for node in request.nodes if node.parent_client_ref is None) + assert (root.identity.class_name, root.identity.template_name) == (plate_entry, plate_entry) diff --git a/tests/resources/test_registry_material_adapter.py b/tests/resources/test_registry_material_adapter.py index 49995d1bf..e77974977 100644 --- a/tests/resources/test_registry_material_adapter.py +++ b/tests/resources/test_registry_material_adapter.py @@ -38,7 +38,8 @@ def test_registry_definition_is_registered_once_with_promoted_fields(tmp_path) - assert second == first assert template.resource_type == "container" - assert template.class_name == "RegularContainer" + # 模板的 class 是初始化物料用的注册表名(条目 id),实现模块在 module_name + assert template.class_name == "lab_beaker" assert template.category == ["container"] assert template.available_sites[0]["label"] == "slot" assert "category" not in template.definition diff --git a/tests/server/test_legacy_graph_compat.py b/tests/server/test_legacy_graph_compat.py index cc9e73a2f..82966de5e 100644 --- a/tests/server/test_legacy_graph_compat.py +++ b/tests/server/test_legacy_graph_compat.py @@ -324,8 +324,9 @@ def test_legacy_graph_markers_and_upgrade_report(): assert "根级 position ×6" in reports[0] assert legacy_graph_markers(upgraded) == {} plate, well = upgraded["nodes"][2], upgraded["nodes"][4] - assert (plate["template_name"], plate["class"], plate["config"]["type"]) == ("plate", "Plate", "Plate") - assert (well["template_name"], well["class"], well["config"]["type"]) == ("well", "Well", "Well") + # class 是初始化它用的注册表名(即模板名),config.type 是 PLR 类名 + assert (plate["template_name"], plate["class"], plate["config"]["type"]) == ("plate", "plate", "Plate") + assert (well["template_name"], well["class"], well["config"]["type"]) == ("well", "well", "Well") # 当前契约的图:不转换、不提示 reports.clear() diff --git a/tests/server/test_legacy_graph_registry_upgrade.py b/tests/server/test_legacy_graph_registry_upgrade.py index 402f133a1..caa1e81a0 100644 --- a/tests/server/test_legacy_graph_registry_upgrade.py +++ b/tests/server/test_legacy_graph_registry_upgrade.py @@ -37,6 +37,8 @@ FIXTURES = Path(__file__).parent / "fixtures" / "legacy_graphs" EXPERIMENTS = REPO_ROOT / "unilabos" / "test" / "experiments" CONTAINER_YAML = REPO_ROOT / "unilabos" / "registry" / "resources" / "organic" / "container.yaml" +#: 物料 / 模板的 class:初始化它用的注册表名 +CONTAINER_CLASS = "container" #: 旧夹具 → 手工改成当前写法的示例图 LEGACY_FIXTURES = { @@ -117,7 +119,9 @@ def test_legacy_fixture_upgrades_to_the_hand_fixed_example(fixture, registry_loo for node in upgraded["nodes"]: if node.get("type") == "container": assert node["template_name"] == "container", node["id"] - assert node["class"] == node["config"]["type"] == "RegularContainer", node["id"] + # class 是初始化它用的注册表名,config.type 是 PLR 类名 + assert node["class"] == CONTAINER_CLASS, node["id"] + assert node["config"]["type"] == "RegularContainer", node["id"] # 幂等:升级结果不再带旧字段,再升级不变 assert legacy_graph_markers(upgraded) == {} again: list[str] = [] @@ -145,7 +149,8 @@ def test_registry_entry_without_config_info_uses_the_declared_class() -> None: assert registry_resource_class_name(entry) is None upgraded = _upgrade(_read(FIXTURES / "mock_reactor.json"), _Lookup({"container": entry})) reactor = _by_id(upgraded)["reactor"] - assert reactor["class"] == reactor["config"]["type"] == "RegularContainer" + assert reactor["class"] == CONTAINER_CLASS + assert reactor["config"]["type"] == "RegularContainer" def test_unknown_template_names_the_node_and_the_template(registry_lookup) -> None: @@ -188,7 +193,7 @@ def no_lookup(name: str): # 手工改好的示例图:只做形状转换(根级 position、name 等),物料节点不查注册表 current = _read(EXPERIMENTS / "Protocol_Test_Station" / "simple_stir_heatchill_test_station.json") upgraded = _upgrade(current, no_lookup) - assert _by_id(upgraded)["main_reactor"]["class"] == "RegularContainer" + assert _by_id(upgraded)["main_reactor"]["class"] == CONTAINER_CLASS # 完全当前契约的图:原样返回、不提示;class 为空而 config.type 已有也是合法写法 payload = { @@ -268,7 +273,9 @@ def test_legacy_fixture_boots_like_the_hand_fixed_example(fixture, host_registry if content.type == "device" or (content.parent is not None and content.parent.type != "device"): continue (resource,) = ResourceTreeSet([ResourceTreeInstance(node)]).to_plr_resources() - assert content.klass == type(resource).__name__ == entry_class, content.id + # class 是初始化它用的注册表名;建出来的 PLR 类就是 config.type 指的那个 + assert content.klass == CONTAINER_CLASS, content.id + assert type(resource).__name__ == entry_class == content.config["type"], content.id def test_unknown_template_refuses_to_start(host_registry, tmp_path, monkeypatch, capsys) -> None: @@ -379,7 +386,7 @@ def request(method: str, path: str, body: Optional[dict[str, Any]] = None) -> An for container in ("main_reactor", "secondary_reactor"): node = live[container] assert (node["template_name"], node["class"], node["config"]["type"]) == ( - "container", "RegularContainer", "RegularContainer" + "container", CONTAINER_CLASS, "RegularContainer" ), node # 文件本身没被改写 assert _read(graph) == _read(FIXTURES / "simple_stir_heatchill_test_station.json") diff --git a/tests/server/test_material_io_inventory.py b/tests/server/test_material_io_inventory.py index 419e9764c..c84614728 100644 --- a/tests/server/test_material_io_inventory.py +++ b/tests/server/test_material_io_inventory.py @@ -208,7 +208,9 @@ def test_load_instantiates_the_registry_class_with_its_default_children(material assert root.config["name"] == "新吸头盒" assert (root.template_name, root.template_uuid) == (template, plan["template_uuid"]) assert root.meta_data["material_io"] == {"task_uuid": TASK, "job_uuid": job} - assert root.config["type"] == root.class_name and root.resource_type == "tip_rack" + # class 是初始化它用的注册表名(即模板名);config.type 是 PLR 类名(反序列化靠它) + assert root.class_name == template and root.config["type"] == "StandingTipRack" + assert root.resource_type == "tip_rack" spots = [node.material for node in tree.nodes if node.material.parent_material_uuid == new] tips = [node.material for node in tree.nodes if node.material.resource_type == "tip"] assert (len(spots), len(tips), len(tree.nodes)) == (96, 96, 1 + 96 + 96) diff --git a/unilabos/client/host/legacy_adaptor/legacy/graph.py b/unilabos/client/host/legacy_adaptor/legacy/graph.py index c01d049ca..7fd88840e 100644 --- a/unilabos/client/host/legacy_adaptor/legacy/graph.py +++ b/unilabos/client/host/legacy_adaptor/legacy/graph.py @@ -19,8 +19,9 @@ - dev 时代的物料节点(容器最常见)没有 PLR 类:``class`` 为空或写成注册表模板名 (``"container"``),``config`` 里没有 ``type``,``config`` 里还可能混着 PLR 构造器 不认的业务字段(``filter_type``)。当前契约是 ``template_name`` = 注册表模板、 - ``class`` = ``config.type`` = 该模板的 PLR 类名(物料权威按模板校验 ``class``,PLR 按 - ``config.type`` 构造)。 + ``class`` = 初始化它用的注册表名(即该模板,物料权威按模板校验 ``class``)、 + ``config.type`` = 该模板的 PLR 类名(PLR 按它反序列化)。写成 PLR 类名的 ``class`` + 在物料入库时按模板换成注册表名(:mod:`unilabos.resources.material_class`)。 这些形状只在**接收旧数据的边界**被识别并一次性转换:``-g`` 启动文件与 ``unilab graph upload`` 的读取入口(:func:`upgrade_legacy_graph_payload`)、旧后端 @@ -464,7 +465,8 @@ def _fill_material_plr_class( f"的 PLR 类 {class_name!r} 不一致:图里是旧版 PLR 序列化,需按当前模板重新创建该物料" ) node["template_name"] = template - node["class"] = class_name + # class 是初始化它用的注册表名(即模板名);config.type 是 PLR 类名 + node["class"] = template if not plr_type: node["config"] = {**config, "type": class_name} _move_foreign_config_to_data(node, class_name, entry, label) diff --git a/unilabos/client/host/ros2/presets/resource_mesh_manager.py b/unilabos/client/host/ros2/presets/resource_mesh_manager.py index e29d146b8..a54dff198 100644 --- a/unilabos/client/host/ros2/presets/resource_mesh_manager.py +++ b/unilabos/client/host/ros2/presets/resource_mesh_manager.py @@ -160,8 +160,10 @@ def add_resource_mesh(self,resource_config_str:str): if any(item['id'] == resource_config['id'] for item in self.resource_config_dict.values()): self.get_logger().info(f'资源 {resource_config["id"]} 已存在') return - if resource_config['class'] in registry.resource_type_registry.keys(): - model_config = registry.resource_type_registry[resource_config['class']]['model'] + # 注册表资源 id 是物料的 template_name;class 是完整类路径(旧图里才写资源 id) + registry_key = resource_config.get('template_name') or resource_config.get('class') + if registry_key in registry.resource_type_registry.keys(): + model_config = registry.resource_type_registry[registry_key]['model'] if model_config['type'] == 'resource': self.resource_model[resource_config['id']] = { 'mesh': f"{str(self.mesh_path)}/device_mesh/resources/{model_config['mesh']}", @@ -172,12 +174,12 @@ def add_resource_mesh(self,resource_config_str:str): 'mesh_tf': model_config['children_mesh_tf'] } resources = [resource_config] - if resource_config.get('class') in registry.resource_type_registry: + if registry_key in registry.resource_type_registry: # registry 资源类:实例化 PLR 草稿,经 ResourceTreeSet 展开为带父子 uuid 的扁平节点 from unilabos.resources.materials import instantiate_registry_resource from unilabos.resources.resource_tracker import ResourceTreeSet - draft = instantiate_registry_resource(resource_config['class'], resource_config['name']) + draft = instantiate_registry_resource(registry_key, resource_config['name']) tree_set = ResourceTreeSet.from_plr_resources([draft], known_random_uuid=True) resources = [node for tree in tree_set.dump() for node in tree] # 与 __init__ 一致按 uuid 建索引:resource_mesh_setup 按 parent_uuid 查父节点 diff --git a/unilabos/device_mesh/resource_visalization.py b/unilabos/device_mesh/resource_visalization.py index 5dc2423ca..bb493e6fc 100644 --- a/unilabos/device_mesh/resource_visalization.py +++ b/unilabos/device_mesh/resource_visalization.py @@ -96,7 +96,8 @@ def __init__(self, device: dict, resource: dict, enable_rviz: bool = True): if (node['type'] in self.resource_type and node['class'] != '') or (node['type'] == 'device' and node['class'] != ''): model_config = {} if node['type'] in self.resource_type: - resource_class = node['class'] + # 注册表资源 id 是物料的 template_name;class 是完整类路径(旧图里才写资源 id) + resource_class = node.get('template_name') or node['class'] if resource_class not in registry.resource_type_registry.keys(): raise ValueError(f"{node['id']}资源类型 {resource_class} 未在注册表中注册") elif "model" in registry.resource_type_registry[resource_class].keys(): diff --git a/unilabos/protocol/materials.py b/unilabos/protocol/materials.py index f1b53fc84..779eaf872 100644 --- a/unilabos/protocol/materials.py +++ b/unilabos/protocol/materials.py @@ -147,6 +147,7 @@ class ResourceTemplateWrite(ServerObject): name: NonEmptyStr display_name: Optional[NonEmptyStr] = None resource_type: NonEmptyStr = "resource" + #: 按这个模板初始化的物料的 class:注册表模板是注册表资源名(即模板名),实现模块在 ``module_name`` class_name: Optional[str] = None module_name: Optional[str] = None template_version: NonEmptyStr = "1" @@ -295,6 +296,8 @@ class MaterialIdentityWrite(ServerObject): display_name: str = "" description: str = "" resource_type: NonEmptyStr = "resource" + #: 初始化它用的注册表名(注册表资源名,与模板名相同;没有注册表条目的孩子是 PLR 类名; + #: 设备是注册表设备名)。PLR 类名在 ``config.type``,见 unilabos.resources.material_class。 class_name: NonEmptyStr = "Resource" machine_name: str = "" barcode: str = "" diff --git a/unilabos/resources/adapters/plr_materials.py b/unilabos/resources/adapters/plr_materials.py index afed939bd..ce1e0ef74 100644 --- a/unilabos/resources/adapters/plr_materials.py +++ b/unilabos/resources/adapters/plr_materials.py @@ -6,6 +6,7 @@ from dataclasses import dataclass from typing import Any, Collection, Mapping, Optional, Protocol, Sequence +from unilabos.resources.material_class import material_class from unilabos.resources.objects.naming import PLR_KEY_FIELD, canonical_uuid, plr_key from unilabos.resources.objects.resource import ResourceDict from unilabos.resources.resource_tracker import ResourceTreeSet @@ -257,9 +258,13 @@ def resource_tree_to_create( display_name=resource.display_name, description=resource.description, resource_type=resource.type, - class_name=( - resource.klass - or str(resource.config.get("type") or "Resource") + # 初始化它用的注册表名(没有注册表条目时是 PLR 类名;设备不变), + # 见 unilabos.resources.material_class + class_name=material_class( + resource_type=resource.type, + klass=resource.klass, + template_name=resource.template_name, + plr_type=resource.config.get("type"), ), machine_name=resource.machine_name, barcode=resource.barcode, diff --git a/unilabos/resources/adapters/registry_materials.py b/unilabos/resources/adapters/registry_materials.py index dd7ee515c..2f0bc7ce6 100644 --- a/unilabos/resources/adapters/registry_materials.py +++ b/unilabos/resources/adapters/registry_materials.py @@ -81,10 +81,11 @@ def _resource_type(definition: Mapping[str, Any]) -> str: def registry_resource_class_name(definition: Mapping[str, Any]) -> str | None: - """注册表资源条目的 PLR 类名:``config_info`` 里序列化的 ``config.type``,其次非通用的 ``class.type``。 + """注册表资源条目的 PLR 短类型名:``config_info`` 里序列化的 ``config.type``,其次非通用的 ``class.type``。 - 物料权威登记模板时用它填 ``class_name``,并按它校验物料的 ``class``;旧格式图在读图边界按 - 同一规则补齐 PLR 类名。条目没有 ``config_info``、``class.type`` 又是通用后端名时返回 None。 + 它是物料 ``config.type`` 的来源(PLR 反序列化靠它找类);旧格式图在读图边界按同一规则补齐。 + 物料与模板的 ``class`` 是注册表资源名本身(见 :mod:`unilabos.resources.material_class`)。 + 条目没有 ``config_info``、``class.type`` 又是通用后端名时返回 None。 """ components = [ @@ -173,7 +174,9 @@ def registry_definition_to_template( name=name, display_name=str(definition.get("display_name") or name), resource_type=_resource_type(definition), - class_name=registry_resource_class_name(definition), + # class 是初始化物料用的注册表名,即条目 id;实现模块在 module_name(class.module)。 + # 条目没有声明实现(没有 class.module)时没法按它初始化,模板不约束物料的 class。 + class_name=name if class_definition.get("module") else None, module_name=str(class_definition.get("module") or "") or None, template_version=str(definition.get("version") or "registry-v1"), category=category, diff --git a/unilabos/resources/material_class.py b/unilabos/resources/material_class.py new file mode 100644 index 000000000..1e303c374 --- /dev/null +++ b/unilabos/resources/material_class.py @@ -0,0 +1,101 @@ +"""物料 ``class`` 的约定:初始化它用的注册表名(registry name)。 + +字段沿用 ``class`` / ``class_name``(图文件、旧后端与前端都按这个名字读),含义如下: + +- 按注册表资源初始化的物料:``class`` 是注册表资源名(如 ``container``、``virtual_heating_sample``、 + ``opentrons_96_tiprack_300ul``),与它的资源模板名相同。实现所在的模块(注册表条目的 + ``class.module``)按这个名字在注册表里查,不另存; +- 没有注册表条目的 PLR 物料(孔位、枪头位等随父物料的注册表工厂一起建出来的孩子,或临时构造的 + PLR 资源):``class`` 退回 PLR 类名; +- 设备:注册表设备名(不变)。 + +``config.type`` 是 PLR 类名:设备重启重建 PLR 实例就是按它直接反序列化,``class`` 只是记录, +不参与重建。 +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, Optional + + +def registry_resource_entry(name: Any) -> Optional[Mapping[str, Any]]: + """注册表资源条目;名字不是注册表资源名(或目录不可用)时返回 None。 + + 资源类目录在调度权威里是 Host 上报的生效条目,在 Host / Slave 里是本地扫描。 + """ + + text = str(name or "").strip() + if not text: + return None + try: + from unilabos.registry.catalog import resource_entry + + entry = resource_entry(text) + except Exception: # noqa: BLE001 - 目录不可用时按没有注册表条目处理 + return None + return entry if isinstance(entry, Mapping) else None + + +def registry_resource_module(name: Any) -> Optional[str]: + """注册表资源名 → 实现所在的 ``module:attr``(条目的 ``class.module``);查不到返回 None。""" + + entry = registry_resource_entry(name) + definition = entry.get("class") if entry is not None else None + module = definition.get("module") if isinstance(definition, Mapping) else None + text = str(module or "").strip() + module_name, sep, attribute = text.partition(":") + return text if sep and module_name and attribute else None + + +def material_class( + *, + resource_type: Any = None, + klass: Any = None, + template_name: Any = None, + plr_type: Any = None, +) -> str: + """按约定得出物料的 ``class``:注册表资源名,没有注册表条目时退回 PLR 类名;设备不变。""" + + current = str(klass or "").strip() + if str(resource_type or "") == "device": + return current or str(template_name or plr_type or "Resource") + template = str(template_name or "").strip() + if template and registry_resource_entry(template) is not None: + return template + if current and registry_resource_entry(current) is not None: + return current + return str(plr_type or "").strip() or current or "Resource" + + +def resolve_material_class( + *, template_name: Any, template_class: Any, identity_class: Any, plr_type: Any = None +) -> Optional[str]: + """物料入库时落的 class;与模板对不上时返回 None。 + + 注册表模板的 class 就是模板名(注册表资源名)。两种过渡情形按模板归一: + + - 升级前登记的注册表模板 class 还是 PLR 类名(注册表同步一次后才改成注册表名):物料带来的 + class 等于模板名,照收; + - 带来物料的一方查不到注册表(如还没收到 Host 上报的调度权威、没升级的客户端),class 退回成了 + PLR 类名(等于 ``config.type``):落模板的 class,也就是注册表名。 + """ + + stored = str(template_class or "").strip() + incoming = str(identity_class or "").strip() + name = str(template_name or "").strip() + if not stored or stored == incoming: + return incoming or stored + if incoming == name: + return incoming + if stored == name and incoming and incoming == str(plr_type or "").strip(): + return stored + return None + + +__all__ = [ + "resolve_material_class", + "material_class", + "registry_resource_entry", + "registry_resource_module", +] diff --git a/unilabos/resources/materials.py b/unilabos/resources/materials.py index 7f25c7c83..7973c4310 100644 --- a/unilabos/resources/materials.py +++ b/unilabos/resources/materials.py @@ -30,7 +30,7 @@ from pylabrobot.resources import ItemizedResource from pylabrobot.resources import Resource as PLRResource -from unilabos.resources.resource_tracker import ResourceTreeInstance, ResourceTreeSet +from unilabos.resources.resource_tracker import ResourceTreeInstance, ResourceTreeSet, set_plr_template_name from unilabos.resources.adapters.plr_materials import ( CreatedPLRMaterials, MaterialGateway, @@ -48,7 +48,7 @@ MaterialTransferItem, MaterialTreeRead, ) -from unilabos.resources.objects.resource import EXTRA_BOUND_DEVICE +from unilabos.resources.objects.resource import EXTRA_BOUND_DEVICE, EXTRA_RESOURCE_CLASS from unilabos.utils.log import trace @@ -665,6 +665,11 @@ def instantiate_registry_resource(class_name: str, name: str) -> PLRResource: raise ValueError(f"registry 资源类 {class_name!r} 无法实例化({module}):{exc}") from exc if not isinstance(draft, PLRResource): raise ValueError(f"registry 资源类不可实例化: {class_name!r}") + # 物料记下初始化它用的注册表名:模板名就是它,入库后 class 也是它(见 + # unilabos.resources.material_class)。资源类自己登记了模板名的(按库位快照建的台面等)不覆盖。 + extra = getattr(draft, "unilabos_extra", None) + if not (isinstance(extra, dict) and extra.get(EXTRA_RESOURCE_CLASS)): + set_plr_template_name(draft, class_name) return draft diff --git a/unilabos/resources/objects/resource.py b/unilabos/resources/objects/resource.py index 8fc6e35bd..13a3a476a 100644 --- a/unilabos/resources/objects/resource.py +++ b/unilabos/resources/objects/resource.py @@ -105,7 +105,14 @@ class ResourceDict(BaseModel): description="Parent resource object", default=None, exclude=True ) type: Union[Literal["device"], str] = Field(description="Resource type") - klass: str = Field(alias="class", description="Resource class name") + klass: str = Field( + alias="class", + description=( + "Registry name the resource was initialized from (registry resource / device id); " + "PLR class name for children without a registry entry. The PLR class used for " + "deserialization is config.type" + ), + ) pose: ResourceDictPosition = Field( description="Resource pose relative to its parent, plus geometry/layout metadata", default_factory=ResourceDictPosition, diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index 20281af23..90eed7868 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -15,6 +15,7 @@ ResourceDictType, assemble_tracker_state, ) +from unilabos.resources.material_class import material_class from unilabos.resources.objects.naming import PLR_KEY_FIELD, plr_key from unilabos.resources.objects.site import ResourceSite from unilabos.resources.objects.state import TRACKER_STATE_KEYS @@ -1037,6 +1038,9 @@ def build_uuid_mapping( for child, child_data in iter_serialized_plr_children(res, serialized): build_uuid_mapping(child, child_data, uuid_list, uid) + #: (模板名, PLR 类名, 序列化里的 class) → 物料 class;本次转换内复用 + class_paths: Dict[Tuple[str, Any, Any], str] = {} + def resource_plr_inner( plr_resource: "PLRResource", d: dict, @@ -1121,6 +1125,18 @@ def resource_plr_inner( # 先构建当前节点的字典(不包含children)。物料 name 等于 uuid,PLR 名作为 # PLR 键存进 config.name(不改 PLR 对象本身),人读标签进 display_name。 + template_name = get_plr_template_name(plr_resource, d) + class_key = (template_name, d.get("type"), d.get("class", "")) + klass = class_paths.get(class_key) + if klass is None: + # class 是初始化它用的注册表名(注册表资源取模板名,没有注册表条目的孩子取 + # PLR 类名),config.type 是 PLR 类名,见 unilabos.resources.material_class。 + # 同一棵树里同模板同类的节点(板上的孔位)只查一次目录。 + klass = class_paths[class_key] = material_class( + klass=d.get("class", ""), + template_name=template_name, + plr_type=d.get("type"), + ) r_dict = { "id": d["name"], "uuid": current_uuid, @@ -1129,8 +1145,8 @@ def resource_plr_inner( "parent": parent_resource, # 直接传入 ResourceDict 对象 "parent_uuid": parent_uuid, # 使用 parent_uuid 而不是 parent 对象 "type": replace_plr_type(d.get("category", "")), - "class": d.get("class", ""), - "template_name": get_plr_template_name(plr_resource, d), + "class": klass, + "template_name": template_name, "pose": static_pose, "joint_state": joint_state, "config": { diff --git a/unilabos/server/mcp/guide.py b/unilabos/server/mcp/guide.py index 323ac034b..2b43e2328 100644 --- a/unilabos/server/mcp/guide.py +++ b/unilabos/server/mcp/guide.py @@ -59,7 +59,8 @@ retry 由调度产生新 attempt,旧失败记录保留;operator_intervention 才可替换结果。 - 材料 UUID 由物料权威分配;物料 name 恒等于 uuid,人读标签是 display_name(按名字搜索 / 筛选都匹配它), 业务 id 是 resource_id,PLR 树里的名字在 config.name;引用物料用 uuid 或 resource_id。 - template_name 是注册表模板;PLR 类只取 config.type,绝不回退外层 type/klass。材料位置与 substances 内容分开。 + template_name 是注册表模板;class 是初始化它用的注册表名(没有注册表条目的孩子是 PLR 类名), + PLR 类名只取 config.type,绝不回退外层 type/klass。材料位置与 substances 内容分开。 - materials 写入口保持 InventoryMutation 信封与原有事务校验;移交由服务端变更权威, 源设备卸载、目标设备 service load,不在 MCP 本地改树。 - 动作锁和物料锁交给调度(物料入参默认都加锁,驱动不能按动作豁免);复现竞争要先提交同组多个任务,再等待, diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index 0bdad2f88..551244ba1 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -82,6 +82,7 @@ plr_key, rekey_bare_label_items, ) +from unilabos.resources.material_class import registry_resource_module, resolve_material_class from unilabos.resources.objects.site import site_template_whitelist from unilabos.server.services.materials.snapshot import ( compare_material_snapshot, @@ -2286,7 +2287,8 @@ def ensure_links( @staticmethod def _validate_template_identity( template: ResourceTemplateRecord, identity: Any - ) -> None: + ) -> str: + """物料身份与模板对得上时返回入库用的 class(初始化它用的注册表名),否则抛错。""" if template.status != "active": raise MaterialValidationError( f"template is not active: {template.template_uuid}" @@ -2300,11 +2302,20 @@ def _validate_template_identity( # 子节点按类名共用组件模板(如所有 ``Well`` 都是模板 ``Well``),同一个类的 # 实例可以是 well / tube 等不同类型;模板上的 resource_type 只是按模板新建 # 物料时的默认值,物料自己的 resource_type 才是它的类型(建树后不可变)。 - if template.class_name and identity.class_name != template.class_name: + # class 是初始化物料用的注册表名,注册表模板的 class 就是模板名;两种过渡情形(模板还没 + # 按注册表同步、带来物料的一方查不到注册表)按模板归一,见 resolve_material_class。 + resolved = resolve_material_class( + template_name=template.name, + template_class=template.class_name, + identity_class=identity.class_name, + plr_type=(identity.config or {}).get("type"), + ) + if resolved is None: raise MaterialValidationError( f"class_name {identity.class_name!r} does not match template " f"{template.name!r} class_name {template.class_name!r}" ) + return resolved @staticmethod def _site_from_template( @@ -2411,6 +2422,7 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: node_ordinals[node.client_ref] = ordinal templates: dict[str, ResourceTemplateRecord] = {} resolved_templates: dict[str, ResourceTemplateRecord] = {} + resolved_classes: dict[str, str] = {} affected: list[AggregateVersion] = [] sequences: list[int] = [] node_sites: dict[str, list[SiteCreate]] = {} @@ -2431,6 +2443,8 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: display_name=node.identity.template_name, resource_type=node.identity.resource_type, class_name=node.identity.class_name, + # 模板名是注册表资源名时记下实现模块(与注册表同步的模板一致) + module_name=registry_resource_module(node.identity.template_name), available_sites=[ site.model_dump( mode="json", @@ -2499,7 +2513,9 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: ) templates[template_key] = template resolved_templates[node.client_ref] = template - self._validate_template_identity(template, node.identity) + resolved_classes[node.client_ref] = self._validate_template_identity( + template, node.identity + ) explicit_sites = list(node.sites) if not explicit_sites: explicit_sites = [ @@ -2562,7 +2578,7 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: display_name=display_name, description=identity.description, resource_type=identity.resource_type, - class_name=identity.class_name, + class_name=resolved_classes[node.client_ref], machine_name=identity.machine_name, barcode=identity.barcode, barcode_symbology=identity.barcode_symbology, diff --git a/unilabos/server/services/materials/inventory_commands.py b/unilabos/server/services/materials/inventory_commands.py index 011c3b4d1..4a4010ad8 100644 --- a/unilabos/server/services/materials/inventory_commands.py +++ b/unilabos/server/services/materials/inventory_commands.py @@ -780,7 +780,7 @@ def _instance_inbound(self, payload: Mapping[str, Any], *, actor: str) -> dict[s identity=MaterialIdentityWrite( resource_id=ResourceContract(self.materials)._resource_id(name), display_name=name, lot_uuid=lot_uuid, resource_type=template.resource_type, - class_name=template.class_name or template.resource_type or "Resource", + class_name=template.class_name or template.name, barcode=barcode, template_name=template.name, extra={"legacy_cloud_id": legacy} if legacy else {}, ), diff --git a/unilabos/server/services/materials/material_io.py b/unilabos/server/services/materials/material_io.py index 5bbbc26cc..46fcbbc10 100644 --- a/unilabos/server/services/materials/material_io.py +++ b/unilabos/server/services/materials/material_io.py @@ -278,7 +278,7 @@ def _load(self, plan: Mapping[str, Any], site: Any, *, command_id: str) -> dict[ resource_id=ResourceContract(self.materials)._resource_id(name), display_name=name, resource_type=template.resource_type, - class_name=template.class_name or template.resource_type or "Resource", + class_name=template.class_name or template.name, barcode=barcode, template_name=template.name, meta_data=meta_data, @@ -316,6 +316,7 @@ def _load_root(self, tree: MaterialTreeCreate, *, material_uuid: str, name: str, ``resource_id`` 是根的路径前缀,根换了不重名的 ID 时一起换。 """ + from unilabos.resources.material_class import material_class from unilabos.server.services.materials.resource_contract import ResourceContract root = next(node for node in tree.nodes if node.parent_client_ref is None) @@ -332,6 +333,13 @@ def _load_root(self, tree: MaterialTreeCreate, *, material_uuid: str, name: str, "display_name": name, "barcode": barcode, "template_name": template_name, + # 换成注册表模板后 class 跟着换成它的注册表名(与模板登记的 class 一致) + "class_name": material_class( + resource_type=root.identity.resource_type, + klass=root.identity.class_name, + template_name=template_name, + plr_type=root.identity.config.get("type"), + ), "meta_data": {**root.identity.meta_data, **meta_data}, }) diff --git a/unilabos/server/services/materials/resource_contract.py b/unilabos/server/services/materials/resource_contract.py index f60916e46..73d5ff85b 100644 --- a/unilabos/server/services/materials/resource_contract.py +++ b/unilabos/server/services/materials/resource_contract.py @@ -563,7 +563,7 @@ def create_material(self, values: Mapping[str, Any]) -> dict[str, Any]: display_name=display_name, description=str(values.get("description") or ""), resource_type=template.resource_type, - class_name=template.class_name or template.resource_type or "Resource", + class_name=template.class_name or template.name, barcode=barcode, template_name=template.name, config=_mapping(values.get("config")), diff --git a/unilabos/test/experiments/Protocol_Test_Station/add_protocol_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/add_protocol_test_station.json index 99980a8a6..5421b701f 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/add_protocol_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/add_protocol_test_station.json @@ -169,7 +169,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 50, @@ -195,7 +195,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 150, @@ -221,7 +221,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -247,7 +247,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 350, @@ -273,7 +273,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 450, @@ -299,7 +299,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -320,7 +320,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -341,7 +341,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -362,7 +362,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -383,7 +383,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -404,7 +404,7 @@ "children": [], "parent": "AddProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, diff --git a/unilabos/test/experiments/Protocol_Test_Station/centrifuge_protocol_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/centrifuge_protocol_test_station.json index 186b3081b..52718ba3c 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/centrifuge_protocol_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/centrifuge_protocol_test_station.json @@ -146,7 +146,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -172,7 +172,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -193,7 +193,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -214,7 +214,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -240,7 +240,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -266,7 +266,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -292,7 +292,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -313,7 +313,7 @@ "children": [], "parent": "CentrifugeProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, diff --git a/unilabos/test/experiments/Protocol_Test_Station/clean_vessel_protocol_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/clean_vessel_protocol_test_station.json index ff6b1db41..53bf0fd43 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/clean_vessel_protocol_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/clean_vessel_protocol_test_station.json @@ -148,7 +148,7 @@ "children": [], "parent": "CleanVesselProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 50, @@ -174,7 +174,7 @@ "children": [], "parent": "CleanVesselProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 150, @@ -200,7 +200,7 @@ "children": [], "parent": "CleanVesselProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -226,7 +226,7 @@ "children": [], "parent": "CleanVesselProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 350, @@ -247,7 +247,7 @@ "children": [], "parent": "CleanVesselProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -273,7 +273,7 @@ "children": [], "parent": "CleanVesselProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -299,7 +299,7 @@ "children": [], "parent": "CleanVesselProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, diff --git a/unilabos/test/experiments/Protocol_Test_Station/dual_valve_pump_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/dual_valve_pump_test_station.json index 615a2ec67..be1892afe 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/dual_valve_pump_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/dual_valve_pump_test_station.json @@ -119,7 +119,7 @@ "children": [], "parent": "DualValvePumpStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -145,7 +145,7 @@ "children": [], "parent": "DualValvePumpStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -171,7 +171,7 @@ "children": [], "parent": "DualValvePumpStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -197,7 +197,7 @@ "children": [], "parent": "DualValvePumpStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -218,7 +218,7 @@ "children": [], "parent": "DualValvePumpStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -239,7 +239,7 @@ "children": [], "parent": "DualValvePumpStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -260,7 +260,7 @@ "children": [], "parent": "DualValvePumpStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, diff --git a/unilabos/test/experiments/Protocol_Test_Station/evacuateandrefill_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/evacuateandrefill_test_station.json index d57d4b66d..923fa00b6 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/evacuateandrefill_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/evacuateandrefill_test_station.json @@ -228,7 +228,7 @@ "children": [], "parent": "EvacuateRefillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -254,7 +254,7 @@ "children": [], "parent": "EvacuateRefillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -280,7 +280,7 @@ "children": [], "parent": "EvacuateRefillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -306,7 +306,7 @@ "children": [], "parent": "EvacuateRefillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -327,7 +327,7 @@ "children": [], "parent": "EvacuateRefillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -369,7 +369,7 @@ "children": [], "parent": "EvacuateRefillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -390,7 +390,7 @@ "children": [], "parent": "EvacuateRefillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, diff --git a/unilabos/test/experiments/Protocol_Test_Station/evaporate_protocol_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/evaporate_protocol_test_station.json index 1995bb76e..5791717bc 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/evaporate_protocol_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/evaporate_protocol_test_station.json @@ -172,7 +172,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -198,7 +198,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -219,7 +219,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -240,7 +240,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -261,7 +261,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 50, @@ -287,7 +287,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 150, @@ -313,7 +313,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -339,7 +339,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 350, @@ -360,7 +360,7 @@ "children": [], "parent": "EvaporateProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, diff --git a/unilabos/test/experiments/Protocol_Test_Station/filter_protocol_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/filter_protocol_test_station.json index 831e44545..5e6070ccd 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/filter_protocol_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/filter_protocol_test_station.json @@ -174,7 +174,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -200,7 +200,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -221,7 +221,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -242,7 +242,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -263,7 +263,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -284,7 +284,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -310,7 +310,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -336,7 +336,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -362,7 +362,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -383,7 +383,7 @@ "children": [], "parent": "FilterProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, diff --git a/unilabos/test/experiments/Protocol_Test_Station/heatchill_protocol_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/heatchill_protocol_test_station.json index 25e9b849a..659c41130 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/heatchill_protocol_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/heatchill_protocol_test_station.json @@ -223,7 +223,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 50, @@ -249,7 +249,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 150, @@ -275,7 +275,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -301,7 +301,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 650, @@ -327,7 +327,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 350, @@ -353,7 +353,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 450, @@ -379,7 +379,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -400,7 +400,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -421,7 +421,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -442,7 +442,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -463,7 +463,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -484,7 +484,7 @@ "children": [], "parent": "HeatChillProtocolTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, diff --git a/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_filterthrough_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_filterthrough_test_station.json index 1191cd587..546b0dfb8 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_filterthrough_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_filterthrough_test_station.json @@ -134,7 +134,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -160,7 +160,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -186,7 +186,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -208,7 +208,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -230,7 +230,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -252,7 +252,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -273,7 +273,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -294,7 +294,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -315,7 +315,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -336,7 +336,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -357,7 +357,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -378,7 +378,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -404,7 +404,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -430,7 +430,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -456,7 +456,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -482,7 +482,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 500, @@ -508,7 +508,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -534,7 +534,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -555,7 +555,7 @@ "children": [], "parent": "PumpTransferFilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, diff --git a/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_test_station.json index e340028d0..80b8013c2 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/pumptransfer_test_station.json @@ -76,7 +76,7 @@ "children": [], "parent": "SimpleProtocolStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -102,7 +102,7 @@ "children": [], "parent": "SimpleProtocolStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -128,7 +128,7 @@ "children": [], "parent": "SimpleProtocolStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -154,7 +154,7 @@ "children": [], "parent": "SimpleProtocolStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -175,7 +175,7 @@ "children": [], "parent": "SimpleProtocolStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -196,7 +196,7 @@ "children": [], "parent": "SimpleProtocolStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -217,7 +217,7 @@ "children": [], "parent": "SimpleProtocolStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, diff --git a/unilabos/test/experiments/Protocol_Test_Station/run_column_protocol_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/run_column_protocol_test_station.json index 983b55257..7c1f952fe 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/run_column_protocol_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/run_column_protocol_test_station.json @@ -102,7 +102,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -129,7 +129,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -156,7 +156,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -183,7 +183,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -210,7 +210,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -231,7 +231,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, @@ -252,7 +252,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 800, @@ -273,7 +273,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -294,7 +294,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1000, @@ -315,7 +315,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, diff --git a/unilabos/test/experiments/Protocol_Test_Station/simple_stir_heatchill_test_station.json b/unilabos/test/experiments/Protocol_Test_Station/simple_stir_heatchill_test_station.json index ae8318162..dd62e9336 100644 --- a/unilabos/test/experiments/Protocol_Test_Station/simple_stir_heatchill_test_station.json +++ b/unilabos/test/experiments/Protocol_Test_Station/simple_stir_heatchill_test_station.json @@ -78,7 +78,7 @@ "children": [], "parent": "SimpleStirHeatChillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 500, @@ -104,7 +104,7 @@ "children": [], "parent": "SimpleStirHeatChillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 700, diff --git a/unilabos/test/experiments/comprehensive_protocol/comprehensive_station.json b/unilabos/test/experiments/comprehensive_protocol/comprehensive_station.json index 606f6b7cc..2458a902a 100644 --- a/unilabos/test/experiments/comprehensive_protocol/comprehensive_station.json +++ b/unilabos/test/experiments/comprehensive_protocol/comprehensive_station.json @@ -163,7 +163,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 200, @@ -189,7 +189,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -215,7 +215,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, @@ -241,7 +241,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -267,7 +267,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, @@ -337,7 +337,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -420,7 +420,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 500, @@ -446,7 +446,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1100, @@ -662,7 +662,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -688,7 +688,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, @@ -714,7 +714,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1050, @@ -763,7 +763,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -790,7 +790,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 600, @@ -816,7 +816,7 @@ "children": [], "parent": "OrganicSynthesisStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 650, diff --git a/unilabos/test/experiments/mock_devices/mock_all.json b/unilabos/test/experiments/mock_devices/mock_all.json index e92684b5c..3f84f585b 100644 --- a/unilabos/test/experiments/mock_devices/mock_all.json +++ b/unilabos/test/experiments/mock_devices/mock_all.json @@ -33,7 +33,7 @@ "type": "RegularContainer" }, "template_name": "container", - "class": "RegularContainer", + "class": "container", "name": "模拟容器", "type": "container", "parent": "MockChiller1", diff --git a/unilabos/test/experiments/mock_protocol/addteststation.json b/unilabos/test/experiments/mock_protocol/addteststation.json index 8d2f5d135..b8cdf697d 100644 --- a/unilabos/test/experiments/mock_protocol/addteststation.json +++ b/unilabos/test/experiments/mock_protocol/addteststation.json @@ -98,7 +98,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -125,7 +125,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 180, @@ -152,7 +152,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 260, @@ -179,7 +179,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 340, @@ -206,7 +206,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 720, @@ -227,7 +227,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 850, @@ -248,7 +248,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, @@ -275,7 +275,7 @@ "children": [], "parent": "AddTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, diff --git a/unilabos/test/experiments/mock_protocol/centrifugeteststation.json b/unilabos/test/experiments/mock_protocol/centrifugeteststation.json index a114fb8b2..07cfbaf41 100644 --- a/unilabos/test/experiments/mock_protocol/centrifugeteststation.json +++ b/unilabos/test/experiments/mock_protocol/centrifugeteststation.json @@ -95,7 +95,7 @@ "children": [], "parent": "CentrifugeTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -116,7 +116,7 @@ "children": [], "parent": "CentrifugeTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -137,7 +137,7 @@ "children": [], "parent": "CentrifugeTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -158,7 +158,7 @@ "children": [], "parent": "CentrifugeTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -179,7 +179,7 @@ "children": [], "parent": "CentrifugeTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, diff --git a/unilabos/test/experiments/mock_protocol/cleanvesselteststation.json b/unilabos/test/experiments/mock_protocol/cleanvesselteststation.json index 25095caa0..cc3a09d9c 100644 --- a/unilabos/test/experiments/mock_protocol/cleanvesselteststation.json +++ b/unilabos/test/experiments/mock_protocol/cleanvesselteststation.json @@ -90,7 +90,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -117,7 +117,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -144,7 +144,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -171,7 +171,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -192,7 +192,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -219,7 +219,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 850, @@ -246,7 +246,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1000, @@ -267,7 +267,7 @@ "children": [], "parent": "CleanVesselTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, diff --git a/unilabos/test/experiments/mock_protocol/dissolveteststation.json b/unilabos/test/experiments/mock_protocol/dissolveteststation.json index 2f7f37676..1afba7b17 100644 --- a/unilabos/test/experiments/mock_protocol/dissolveteststation.json +++ b/unilabos/test/experiments/mock_protocol/dissolveteststation.json @@ -109,7 +109,7 @@ "children": [], "parent": "DissolveTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -136,7 +136,7 @@ "children": [], "parent": "DissolveTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -163,7 +163,7 @@ "children": [], "parent": "DissolveTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -190,7 +190,7 @@ "children": [], "parent": "DissolveTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -217,7 +217,7 @@ "children": [], "parent": "DissolveTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1000, @@ -238,7 +238,7 @@ "children": [], "parent": "DissolveTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 850, diff --git a/unilabos/test/experiments/mock_protocol/filterteststation.json b/unilabos/test/experiments/mock_protocol/filterteststation.json index 7f0c803e9..7a1de5e54 100644 --- a/unilabos/test/experiments/mock_protocol/filterteststation.json +++ b/unilabos/test/experiments/mock_protocol/filterteststation.json @@ -94,7 +94,7 @@ "children": [], "parent": "FilterTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -115,7 +115,7 @@ "children": [], "parent": "FilterTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -136,7 +136,7 @@ "children": [], "parent": "FilterTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -157,7 +157,7 @@ "children": [], "parent": "FilterTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -178,7 +178,7 @@ "children": [], "parent": "FilterTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, diff --git a/unilabos/test/experiments/mock_protocol/filterthroughteststation.json b/unilabos/test/experiments/mock_protocol/filterthroughteststation.json index 53d8d9c36..6d130d8fd 100644 --- a/unilabos/test/experiments/mock_protocol/filterthroughteststation.json +++ b/unilabos/test/experiments/mock_protocol/filterthroughteststation.json @@ -94,7 +94,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -121,7 +121,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -148,7 +148,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -175,7 +175,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -202,7 +202,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 850, @@ -223,7 +223,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1000, @@ -244,7 +244,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -271,7 +271,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 150, @@ -298,7 +298,7 @@ "children": [], "parent": "FilterThroughTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 300, diff --git a/unilabos/test/experiments/mock_protocol/heatchillteststation.json b/unilabos/test/experiments/mock_protocol/heatchillteststation.json index 1e3f67e36..04906ab08 100644 --- a/unilabos/test/experiments/mock_protocol/heatchillteststation.json +++ b/unilabos/test/experiments/mock_protocol/heatchillteststation.json @@ -95,7 +95,7 @@ "children": [], "parent": "HeatChillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -116,7 +116,7 @@ "children": [], "parent": "HeatChillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -137,7 +137,7 @@ "children": [], "parent": "HeatChillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -158,7 +158,7 @@ "children": [], "parent": "HeatChillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -179,7 +179,7 @@ "children": [], "parent": "HeatChillTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, diff --git a/unilabos/test/experiments/mock_protocol/runcolumnteststation.json b/unilabos/test/experiments/mock_protocol/runcolumnteststation.json index 06e75ae98..05e5f1ea1 100644 --- a/unilabos/test/experiments/mock_protocol/runcolumnteststation.json +++ b/unilabos/test/experiments/mock_protocol/runcolumnteststation.json @@ -94,7 +94,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -121,7 +121,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -148,7 +148,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -175,7 +175,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -202,7 +202,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 750, @@ -223,7 +223,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 900, @@ -244,7 +244,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1050, @@ -265,7 +265,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1200, @@ -286,7 +286,7 @@ "children": [], "parent": "RunColumnTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, diff --git a/unilabos/test/experiments/mock_protocol/stirteststation.json b/unilabos/test/experiments/mock_protocol/stirteststation.json index 75ab58f54..0c812f21a 100644 --- a/unilabos/test/experiments/mock_protocol/stirteststation.json +++ b/unilabos/test/experiments/mock_protocol/stirteststation.json @@ -73,7 +73,7 @@ "children": [], "parent": "StirTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -94,7 +94,7 @@ "children": [], "parent": "StirTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -115,7 +115,7 @@ "children": [], "parent": "StirTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -136,7 +136,7 @@ "children": [], "parent": "StirTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -157,7 +157,7 @@ "children": [], "parent": "StirTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 850, @@ -178,7 +178,7 @@ "children": [], "parent": "StirTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, diff --git a/unilabos/test/experiments/mock_protocol/transferteststation.json b/unilabos/test/experiments/mock_protocol/transferteststation.json index 5d58d2cbb..c497e7bfa 100644 --- a/unilabos/test/experiments/mock_protocol/transferteststation.json +++ b/unilabos/test/experiments/mock_protocol/transferteststation.json @@ -53,7 +53,7 @@ "children": [], "parent": "TransferTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -74,7 +74,7 @@ "children": [], "parent": "TransferTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -95,7 +95,7 @@ "children": [], "parent": "TransferTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -116,7 +116,7 @@ "children": [], "parent": "TransferTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -137,7 +137,7 @@ "children": [], "parent": "TransferTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -158,7 +158,7 @@ "children": [], "parent": "TransferTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 850, @@ -179,7 +179,7 @@ "children": [], "parent": "TransferTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 950, diff --git a/unilabos/test/experiments/mock_protocol/washsolidteststation.json b/unilabos/test/experiments/mock_protocol/washsolidteststation.json index c45121201..504c28466 100644 --- a/unilabos/test/experiments/mock_protocol/washsolidteststation.json +++ b/unilabos/test/experiments/mock_protocol/washsolidteststation.json @@ -143,7 +143,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 100, @@ -170,7 +170,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 250, @@ -197,7 +197,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 400, @@ -224,7 +224,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 550, @@ -251,7 +251,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, @@ -278,7 +278,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 850, @@ -299,7 +299,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1000, @@ -320,7 +320,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1150, @@ -347,7 +347,7 @@ "children": [], "parent": "WashSolidTestStation", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 1000, diff --git a/unilabos/test/experiments/mock_reactor.json b/unilabos/test/experiments/mock_reactor.json index 1d0c9ccb4..5ae28aa4b 100644 --- a/unilabos/test/experiments/mock_reactor.json +++ b/unilabos/test/experiments/mock_reactor.json @@ -30,7 +30,7 @@ "children": [], "parent": "ReactorX", "type": "container", - "class": "RegularContainer", + "class": "container", "template_name": "container", "position": { "x": 698.1111111111111, From 8d0088c8480c6880c4f0dc5d3b5cd01b62e23f5e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:39:06 +0800 Subject: [PATCH 06/59] feat(resources): import material classes' modules from the registry before deserializing PLR deserializes by config.type and only finds classes already imported in the process. The PLR registration hook (plr_additional_res_reg) now has two defined ways to make them importable: 1. explicit: register_plr_module / register_plr_class (unchanged), for classes that are not reachable through a registry entry; 2. by registry: register_registry_resources(*names) takes a material's class (the registry name it was initialized from; legacy rows fall back to the template name), looks up the entry's class.module - usually a factory function - and registers the module part, i.e. the file the factory lives in, which defines or imports the class it returns. to_plr_resources registers the names found in the tree, then register() imports everything pending once per process; the class itself is still resolved only by config.type. The registry-wide scan in find_plr_resource_class stays as the last resort for rows without a registry name. --- tests/resources/test_plr_registration_hook.py | 79 +++++++++++++++++++ unilabos/resources/material_class.py | 5 +- unilabos/resources/plr_additional_res_reg.py | 55 ++++++++++--- unilabos/resources/resource_tracker.py | 13 ++- 4 files changed, 136 insertions(+), 16 deletions(-) diff --git a/tests/resources/test_plr_registration_hook.py b/tests/resources/test_plr_registration_hook.py index 32ed25170..c10fb299a 100644 --- a/tests/resources/test_plr_registration_hook.py +++ b/tests/resources/test_plr_registration_hook.py @@ -149,3 +149,82 @@ def test_core_preset_classes_deserialize_in_a_fresh_process(tmp_path): assert completed.returncode == 0, completed.stderr[-3000:] classes = set(json.loads(completed.stdout.strip().splitlines()[-1])) assert {"BottleCarrier", "Bottle", "WareHouse", "RegularContainer"} <= classes + + +@pytest.fixture() +def registry_pkg(tmp_path, monkeypatch): + """注册表里登记了工厂函数、自己不主动登记的驱动包:类只有 import 工厂所在的模块后才可见。""" + + from unilabos.registry.registry import lab_registry + + pkg = tmp_path / "fake_registry_pkg" + pkg.mkdir() + (pkg / "__init__.py").write_text("", encoding="utf-8") + (pkg / "labware.py").write_text( + "from pylabrobot.resources import Resource\n" + "class FakeRegistryPlate(Resource):\n" + " def __init__(self, name, size_x=10.0, size_y=10.0, size_z=10.0, category=None, model=None, **kwargs):\n" + " super().__init__(name=name, size_x=size_x, size_y=size_y, size_z=size_z, category=category, model=model)\n" + "def make_fake_plate(name):\n" + " return FakeRegistryPlate(name)\n", + encoding="utf-8", + ) + monkeypatch.syspath_prepend(str(tmp_path)) + for name in ("fake_registry_pkg", "fake_registry_pkg.labware"): + monkeypatch.delitem(sys.modules, name, raising=False) + monkeypatch.setitem( + lab_registry.resource_type_registry, + "fake_registry_plate", + {"class": {"module": "fake_registry_pkg.labware:make_fake_plate", "type": "pylabrobot"}}, + ) + yield "fake_registry_plate" + for name in ("fake_registry_pkg", "fake_registry_pkg.labware"): + sys.modules.pop(name, None) + + +def test_registry_name_registers_the_module_its_factory_lives_in(isolated_hook, registry_pkg): + from pylabrobot.resources import Resource + from pylabrobot.utils.object_parsing import find_subclass + + # 注册表名 → class.module 的模块部分;PLR 类名(孔位)与空名字跳过 + assert isolated_hook.register_registry_resources(registry_pkg, "Well", "") == ("fake_registry_pkg.labware",) + assert isolated_hook.register_registry_resources(registry_pkg) == () + assert "fake_registry_pkg.labware" not in sys.modules + + isolated_hook.register() + + assert "fake_registry_pkg.labware" in sys.modules + assert find_subclass("FakeRegistryPlate", Resource) is not None + + +def test_rebuild_registers_the_tree_classes_and_deserializes_by_config_type(isolated_hook, registry_pkg): + from uuid import uuid4 + + from unilabos.resources.resource_tracker import ( + ResourceDict, + ResourceDictInstance, + ResourceTreeInstance, + ResourceTreeSet, + ) + + node = ResourceDictInstance( + ResourceDict.model_validate( + { + "id": "plate_1", + "uuid": str(uuid4()), + "name": "plate_1", + "type": "plate", + "class": registry_pkg, + "template_name": registry_pkg, + "config": {"type": "FakeRegistryPlate", "name": "plate_1"}, + "data": {}, + "extra": {}, + "pose": {"size": {"width": 10, "height": 10, "depth": 10}}, + } + ) + ) + + (plate,) = ResourceTreeSet([ResourceTreeInstance(node)]).to_plr_resources() + + assert type(plate).__name__ == "FakeRegistryPlate" + assert "fake_registry_pkg.labware" in isolated_hook.registered_plr_modules() diff --git a/unilabos/resources/material_class.py b/unilabos/resources/material_class.py index 1e303c374..213c292cf 100644 --- a/unilabos/resources/material_class.py +++ b/unilabos/resources/material_class.py @@ -9,8 +9,9 @@ PLR 资源):``class`` 退回 PLR 类名; - 设备:注册表设备名(不变)。 -``config.type`` 是 PLR 类名:设备重启重建 PLR 实例就是按它直接反序列化,``class`` 只是记录, -不参与重建。 +``config.type`` 是 PLR 类名:设备重启重建 PLR 实例就是按它直接反序列化。反序列化之前按 ``class`` +把注册表条目 ``class.module`` 所在的模块 import 进来,让类可见(见 +:func:`unilabos.resources.plr_additional_res_reg.register_registry_resources`),不用 ``class`` 找类。 """ from __future__ import annotations diff --git a/unilabos/resources/plr_additional_res_reg.py b/unilabos/resources/plr_additional_res_reg.py index 500dcc00f..20bf8eaca 100644 --- a/unilabos/resources/plr_additional_res_reg.py +++ b/unilabos/resources/plr_additional_res_reg.py @@ -5,27 +5,31 @@ PLR 资源类、后端类必须在反序列化前被导入,否则报"找不到类型"。 框架在 :meth:`ResourceTreeSet.to_plr_resources` 和构造 PyLabRobot 风格驱动之前调用 -:func:`register`,把登记过的模块全部导入(幂等,只导入一次)。 +:func:`register`,把登记过的模块全部导入(幂等,只导入一次)。反序列化本身只按 ``type`` +(物料的 ``config.type``)找类,登记只负责让类所在的模块先 import 进来。 -使用方式: +两种登记方式: -- 外部驱动包在包导入时(如 ``__init__.py``)登记自己的资源/后端模块,可只写模块路径, - 从而延迟导入重模块:: +1. 主动登记:外部驱动包在包导入时(如 ``__init__.py``)登记自己的资源/后端模块,可只写模块路径, + 从而延迟导入重模块:: - from unilabos.resources.plr_additional_res_reg import register_plr_module + from unilabos.resources.plr_additional_res_reg import register_plr_module - register_plr_module("my_driver_pkg.labware", "my_driver_pkg.backends") + register_plr_module("my_driver_pkg.labware", "my_driver_pkg.backends") -- 已导入的类也可直接登记(记录其所在模块,可用作类装饰器):: + 已导入的类也可直接登记(记录其所在模块,可用作类装饰器):: - from unilabos.resources.plr_additional_res_reg import register_plr_class + from unilabos.resources.plr_additional_res_reg import register_plr_class - @register_plr_class - class MyDeck(Deck): ... + @register_plr_class + class MyDeck(Deck): ... -- 注册表条目(``class.type: pylabrobot`` + ``module: pkg.mod:Name``)里的资源类由 - :func:`unilabos.resources.resource_tracker.find_plr_resource_class` 按需懒加载, - 不必额外登记;本钩子覆盖不在注册表里的类(如自定义 Deck 子类、液体处理后端)。 +2. 按注册表自动登记(:func:`register_registry_resources`):物料的 ``class`` 是初始化它用的注册表名, + 注册表条目的 ``class.module``(``pkg.labware:make_plate``)多半指向模块里的工厂函数,函数返回的类 + 定义在(或 import 进)这个模块。登记模块部分(``pkg.labware``)并 import,类就进了 PLR 的子类表。 + ``to_plr_resources`` 反序列化之前对树里出现的注册表名自动做这一步,不必手写。 + +不在注册表里、也不在注册表条目模块里的类(如单独文件里的自定义 Deck 子类、液体处理后端)用方式 1。 内置的 ``WorkStationContainer``、``UniLiquidHandlerRvizBackend`` 与 ``unilabos.resources.presets`` 里的预设类(``RegularContainer``、``Bottle``、``ItemizedCarrier``、``BottleCarrier``、``WareHouse``) @@ -76,6 +80,30 @@ def register_plr_class(cls: T) -> T: return cls +def register_registry_resources(*names: str) -> Tuple[str, ...]: + """按注册表资源名登记实现模块(下一次 :func:`register` 时导入),返回这次新登记的模块。 + + 名字是物料的 ``class``(初始化它用的注册表名)或模板名;查到条目后取 ``class.module`` 的 + 模块部分——条目多半是模块里的工厂函数,import 函数所在的文件,它返回的类随之登记。 + 不是注册表资源名(如孔位的 PLR 类名)、条目没有声明实现的名字跳过。 + """ + + from unilabos.resources.material_class import registry_resource_module + + added: list[str] = [] + for name in dict.fromkeys(str(item or "").strip() for item in names): + module_path = registry_resource_module(name) if name else None + if module_path is None: + continue + module = module_path.partition(":")[0] + with _lock: + if module in _registered: + continue + _registered[module] = None + added.append(module) + return tuple(added) + + def registered_plr_modules() -> Tuple[str, ...]: """当前登记的全部模块(含内置),按登记顺序。""" @@ -110,5 +138,6 @@ def register() -> None: "register", "register_plr_class", "register_plr_module", + "register_registry_resources", "registered_plr_modules", ] diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index 90eed7868..727bfdde0 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -19,7 +19,7 @@ from unilabos.resources.objects.naming import PLR_KEY_FIELD, plr_key from unilabos.resources.objects.site import ResourceSite from unilabos.resources.objects.state import TRACKER_STATE_KEYS -from unilabos.resources.plr_additional_res_reg import register +from unilabos.resources.plr_additional_res_reg import register, register_registry_resources from unilabos.resources.plr_identity import ( material_children, material_serialization, @@ -1257,6 +1257,17 @@ def to_plr_resources(self, skip_devices=True) -> List["PLRResource"]: Returns: List[PLRResource]: PLR 资源实例列表 """ + # 只按 config.type 反序列化;先把类所在的模块 import 进来:物料的 class(初始化它用的 + # 注册表名,旧数据里退到模板名)对应注册表条目的 class.module 所在文件,连同主动登记的模块 + register_registry_resources( + *{ + name + for tree in self.trees + for node in tree.get_all_nodes() + if node.res_content.type != "device" + for name in (node.res_content.klass, node.res_content.template_name) + } + ) register() def collect_node_data( From d4d4773b9fb3e64fd68bd78a3e8b77b3e364bc5b Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:21:22 +0800 Subject: [PATCH 07/59] fix: decode subprocess output and the session file as UTF-8 On Windows with a Chinese locale, text=True / open() default to GBK. The dependency installer read pip/uv output strictly as GBK, so a non-GBK byte failed the driver package install. Subprocess output (pip, uv, dora) is now decoded as UTF-8 with errors="replace"; the session file and the dora benchmark log are written and read as UTF-8. --- unilabos/client/host/dora/benchmark/run.py | 2 +- unilabos/client/host/dora/runtime.py | 2 ++ unilabos/client/session.py | 4 ++-- unilabos/server/services/driver_packages.py | 2 +- unilabos/utils/environment_check.py | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/unilabos/client/host/dora/benchmark/run.py b/unilabos/client/host/dora/benchmark/run.py index 6065f6044..814131b21 100644 --- a/unilabos/client/host/dora/benchmark/run.py +++ b/unilabos/client/host/dora/benchmark/run.py @@ -59,7 +59,7 @@ def run_one(n: int, out_dir: str, bench_params: Dict[str, Any], device_tick_ms: log_path = os.path.join(out_dir, f"run_n{n}.log") print(f"[run] N={n} 启动 dataflow -> {df_path}") - with open(log_path, "w") as logf: + with open(log_path, "w", encoding="utf-8") as logf: proc = runtime.run_dataflow(df_path, stdout=logf, stderr=logf) deadline = time.monotonic() + bench_params.get("timeout_s", 30.0) + 30.0 while time.monotonic() < deadline: diff --git a/unilabos/client/host/dora/runtime.py b/unilabos/client/host/dora/runtime.py index b2ab0bfe9..56570c7c6 100644 --- a/unilabos/client/host/dora/runtime.py +++ b/unilabos/client/host/dora/runtime.py @@ -102,6 +102,8 @@ def _run_cli(args: List[str], timeout: float = 120.0) -> subprocess.CompletedPro capture_output=True, text=True, timeout=timeout, + encoding="utf-8", + errors="replace", ) diff --git a/unilabos/client/session.py b/unilabos/client/session.py index 5d5cb6c3a..1f72afd03 100644 --- a/unilabos/client/session.py +++ b/unilabos/client/session.py @@ -123,7 +123,7 @@ def _release_lock(self): def _load_state(self) -> SessionState: if self.session_file.exists(): try: - with open(self.session_file, "r") as f: + with open(self.session_file, "r", encoding="utf-8") as f: return SessionState.from_dict(json.load(f)) except (json.JSONDecodeError, KeyError): pass @@ -133,7 +133,7 @@ def _save_state(self): if self._state is None: return self.working_dir.mkdir(parents=True, exist_ok=True) - with open(self.session_file, "w") as f: + with open(self.session_file, "w", encoding="utf-8") as f: json.dump(self._state.to_dict(), f, indent=2) def get_state(self) -> SessionState: diff --git a/unilabos/server/services/driver_packages.py b/unilabos/server/services/driver_packages.py index c50a00c29..7c5a0fea9 100644 --- a/unilabos/server/services/driver_packages.py +++ b/unilabos/server/services/driver_packages.py @@ -846,7 +846,7 @@ def _install_dependencies(self, dependencies: List[str], upgrade: bool, log: Cal command = _dependency_install_command(installer, dependencies, upgrade) log("$ " + " ".join(command)) try: - proc = subprocess.run(command, capture_output=True, text=True, timeout=DEPENDENCY_INSTALL_TIMEOUT_S) + proc = subprocess.run(command, capture_output=True, text=True, timeout=DEPENDENCY_INSTALL_TIMEOUT_S, encoding="utf-8", errors="replace") except FileNotFoundError: log(f"[deps] {installer} 不可用,换下一个安装器") continue diff --git a/unilabos/utils/environment_check.py b/unilabos/utils/environment_check.py index a561ee063..645e8a656 100644 --- a/unilabos/utils/environment_check.py +++ b/unilabos/utils/environment_check.py @@ -42,7 +42,7 @@ def _has_uv() -> bool: _USE_UV = False else: try: - result = subprocess.run([uv_path, "--version"], capture_output=True, text=True, timeout=10) + result = subprocess.run([uv_path, "--version"], capture_output=True, text=True, timeout=10, encoding="utf-8", errors="replace") _USE_UV = result.returncode == 0 except Exception: _USE_UV = False From c3c02f001ebfdd04247cd3a00f758086bd123058 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:21:23 +0800 Subject: [PATCH 08/59] test(ros2): the goal-response stub knows settled jobs goal_response_callback checks _take_settled (jobs already settled when the device went offline); the hand-written _RosExecutionAdapter stub predates it. The test only runs where unilabos_msgs is installed, so it went unnoticed. --- tests/test_action_policy.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_action_policy.py b/tests/test_action_policy.py index 429662b69..fbf95889c 100644 --- a/tests/test_action_policy.py +++ b/tests/test_action_policy.py @@ -930,10 +930,13 @@ def result(self): class _RosExecutionAdapter: _request_goal_cancel = HostNode._request_goal_cancel + _take_settled = HostNode._take_settled def __init__(self): self._goals = {} self._inflight_goal_jobs = set() + # 设备离线时已收尾的作业(goal_response_callback 先查它,忽略迟到的受理) + self._settled_jobs = set() self._canceled_jobs = {"job-1"} self._goal_state_lock = threading.RLock() From a52a649aa52c119b2f528acf41894a340386592c Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:21:23 +0800 Subject: [PATCH 09/59] test: read and write text as UTF-8 explicitly; child processes run in UTF-8 mode Tests read UTF-8 files with a bare read_text() and decoded subprocess output with text=True, both defaulting to the locale (GBK on Chinese Windows), so 7 tests failed there while CI (PYTHONUTF8=1) passed. read_text / write_text / text-mode open() now pass encoding="utf-8", subprocess calls decode UTF-8 with errors="replace", and tests/conftest.py puts child processes in UTF-8 mode (PYTHONUTF8 / PYTHONIOENCODING, same as CI). --- tests/app/test_no_ros_installation.py | 6 +-- tests/app/test_package_management.py | 4 +- tests/app/test_process_lifetime.py | 2 +- tests/app/test_root_device_slaves.py | 2 +- tests/app/test_wheel_release.py | 6 +-- tests/client/host/hostlink/test_backend.py | 2 +- tests/client/host/ros2/test_slave_shutdown.py | 2 +- tests/client/host/runtime/test_node.py | 6 +-- tests/conftest.py | 7 +++ .../devices/test_virtual_devices_hostlink.py | 2 +- tests/e2e/readme_demos.py | 4 +- tests/e2e/run_mcp_demos.py | 2 +- tests/e2e/test_readme_demos.py | 2 +- tests/e2e/test_root_device_slaves.py | 4 +- .../registry/test_host_node_backend_parity.py | 2 +- .../test_typed_contract_dev_wiring.py | 2 +- tests/server/test_driver_source_changes.py | 52 +++++++++---------- tests/server/test_full_reset.py | 6 +-- .../server/test_package_operation_recovery.py | 4 +- tests/server/test_runtime_logs.py | 2 +- tests/server/test_v1_lab_workspace.py | 2 +- .../test_workflow_source_monitor_wiring.py | 6 +-- 22 files changed, 67 insertions(+), 60 deletions(-) diff --git a/tests/app/test_no_ros_installation.py b/tests/app/test_no_ros_installation.py index 25db77c34..b6a99d7ac 100644 --- a/tests/app/test_no_ros_installation.py +++ b/tests/app/test_no_ros_installation.py @@ -466,7 +466,7 @@ def test_full_profile_contains_all_python_development_dependencies(monkeypatch): assert {"pytest", "pytest-asyncio", "build", "ruff", "ipython", "jupyterlab", "pandas", "opcua"} <= names docs = (root / "unilabos/utils/requirements-docs.txt").read_text(encoding="utf-8") assert {line.strip() for line in docs.splitlines() if line.strip() and not line.startswith("#")} <= set(extras["full"]) - assert "-r ../unilabos/utils/requirements-docs.txt" in (root / "docs/requirements.txt").read_text() + assert "-r ../unilabos/utils/requirements-docs.txt" in (root / "docs/requirements.txt").read_text(encoding="utf-8") assert not any("ros-" in raw or "rclpy" in raw for raw in captured["install_requires"]) for raw in extras["full"]: requirement = Requirement(raw) @@ -492,8 +492,8 @@ def test_full_conda_profiles_cover_python_extras(monkeypatch): for distro, suffix in (("jazzy", ""), ("humble", "-humble")): # 厂商驱动 SDK(pprp / pylibftdi / pyautogui)随驱动包声明,不再进入 full assert ("pprp", []) not in recipes(distro, full=True) - full = yaml.safe_load((root / f".conda/full{suffix}/recipe.yaml").read_text()) - ros2 = yaml.safe_load((root / f".conda/ros2{suffix}/recipe.yaml").read_text()) + full = yaml.safe_load((root / f".conda/full{suffix}/recipe.yaml").read_text(encoding="utf-8")) + ros2 = yaml.safe_load((root / f".conda/ros2{suffix}/recipe.yaml").read_text(encoding="utf-8")) # Windows SDK 的选择使 full 成为平台包,不能把它发布成同名不同内容的 noarch。 assert "noarch" not in full["build"] dependencies = full["requirements"]["run"] + ros2["requirements"]["run"] diff --git a/tests/app/test_package_management.py b/tests/app/test_package_management.py index 06e43eb62..d23dc96ea 100644 --- a/tests/app/test_package_management.py +++ b/tests/app/test_package_management.py @@ -91,9 +91,9 @@ def test_changes_cli_returns_process_and_changed_file(package_stack, tmp_path, c source = tmp_path / "external" source.mkdir() code = source / "driver.py" - code.write_text("old") + code.write_text("old", encoding="utf-8") service.configure([str(source)], external_only=True) - code.write_text("new") + code.write_text("new", encoding="utf-8") service.source_changes.poll() service.source_changes.poll() capsys.readouterr() diff --git a/tests/app/test_process_lifetime.py b/tests/app/test_process_lifetime.py index 5fd623a62..41acd5b87 100644 --- a/tests/app/test_process_lifetime.py +++ b/tests/app/test_process_lifetime.py @@ -62,7 +62,7 @@ def _pid_alive(pid: int) -> bool: return kernel32.WaitForSingleObject(handle, 0) == 0x102 # WAIT_TIMEOUT:仍在运行 finally: kernel32.CloseHandle(handle) - result = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True) + result = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True, encoding="utf-8", errors="replace") state = result.stdout.strip() return bool(state) and not state.startswith("Z") diff --git a/tests/app/test_root_device_slaves.py b/tests/app/test_root_device_slaves.py index 7d25405c2..1c0f16b92 100644 --- a/tests/app/test_root_device_slaves.py +++ b/tests/app/test_root_device_slaves.py @@ -211,7 +211,7 @@ def test_flag_moves_each_root_device_into_its_own_spec(host: Path, tmp_path: Pat specs = dpx.load_specs(host) assert set(specs) == {"root-station", "root-valve"} assert all(spec.generated_by == "root_devices_as_slaves" and spec.auto_start for spec in specs.values()) - graph = json.loads((dpx.process_dir(host, "root-station") / dpx.graph_filename(specs["root-station"])).read_text("utf-8")) + graph = json.loads((dpx.process_dir(host, "root-station") / dpx.graph_filename(specs["root-station"])).read_text(encoding="utf-8")) assert [node["id"] for node in graph["nodes"]] == ["station", "pump", "vial"] assert [link["id"] for link in graph["links"]] == ["inner", "inner_by_uuid"] diff --git a/tests/app/test_wheel_release.py b/tests/app/test_wheel_release.py index b083733e3..2a7e2146a 100644 --- a/tests/app/test_wheel_release.py +++ b/tests/app/test_wheel_release.py @@ -254,7 +254,7 @@ def test_bundle_rejects_unlisted_wheels(bundle): def test_bundle_rejects_wrong_platform(bundle): path = bundle / "manifest.json" - manifest = json.loads(path.read_text()) + manifest = json.loads(path.read_text(encoding="utf-8")) manifest["platform"] = "wrong-platform" path.write_text(json.dumps(manifest), encoding="utf-8") with pytest.raises(RuntimeError, match="平台不匹配"): @@ -267,10 +267,10 @@ def test_installer_preserves_existing_environment(bundle, monkeypatch): prefix = bundle / ".venv" prefix.mkdir() sentinel = prefix / "keep.txt" - sentinel.write_text("user data") + sentinel.write_text("user data", encoding="utf-8") with pytest.raises(RuntimeError, match="不会覆盖"): installer.main() - assert sentinel.read_text() == "user data" + assert sentinel.read_text(encoding="utf-8") == "user data" def test_installer_is_offline_hash_locked_and_outside_checkout(bundle, monkeypatch): diff --git a/tests/client/host/hostlink/test_backend.py b/tests/client/host/hostlink/test_backend.py index 6c16128ba..dfe500000 100644 --- a/tests/client/host/hostlink/test_backend.py +++ b/tests/client/host/hostlink/test_backend.py @@ -801,7 +801,7 @@ def test_hostlink_backend_import_does_not_load_ros() -> None: [sys.executable, "-c", code], capture_output=True, text=True, - timeout=20, + timeout=20, encoding="utf-8", errors="replace", ) assert result.returncode == 0, result.stderr diff --git a/tests/client/host/ros2/test_slave_shutdown.py b/tests/client/host/ros2/test_slave_shutdown.py index afc1456bb..b469e8f5a 100644 --- a/tests/client/host/ros2/test_slave_shutdown.py +++ b/tests/client/host/ros2/test_slave_shutdown.py @@ -90,7 +90,7 @@ def test_stop_signal_exits_cleanly_with_code_zero(tmp_path, signum) -> None: env = {key: value for key, value in os.environ.items() if key != "ROS_DISCOVERY_SERVER"} env.update({"ROS_DOMAIN_ID": "117", "ROS_AUTOMATIC_DISCOVERY_RANGE": "LOCALHOST", "PYTHONUNBUFFERED": "1"}) process = subprocess.Popen( - [sys.executable, str(script)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env + [sys.executable, str(script)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env, encoding="utf-8", errors="replace" ) try: deadline = time.monotonic() + 30 diff --git a/tests/client/host/runtime/test_node.py b/tests/client/host/runtime/test_node.py index a61b7edf8..f0b7def39 100644 --- a/tests/client/host/runtime/test_node.py +++ b/tests/client/host/runtime/test_node.py @@ -205,7 +205,7 @@ def test_virtual_drivers_import_without_ros() -> None: [sys.executable, "-c", code], capture_output=True, text=True, - timeout=20, + timeout=20, encoding="utf-8", errors="replace", ) assert result.returncode == 0, result.stderr @@ -223,7 +223,7 @@ def test_liquid_handling_package_keeps_optional_rviz_ros_import_lazy() -> None: [sys.executable, "-c", code], capture_output=True, text=True, - timeout=20, + timeout=20, encoding="utf-8", errors="replace", ) assert result.returncode == 0, result.stderr @@ -247,6 +247,6 @@ def test_liquid_handler_drivers_import_in_hostlink_without_ros_runtime() -> None [sys.executable, "-c", code], capture_output=True, text=True, - timeout=30, + timeout=30, encoding="utf-8", errors="replace", ) assert result.returncode == 0, result.stderr diff --git a/tests/conftest.py b/tests/conftest.py index b8baea082..b028966b7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,8 +2,15 @@ from __future__ import annotations +import os + import pytest +# Windows 中文系统的默认编码是 GBK:用例起的子进程(python -c / python -m unilabos)一律跑 UTF-8 模式, +# 与 CI(PYTHONUTF8=1、PYTHONIOENCODING=utf-8)一致;测试进程自己的文本读写都显式写 encoding="utf-8"。 +os.environ.setdefault("PYTHONUTF8", "1") +os.environ.setdefault("PYTHONIOENCODING", "utf-8") + @pytest.fixture(autouse=True) def _release_database_root_locks(): diff --git a/tests/devices/test_virtual_devices_hostlink.py b/tests/devices/test_virtual_devices_hostlink.py index 9056a466e..e80f250b4 100644 --- a/tests/devices/test_virtual_devices_hostlink.py +++ b/tests/devices/test_virtual_devices_hostlink.py @@ -971,7 +971,7 @@ def test_protocol_vessel_lock_queues_other_tasks_without_locking_its_own_steps(t from tests.app.test_process_lifetime import _Unilab # 搅拌器按 0.05 倍跑:编译出的搅拌步(60 s 搅拌 + 30 s 沉降)约 4.5 秒,足够观察排队 - payload = json.loads((EXPERIMENTS / "Protocol_Test_Station" / "simple_stir_heatchill_test_station.json").read_text()) + payload = json.loads((EXPERIMENTS / "Protocol_Test_Station" / "simple_stir_heatchill_test_station.json").read_text(encoding="utf-8")) for node in payload["nodes"]: if node["id"] == "stirrer_1": node.setdefault("config", {})["time_scale"] = 0.05 diff --git a/tests/e2e/readme_demos.py b/tests/e2e/readme_demos.py index 3ba5974e2..9355dcf7a 100644 --- a/tests/e2e/readme_demos.py +++ b/tests/e2e/readme_demos.py @@ -313,7 +313,7 @@ def _git(*args: str, cwd: Path) -> str: check=True, capture_output=True, text=True, - timeout=300, + timeout=300, encoding="utf-8", errors="replace", ).stdout.strip() @@ -389,7 +389,7 @@ def _parse_windows_tcp_range(output: str) -> tuple[int, int]: def _windows_tcp_range() -> tuple[int, int]: result = subprocess.run( ["netsh", "interface", "ipv4", "show", "dynamicport", "tcp"], - capture_output=True, check=True, text=True, errors="replace", timeout=10, + capture_output=True, check=True, text=True, errors="replace", timeout=10, encoding="utf-8", ) return _parse_windows_tcp_range(result.stdout) diff --git a/tests/e2e/run_mcp_demos.py b/tests/e2e/run_mcp_demos.py index 0412917c8..d33c4016e 100644 --- a/tests/e2e/run_mcp_demos.py +++ b/tests/e2e/run_mcp_demos.py @@ -45,7 +45,7 @@ def _spawn(self, command: list[str], log_path: Path) -> subprocess.Popen: self._handles.append(handle) process = subprocess.Popen(command, cwd=self.repo_root, env=self.env, stdout=handle, stderr=subprocess.STDOUT, text=True, - creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0, encoding="utf-8", errors="replace") save(self.work_root / f"{role}-process.json", {"pid": process.pid, "command": command}) return process diff --git a/tests/e2e/test_readme_demos.py b/tests/e2e/test_readme_demos.py index ae33708f5..45607108d 100644 --- a/tests/e2e/test_readme_demos.py +++ b/tests/e2e/test_readme_demos.py @@ -168,7 +168,7 @@ def _spawn(self, command: list[str], log_path: Path) -> subprocess.Popen[str]: stdout=handle, stderr=subprocess.STDOUT, text=True, - start_new_session=os.name != "nt", + start_new_session=os.name != "nt", encoding="utf-8", errors="replace", ) def any_exited(self) -> bool: diff --git a/tests/e2e/test_root_device_slaves.py b/tests/e2e/test_root_device_slaves.py index 7d10ac8db..886b8b018 100644 --- a/tests/e2e/test_root_device_slaves.py +++ b/tests/e2e/test_root_device_slaves.py @@ -308,7 +308,7 @@ def test_failing_constructor_and_hung_action_stay_inside_their_slave(tmp_path: P stdout=handle, stderr=subprocess.STDOUT, text=True, - start_new_session=os.name != "nt", + start_new_session=os.name != "nt", encoding="utf-8", errors="replace", ) host_exited = lambda: host.poll() is not None # noqa: E731 sampler: Optional[_OnlineSampler] = None @@ -522,7 +522,7 @@ def test_root_device_slaves_compile_against_the_host_graph(tmp_path: Path) -> No stdout=handle, stderr=subprocess.STDOUT, text=True, - start_new_session=os.name != "nt", + start_new_session=os.name != "nt", encoding="utf-8", errors="replace", ) host_exited = lambda: host.poll() is not None # noqa: E731 try: diff --git a/tests/registry/test_host_node_backend_parity.py b/tests/registry/test_host_node_backend_parity.py index 699d6674d..af8fd3aa2 100644 --- a/tests/registry/test_host_node_backend_parity.py +++ b/tests/registry/test_host_node_backend_parity.py @@ -70,7 +70,7 @@ def _inspect_backend(backend: str) -> dict: cwd=ROOT, capture_output=True, text=True, - timeout=30, + timeout=30, encoding="utf-8", errors="replace", ) assert result.returncode == 0, result.stderr prefix = "HOST_INSPECTION=" diff --git a/tests/registry/test_typed_contract_dev_wiring.py b/tests/registry/test_typed_contract_dev_wiring.py index 97ef34b72..c046fea65 100644 --- a/tests/registry/test_typed_contract_dev_wiring.py +++ b/tests/registry/test_typed_contract_dev_wiring.py @@ -34,7 +34,7 @@ def dispense(self, source: ResourceSlot, reference: Annotated[ResourceSlot, Mate @action() def legacy(self, anything): return anything -''') +''', encoding="utf-8") devices, _, _ = _parse_file(path, tmp_path) return Registry()._build_device_entry_from_ast("typed_test", devices[0])["class"]["action_value_mappings"] diff --git a/tests/server/test_driver_source_changes.py b/tests/server/test_driver_source_changes.py index 1facb0c8c..d76b66f95 100644 --- a/tests/server/test_driver_source_changes.py +++ b/tests/server/test_driver_source_changes.py @@ -31,21 +31,21 @@ def test_content_changes_additions_deletions_and_noise(tmp_path): root = tmp_path / "unilabos_data" / "driver_packages" / "pump" / "1.0" root.mkdir(parents=True) code = root / "pump.py" - code.write_text("version = 1\n") + code.write_text("version = 1\n", encoding="utf-8") definition = root / "device.yaml" - definition.write_text("class: pump\n") + definition.write_text("class: pump\n", encoding="utf-8") monitor = DriverSourceChanges() register(monitor, root) previous = code.stat() - code.write_text("version = 2\n") + code.write_text("version = 2\n", encoding="utf-8") os.utime(code, ns=(previous.st_atime_ns, previous.st_mtime_ns)) definition.unlink() - (root / "new.py").write_text("pass\n") - (root / "run.log").write_text("log") + (root / "new.py").write_text("pass\n", encoding="utf-8") + (root / "run.log").write_text("log", encoding="utf-8") (root / "database.db").write_bytes(b"sqlite") for directory in [".git", "__pycache__", ".staging"]: (root / directory).mkdir() - (root / directory / "ignored.py").write_text("ignored") + (root / directory / "ignored.py").write_text("ignored", encoding="utf-8") monitor.poll() assert not monitor.status()["restart_required"] notice = settled(monitor)["notices"][0] @@ -64,14 +64,14 @@ def test_only_loaded_targets_and_host_cascade_are_reported(tmp_path): shared = tmp_path / "shared" shared.mkdir() code = shared / "driver.py" - code.write_text("old") + code.write_text("old", encoding="utf-8") other = tmp_path / "other" other.mkdir() monitor = DriverSourceChanges() register(monitor, shared, "host", "host") register(monitor, shared, "pump") register(monitor, other, "balance", auto_start=False) - code.write_text("new") + code.write_text("new", encoding="utf-8") notices = settled(monitor)["notices"] assert {n["process_id"] for n in notices} == {"host", "pump"} host = next(n for n in notices if n["target"] == "host") @@ -81,7 +81,7 @@ def test_only_loaded_targets_and_host_cascade_are_reported(tmp_path): host = next(n for n in monitor.status()["notices"] if n["target"] == "host") assert next(s for s in host["affected_slaves"] if s["id"] == "balance")["auto_start"] # 已检测的变化不会因读提示或代码改回去而假装已经重启。 - code.write_text("old") + code.write_text("old", encoding="utf-8") assert len(settled(monitor)["notices"]) == 2 register(monitor, shared, "pump") assert [n["process_id"] for n in monitor.status()["notices"]] == ["host"] @@ -91,19 +91,19 @@ def test_only_loaded_targets_and_host_cascade_are_reported(tmp_path): def test_saving_and_failed_package_transaction_do_not_publish_transient_files(tmp_path): code = tmp_path / "driver.py" - code.write_text("old") + code.write_text("old", encoding="utf-8") monitor = DriverSourceChanges() register(monitor, tmp_path) - code.write_text("partial") + code.write_text("partial", encoding="utf-8") monitor.poll() - code.write_text("finished") + code.write_text("finished", encoding="utf-8") monitor.poll() assert not monitor.status()["restart_required"] - code.write_text("old") + code.write_text("old", encoding="utf-8") monitor.mutation(True) code.unlink() settled(monitor) - code.write_text("old") + code.write_text("old", encoding="utf-8") monitor.mutation(False) assert not settled(monitor)["restart_required"] @@ -111,10 +111,10 @@ def test_saving_and_failed_package_transaction_do_not_publish_transient_files(tm def test_unreadable_source_is_visible_and_does_not_clear_notices(tmp_path, monkeypatch): from unilabos.server.services import driver_source_changes as module code = tmp_path / "driver.py" - code.write_text("old") + code.write_text("old", encoding="utf-8") monitor = DriverSourceChanges() register(monitor, tmp_path) - code.write_text("new") + code.write_text("new", encoding="utf-8") settled(monitor) def denied(roots): @@ -127,7 +127,7 @@ def denied(roots): def test_source_scan_does_not_follow_directory_symlink_loops(tmp_path): - (tmp_path / "driver.py").write_text("pass") + (tmp_path / "driver.py").write_text("pass", encoding="utf-8") (tmp_path / "loop").symlink_to(tmp_path, target_is_directory=True) assert len(source_snapshot([str(tmp_path)])) == 1 @@ -194,7 +194,7 @@ def test_slave_restart_clears_only_its_notice_and_api_returns_impact(services, t root = tmp_path / "driver_packages" / "pump" / "1.0" root.mkdir(parents=True) code = root / "driver.py" - code.write_text("old") + code.write_text("old", encoding="utf-8") dp.save_ledger(tmp_path, {"pump": dp.DriverPackageRecord(name="pump", package_root=str(root), package_dirs=[str(root)], enabled=False)}) packages.configure([], external_only=True) @@ -202,7 +202,7 @@ def test_slave_restart_clears_only_its_notice_and_api_returns_impact(services, t "package_names": ["pump"], "external_only": True, "extra_args": ["--working_dir", str(tmp_path)]}) processes.start(view["id"]) - code.write_text("new") + code.write_text("new", encoding="utf-8") settled(packages.source_changes) app = FastAPI() app.include_router(create_driver_packages_router()) @@ -218,7 +218,7 @@ def test_slave_restart_clears_only_its_notice_and_api_returns_impact(services, t assert processes._procs[view["id"]].poll() is None processes.restart(view["id"]) assert ok_data(client.get("/api/v1/driver-packages/changes"))["notices"] == [] - code.write_text("again") + code.write_text("again", encoding="utf-8") settled(packages.source_changes) processes.stop(view["id"]) assert not packages.source_changes.status()["restart_required"] @@ -229,12 +229,12 @@ def test_slave_baseline_precedes_popen(services, tmp_path, monkeypatch): root = tmp_path / "external" root.mkdir() code = root / "driver.py" - code.write_text("old") + code.write_text("old", encoding="utf-8") view = processes.create({"name": "外部驱动", "graph_nodes": [{"id": "pump", "class": "pump"}], "devices_dirs": [str(root)], "external_only": True}) def launching(*args, **kwargs): - code.write_text("changed during child startup") + code.write_text("changed during child startup", encoding="utf-8") return FakeProcess() monkeypatch.setattr(dpx.subprocess, "Popen", launching) @@ -248,11 +248,11 @@ def test_package_root_metadata_outside_python_directory_is_watched(services, tmp code = root / "src" / "pump" code.mkdir(parents=True) metadata = root / "pyproject.toml" - metadata.write_text('[project]\nname="pump"\nversion="1"\n') + metadata.write_text('[project]\nname="pump"\nversion="1"\n', encoding="utf-8") dp.save_ledger(tmp_path, {"pump": dp.DriverPackageRecord(name="pump", package_root=str(root), package_dirs=[str(code)], enabled=True)}) packages.configure([str(code)], external_only=True) - metadata.write_text('[project]\nname="pump"\nversion="2"\n') + metadata.write_text('[project]\nname="pump"\nversion="2"\n', encoding="utf-8") notice = settled(packages.source_changes)["notices"][0] assert notice["changed_files"] == [{"path": str(metadata), "change": "modified"}] @@ -262,8 +262,8 @@ def test_dependency_installer_failure_still_warns_shared_processes(services, tmp source = tmp_path / "new_package" code = source / "pump" code.mkdir(parents=True) - (code / "__init__.py").write_text("") - (source / "pyproject.toml").write_text('[project]\nname="pump"\nversion="1"\ndependencies=["pyserial"]\n') + (code / "__init__.py").write_text("", encoding="utf-8") + (source / "pyproject.toml").write_text('[project]\nname="pump"\nversion="1"\ndependencies=["pyserial"]\n', encoding="utf-8") packages.configure([], external_only=True) register(packages.source_changes, tmp_path / "other", "balance") diff --git a/tests/server/test_full_reset.py b/tests/server/test_full_reset.py index 77e7c094b..cac305ffd 100644 --- a/tests/server/test_full_reset.py +++ b/tests/server/test_full_reset.py @@ -44,15 +44,15 @@ def test_archives_only_explicit_targets_and_keeps_packages(tmp_path): edge = reset.paths.root / "edge" edge.mkdir() (edge / "history.db").write_bytes(b"edge-history") - (tmp_path / "device_processes.json").write_text("{}") + (tmp_path / "device_processes.json").write_text("{}", encoding="utf-8") packages = tmp_path / "driver_packages.json" - packages.write_text("keep") + packages.write_text("keep", encoding="utf-8") reset.request(reset.token, "清空全部数据") assert reset.paths.runtime_db.exists() # 请求只登记;必须停机后才执行。 reset.finish() assert not reset.paths.runtime_db.exists() assert not (edge / "history.db").exists() - assert packages.read_text() == "keep" + assert packages.read_text(encoding="utf-8") == "keep" assert (reset.backup / "manifest.json").exists() assert not (reset.paths.root / "reset-pending.json").exists() diff --git a/tests/server/test_package_operation_recovery.py b/tests/server/test_package_operation_recovery.py index 01a096e24..43f2e7a1a 100644 --- a/tests/server/test_package_operation_recovery.py +++ b/tests/server/test_package_operation_recovery.py @@ -59,7 +59,7 @@ def checkpoint(operation_id, **values): @pytest.mark.parametrize('phase,committed', [('before_move', False), ('before_ledger', False), ('after_ledger', True), ('uninstall', False)]) def test_process_crash_reconciles_source_and_ledger_once_and_requires_confirmation(tmp_path, monkeypatch, phase, committed): process = subprocess.run([sys.executable, '-c', CRASH_SCRIPT, str(tmp_path), phase], - capture_output=True, text=True, timeout=30) + capture_output=True, text=True, timeout=30, encoding="utf-8", errors="replace") assert process.returncode == 73, process.stdout + process.stderr service = dp.DriverPackageService(tmp_path) operation = service.operations()[0] @@ -68,7 +68,7 @@ def test_process_crash_reconciles_source_and_ledger_once_and_requires_confirmati assert operation['recovery']['outcome'] == ('committed' if committed else 'rolled_back') record = dp.load_ledger(tmp_path)['demo'] assert record.device_ids == (['new'] if committed else ['old']) - assert ('new' if committed else 'old') in (Path(record.package_root) / 'demo/pump.py').read_text() + assert ('new' if committed else 'old') in (Path(record.package_root) / 'demo/pump.py').read_text(encoding="utf-8") gate = get_host_mutation_gate(tmp_path) with pytest.raises(HostMutationBusy): gate.acquire('slave_start') diff --git a/tests/server/test_runtime_logs.py b/tests/server/test_runtime_logs.py index b56b55e40..cb1b1125a 100644 --- a/tests/server/test_runtime_logs.py +++ b/tests/server/test_runtime_logs.py @@ -55,7 +55,7 @@ def test_tail_incremental_two_readers_and_utf8(tmp_path: Path): @pytest.mark.parametrize("change", ["replace", "truncate", "source"]) def test_reset_on_file_or_source_change(tmp_path: Path, change: str): path = tmp_path / "host.log" - path.write_text("old line\n" * 20) + path.write_text("old line\n" * 20, encoding="utf-8") old = reader.read_log_file(path, source_id="host") source = "host" if change == "replace": diff --git a/tests/server/test_v1_lab_workspace.py b/tests/server/test_v1_lab_workspace.py index b96f15e45..e5d3d3fbb 100644 --- a/tests/server/test_v1_lab_workspace.py +++ b/tests/server/test_v1_lab_workspace.py @@ -64,7 +64,7 @@ def test_package_mounts_and_file_browser(tmp_path) -> None: package_dir = tmp_path / "pkgs" / "acme_driver" package_dir.mkdir(parents=True) (tmp_path / "work" / "sub").mkdir(parents=True) - (tmp_path / "work" / "run.py").write_text("print(1)\n") + (tmp_path / "work" / "run.py").write_text("print(1)\n", encoding="utf-8") packages = SimpleNamespace(inventory=lambda: {"packages": [ {"name": "acme", "version": "1.2.0", "enabled": True, "dirs_exist": True, "source_kind": "local", "package_dirs": [str(package_dir)], "device_ids": ["acme.pump"], "sha256": "abc"}, diff --git a/tests/server/test_workflow_source_monitor_wiring.py b/tests/server/test_workflow_source_monitor_wiring.py index 647e2d1ed..db2b3bbb3 100644 --- a/tests/server/test_workflow_source_monitor_wiring.py +++ b/tests/server/test_workflow_source_monitor_wiring.py @@ -97,7 +97,7 @@ def test_authority_retries_pending_writeback_on_restart_and_watches_external_edi expected_workflow_revision=workflow["revision"]) registration = service._registration(workflow["uuid"]) target = Path(registration["package_root"]) / registration["relative_path"] - assert target.read_text() == SOURCE + assert target.read_text(encoding="utf-8") == SOURCE # Apply 已提交,但这一次(以及进程退出前的每次重试)写回源码都失败 def failing_write(*_args, **_kwargs): @@ -124,7 +124,7 @@ def failing_write(*_args, **_kwargs): service = _start_authority(paths) record = service.get_authoring_record(workflow["uuid"]) assert record["writeback_status"] == "settled" - assert target.read_text() == SOURCE + assert target.read_text(encoding="utf-8") == SOURCE # 外部编辑器改了源码:监视线程重新编译出对应的新候选 edited = SOURCE.replace("amount: float = 2.0", "amount: float = 3.0") @@ -168,7 +168,7 @@ def flaky_write(*args, **kwargs): assert [item["code"] for item in applied["apply_result"]["warnings"]] == ["draft_writeback_pending"] target.unlink() _wait_for(lambda: service.get_authoring_record(workflow["uuid"])["writeback_status"] == "settled") - assert target.read_text() == SOURCE + assert target.read_text(encoding="utf-8") == SOURCE finally: reset_for_test() From 2cba476279e404456b4c41b74c9caded0ef8cba0 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:51:02 +0800 Subject: [PATCH 10/59] test(e2e): demo subprocesses run this checkout, not an installed unilabos subprocess_env now puts the repository root first on PYTHONPATH (as test_process_lifetime already does). Where an older unilabos is installed in the environment, `python -m unilabos` otherwise ran that copy: unknown --root_devices_as_slaves, and the old CLI was refused by the new server (401). --- tests/e2e/readme_demos.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/e2e/readme_demos.py b/tests/e2e/readme_demos.py index 9355dcf7a..444eb5c5f 100644 --- a/tests/e2e/readme_demos.py +++ b/tests/e2e/readme_demos.py @@ -499,6 +499,8 @@ def subprocess_env(extra: dict[str, str]) -> dict[str, str]: if not key.startswith("UNILABOS_") and not any(key.startswith(spec.package.upper() + "_") for spec in DEMOS) } environment.update({"PYTHONUNBUFFERED": "1", "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}) + # 子进程跑本仓库的代码,不用环境里装过的旧版 unilabos(与 test_process_lifetime 同一做法) + environment["PYTHONPATH"] = os.pathsep.join(filter(None, [str(REPO_ROOT), environment.get("PYTHONPATH")])) environment.update(extra) return environment From 8d62c6ad90471860f8fb9323c1871c8015ada092 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:51:10 +0800 Subject: [PATCH 11/59] test: the reconnect-logging test captures each record once under pytest 9 pytest 9 attaches its capture handlers directly to loggers that do not propagate (unilabos.comm). Turning propagation on as well made every record reach caplog twice, so the WARNING/DEBUG sequence the test checks was off by one. Propagation is only switched on when pytest did not attach the handler. --- tests/server/test_backend_control_protocol.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/server/test_backend_control_protocol.py b/tests/server/test_backend_control_protocol.py index b6c10b62a..7f2c3b6dc 100644 --- a/tests/server/test_backend_control_protocol.py +++ b/tests/server/test_backend_control_protocol.py @@ -97,7 +97,9 @@ def test_reconnect_failures_are_not_logged_as_errors_each_time(caplog) -> None: comm_logger = logging.getLogger("unilabos.comm") previous_propagate = comm_logger.propagate - comm_logger.propagate = True # 通信日志独立成文件时不向上传播,caplog 需要它传播 + # 通信日志独立成文件时不向上传播。pytest 9 起直接把捕获 handler 挂到不传播的 logger 上,再打开传播 + # 会让同一条记录被捕获两次;旧版只在根 logger 上捕获,才需要打开传播。 + comm_logger.propagate = caplog.handler not in comm_logger.handlers client = BackendWebSocketClient("ws://127.0.0.1:1/api/v1/ws/schedule") client._running = True refused = ConnectionRefusedError(1225, "远程计算机拒绝网络连接") From b744ec9699f8c8f271cbcd5e9867edb77e2c011d Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:30:04 +0800 Subject: [PATCH 12/59] feat(events): push material invalidations on /api/v1/events The frontend keeps a single event stream per station, because a second long-lived connection per tab starves REST under HTTP/1.1. It refreshes material views on material.changed from that stream. The backend only published material changes on /api/v1/materials/events, so material views fell back to a 30 s poll. While this process holds the materials authority, /api/v1/events now compares the ledger tail about once a second, together with the workflow poll. When the tail changes it pushes an id-less material.changed with data {"sequence": }, like the runtime.logs.changed notices. The workflow cursor and Last-Event-ID are untouched, the baseline is fixed before the response headers, and a failed ledger read skips that round instead of breaking the stream. /api/v1/materials/events stays for clients that replay by sequence. --- docs/developer_guide/api_v1_migration.md | 3 +- docs/developer_guide/interfaces/realtime.md | 9 +- .../test_runtime_events_material_notices.py | 96 +++++++++++++++++++ unilabos/server/api/runtime/events.py | 60 +++++++++++- 4 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 tests/server/test_runtime_events_material_notices.py diff --git a/docs/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index 25872bd5a..3a28209ad 100644 --- a/docs/developer_guide/api_v1_migration.md +++ b/docs/developer_guide/api_v1_migration.md @@ -149,7 +149,8 @@ dev 内部异常到业务码的映射集中在 `envelope.py`,不在各路由 (`task` / `node_run` / `node_job` / `manual_confirmation` / `resource`)放进 V1 事件,不再单独发事件名; 原载荷字段保留。换名在 API 层(`api/runtime/events.py:to_v1_event`)做,`frontend_event` 表仍存 dev 名。 `runtime.logs.changed`(无 id 的日志通知)与物料的 `/api/v1/materials/events`(`materials.changed`)不在 - V1 合同里,暂保持原名。CLI `workflow watch` 同步修改。 + V1 合同里,暂保持原名。物料失效另以 V1 名 `material.changed`(无 id,`data.sequence` 为账本末尾)随 + `/api/v1/events` 推送,前端每个工站只维持这一条事件流。CLI `workflow watch` 同步修改。 ## 库存与工作区(p7-c 落地) diff --git a/docs/developer_guide/interfaces/realtime.md b/docs/developer_guide/interfaces/realtime.md index 3b079babe..109d1ce54 100644 --- a/docs/developer_guide/interfaces/realtime.md +++ b/docs/developer_guide/interfaces/realtime.md @@ -4,8 +4,8 @@ | 使用者 | 通道 | 内容 | | --- | --- | --- | -| 浏览器工作流页、日志页 | SSE `/api/v1/events` | 持久工作流变更 + 瞬时日志失效通知 | -| 浏览器物料库、地图 | SSE `/api/v1/materials/events` | 物料账本变更通知 | +| 浏览器(每个工站一条) | SSE `/api/v1/events` | 持久工作流变更 + 瞬时日志失效通知 + 瞬时物料失效通知(`material.changed`) | +| 需要按账本续传 / 精确失效的客户端 | SSE `/api/v1/materials/events` | 物料账本变更通知(`materials.changed`,带 sequence 游标) | | Host ↔ 微后端/上游 Backend | WS `/api/v1/ws/schedule` + HTTP | runtime.v1 控制、命令正文与事件回收 | | Host ↔ Slave | HostLink TCP,默认 7302 | 握手、路由、RPC、topic、物料投影、日志 | | 本机 AI 客户端 | Streamable HTTP `/mcp` | 工具调用,不是上述浏览器事件流 | @@ -31,6 +31,11 @@ | 无事件时 | keepalive 注释;工作流检查约 1 秒,心跳约 15 秒 | keepalive 注释;约 1 秒检查账本 | 三个游标相互独立:工作流 id、物料 sequence、日志 stream:offset。不能混用,也不能以最后日志通知替换工作流游标。 + +`/api/v1/events` 上的 `material.changed` 与日志通知一样**不带 id**:本进程持有物料权威时,后端约每秒比较一次 +账本末尾序号,变了就推 `event: material.changed` + `data: {"sequence": <账本末尾>}`。它只说明"物料变了、请重读", +不回放、不占工作流游标;断线期间的物料变化由重连后的 REST 补读覆盖。浏览器因此每个工站只需维持 +`/api/v1/events` 一条长连接(HTTP/1.1 下每个源最多约 6 条连接,多开标签页时第二条流会挤占 REST)。 后端内部检查账本不等于要求浏览器每秒 GET 全量数据;前端维持事件流,仅在失效时拉取。 ### 物料通知 diff --git a/tests/server/test_runtime_events_material_notices.py b/tests/server/test_runtime_events_material_notices.py new file mode 100644 index 000000000..6fe98e12f --- /dev/null +++ b/tests/server/test_runtime_events_material_notices.py @@ -0,0 +1,96 @@ +"""/api/v1/events 的物料失效:账本前进就推一条无 id 的 material.changed,不动工作流游标。 + +前端每个工站只维持这一条事件流(HTTP/1.1 连接数有限),物料失效与工作流、日志通知走同一条。 +""" + +from __future__ import annotations + +import asyncio +import json +from types import SimpleNamespace +from unittest.mock import Mock + +from unilabos.server.api.runtime import events + + +class _Request: + async def is_disconnected(self): + return False + + +class _NoLogNotices: + def subscribe(self, listener): + return lambda: None + + +def _quiet(monkeypatch): + monkeypatch.setattr(events, "log_notices", _NoLogNotices()) + monkeypatch.setattr(events, "shutting_down", lambda: False) + + +def test_ledger_advance_emits_one_idless_material_changed(monkeypatch): + _quiet(monkeypatch) + workflow = Mock() + workflow.read_event_window.return_value = (1, 41, []) + + async def scenario(): + stream = events.runtime_event_stream( + _Request(), workflow, cursor=41, material_sequence=lambda: 7, material_cursor=5 + ) + assert "connected" in await anext(stream) + frame = await asyncio.wait_for(anext(stream), 2) + assert frame.startswith("event: material.changed\n") + assert "id:" not in frame + assert json.loads(frame.split("data: ")[1]) == {"sequence": 7} + await stream.aclose() + + asyncio.run(scenario()) + + +def test_unchanged_ledger_sends_nothing_before_workflow_events(monkeypatch): + _quiet(monkeypatch) + workflow = Mock() + workflow.read_event_window.return_value = (1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}]) + + async def scenario(): + stream = events.runtime_event_stream( + _Request(), workflow, cursor=41, material_sequence=lambda: 7, material_cursor=7 + ) + assert "connected" in await anext(stream) + frame = await asyncio.wait_for(anext(stream), 2) + assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") + await stream.aclose() + + asyncio.run(scenario()) + + +def test_ledger_read_failure_does_not_break_the_workflow_stream(monkeypatch): + _quiet(monkeypatch) + workflow = Mock() + workflow.read_event_window.return_value = (1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}]) + + def broken(): + raise RuntimeError("materials.db is locked") + + async def scenario(): + stream = events.runtime_event_stream( + _Request(), workflow, cursor=41, material_sequence=broken, material_cursor=3 + ) + assert "connected" in await anext(stream) + frame = await asyncio.wait_for(anext(stream), 2) + assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") + await stream.aclose() + + asyncio.run(scenario()) + + +def test_reader_exists_only_where_the_materials_authority_lives(monkeypatch): + from unilabos.server import execution_composition + + monkeypatch.setattr(execution_composition, "get_materials_service", lambda: None) + assert events.material_sequence_reader() is None + + authority = SimpleNamespace(latest_ledger_sequence=lambda: 12) + monkeypatch.setattr(execution_composition, "get_materials_service", lambda: authority) + reader = events.material_sequence_reader() + assert reader is not None and reader() == 12 diff --git a/unilabos/server/api/runtime/events.py b/unilabos/server/api/runtime/events.py index df9eb90ab..aad39bf18 100644 --- a/unilabos/server/api/runtime/events.py +++ b/unilabos/server/api/runtime/events.py @@ -19,12 +19,19 @@ ``workflow.authoring.changed`` 在库里就是 V1 名,原样发送:``@workflow`` 源码创作的状态迁移 (``data.cause``),以及工作流定义的变化(``data.change``:``created`` / ``updated`` / ``deleted`` / ``graph_saved`` / ``published``),都与变更同一事务写入。游标与 ``stream.reset`` 协议不变。 + +物料失效:本进程持有物料权威时,物料账本前进就推一条**不带 id** 的 ``material.changed`` +(``data: {"sequence": <账本末尾序号>}``),与日志通知一样不动工作流游标。只维持这一条事件流的 +前端据此重读物料;要按账本 sequence 续传、按 aggregate 精确失效的客户端仍用 +``/api/v1/materials/events``(``materials.changed``)。 """ from __future__ import annotations import asyncio +import json import time +from collections.abc import Callable from typing import Any, Dict @@ -41,6 +48,8 @@ RUNTIME_CHANGED_EVENT = "workflow.runtime.changed" AUTHORING_CHANGED_EVENT = "workflow.authoring.changed" ERROR_HANDLING_CHANGED_EVENT = "station.error_handling.changed" +#: 物料账本前进的瞬时失效通知(无 id,不占工作流游标) +MATERIAL_CHANGED_EVENT = "material.changed" #: dev 持久事件名 → (V1 事件名, data.kind)。不在表里的事件名原样发送。 _V1_EVENTS: Dict[str, tuple[str, str | None]] = { @@ -65,8 +74,40 @@ def to_v1_event(event: Dict[str, Any]) -> Dict[str, Any]: return {**event, "event": name, "data": data} +def material_sequence_reader() -> Callable[[], int] | None: + """本进程持有物料权威时返回"账本末尾序号"读取函数;Host 子进程等没有权威的进程返回 None。""" + + try: + from unilabos.server.execution_composition import get_materials_service + except ImportError: + return None + reader = getattr(get_materials_service(), "latest_ledger_sequence", None) + return reader if callable(reader) else None + + +def _read_material_sequence(reader: Callable[[], int], fallback: int) -> int: + try: + return int(reader()) + except Exception: # noqa: BLE001 - 读不到账本只是这一轮不发失效,不能断开工作流事件流 + return fallback + + +def material_changed_frame(sequence: int) -> str: + """不写 SSE id:Last-Event-ID 只表示工作流持久事件的序号。""" + + data = json.dumps({"sequence": sequence}, separators=(",", ":")) + return f"event: {MATERIAL_CHANGED_EVENT}\ndata: {data}\n\n" + + async def runtime_event_stream( - request: Request, service=None, cursor: int = 0, *, watermark: bool = False, replay: bool = False + request: Request, + service=None, + cursor: int = 0, + *, + watermark: bool = False, + replay: bool = False, + material_sequence: Callable[[], int] | None = None, + material_cursor: int = 0, ): from unilabos.server.api.runtime.workflow import format_sse_event @@ -97,6 +138,12 @@ def receive(notice: RuntimeLogNotice): now = time.monotonic() if now >= next_workflow: next_workflow = now + 1 + if material_sequence is not None: + # 账本末尾变了(前进,或库被重置后变小)就发一次失效;只比较末尾,不回放账本。 + latest_material = _read_material_sequence(material_sequence, material_cursor) + if latest_material != material_cursor: + material_cursor = latest_material + yield material_changed_frame(latest_material) if service is not None: oldest, latest, events = service.read_event_window(after_id=cursor, limit=101) reason = None @@ -158,9 +205,18 @@ async def events( # 必须在发送响应头之前固定水位,客户端 onopen 后的 REST 补读才能覆盖 # “快照 → 订阅”之间的变化。纯执行面的 Host 没有 Workflow Authority。 cursor = service.latest_event_sequence() if service is not None else 0 + # 物料账本基线同样在响应头之前固定:onopen 后的 REST 补读覆盖此前的物料变化。 + material_sequence = material_sequence_reader() + material_cursor = _read_material_sequence(material_sequence, 0) if material_sequence is not None else 0 return StreamingResponse( runtime_event_stream( - request, service, cursor, watermark=fresh and service is not None, replay=bool(value) and cursor == 0 + request, + service, + cursor, + watermark=fresh and service is not None, + replay=bool(value) and cursor == 0, + material_sequence=material_sequence, + material_cursor=material_cursor, ), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, From 22e87cdde8644077e28fa4c4af5443c824bfb994 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:34:39 +0800 Subject: [PATCH 13/59] feat(workflow): derive the V1 inventory_requirements list from the nodes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Node meta_data.inventory_requirements is what scheduling, preflight and task binding use. The V1 graph root list was always [] (dev keeps no separate requirement table), so requirements that will be reserved never showed up in clients. The frontend's node 资源需求 tab and run preparation said 「该工作流没有声明库存需求」 for the demo's flow. Reading a graph now projects each node requirement into the V1 shape: - uuid is uuid5 of workflow, node and key, so it is stable per read. - content maps to current_substance, lot to lot (splittable), material to material (1 件). - A key repeated across nodes becomes /, as task bindings write it. - A quantity given by a runtime reference reads 0 and is flagged quantity_dynamic. - The original entry, the inventory mode and whether reservation is deferred ride along in meta_data.unilab. Nodes stay the only source: nothing new is stored, and the existing visibility filter still hides private sub-graph requirements. --- ...kflow_inventory_requirements_projection.py | 144 ++++++++++++++++++ unilabos/server/api/runtime/workflow.py | 9 +- .../runtime/workflow/definition_edit.py | 92 ++++++++++- 3 files changed, 242 insertions(+), 3 deletions(-) create mode 100644 tests/server/test_workflow_inventory_requirements_projection.py diff --git a/tests/server/test_workflow_inventory_requirements_projection.py b/tests/server/test_workflow_inventory_requirements_projection.py new file mode 100644 index 000000000..a1d04024a --- /dev/null +++ b/tests/server/test_workflow_inventory_requirements_projection.py @@ -0,0 +1,144 @@ +"""工作流库存需求:节点 ``meta_data.inventory_requirements`` 是唯一来源,V1 图根列表每次读取从节点派生。 + +前端只读 V1 图根 ``inventory_requirements``(节点「资源需求」页签、运行准备);以前这里恒为空, +节点上真实声明的需求(调度据此预留)在前端看不到。 +""" + +from __future__ import annotations + +from typing import Any +from uuid import NAMESPACE_URL, uuid4, uuid5 + +import pytest +from fastapi.testclient import TestClient + +from unilabos.server.api.runtime.workflow import create_workflow_app +from unilabos.server.services.runtime.workflow.definition_edit import ( + definition_graph, + project_inventory_requirements, +) +from unilabos.server.services.runtime.workflow.service import WorkflowService + +WORKFLOW = "11111111-1111-4111-8111-111111111111" +PLATE_TEMPLATE = "22222222-2222-4222-8222-222222222222" +WATER_TEMPLATE = "33333333-3333-4333-8333-333333333333" + + +def _node(uuid: str, requirements: list[dict[str, Any]], **meta: Any) -> dict[str, Any]: + return { + "uuid": uuid, + "type": "device_action", + "execution_policy": {}, + "meta_data": {"target_device_id": "dev-a", "inventory_requirements": requirements, **meta}, + } + + +def test_node_requirements_project_to_the_v1_list() -> None: + graph = { + "workflow": {"uuid": WORKFLOW}, + "nodes": [ + _node("node-a", [{"key": "resource", "kind": "material", "template_uuid": PLATE_TEMPLATE}]), + _node("node-b", [{"key": "water", "kind": "lot", "template_uuid": WATER_TEMPLATE, "quantity": 1200.0, "unit": "ul"}]), + _node( + "node-c", + [{"key": "water", "kind": "lot", "template_uuid": WATER_TEMPLATE, + "quantity": {"kind": "workflow_input", "parameter": "volume"}, "unit": "ul"}], + ), + _node( + "node-d", + [{"key": "buffer", "kind": "content", "substance_name": "PBS", "quantity": 4, "unit": "ml", + "material_uuid": {"kind": "node_output", "workflow_node_uuid": "node-a", "data_key": "plate"}}], + ), + {"uuid": "node-e", "type": "device_action", "meta_data": {}}, + ], + "edges": [], + } + + items = project_inventory_requirements(graph) + by_node = {item["consume_node_uuid"]: item for item in items} + assert set(by_node) == {"node-a", "node-b", "node-c", "node-d"} + for item in items: + assert item["workflow_uuid"] == WORKFLOW + assert item["uuid"] == str( + uuid5(NAMESPACE_URL, f"unilabos://workflow/{WORKFLOW}/{item['consume_node_uuid']}/{item['meta_data']['unilab']['inventory']['key']}") + ) + + plate = by_node["node-a"] + assert (plate["target_type"], plate["required_quantity"], plate["quantity_unit"], plate["allow_split"]) == ( + "material", 1.0, "件", False, + ) + assert plate["requirement_key"] == "resource" + assert plate["meta_data"]["unilab"]["inventory"]["template_uuid"] == PLATE_TEMPLATE + assert plate["meta_data"]["unilab"]["deferred"] is False + + # 同一 key 出现在两个节点:按任务绑定的写法区分 + water = by_node["node-b"] + assert water["requirement_key"] == "node-b/water" + assert (water["target_type"], water["required_quantity"], water["quantity_unit"], water["allow_split"]) == ( + "lot", 1200.0, "ul", True, + ) + assert water["meta_data"]["unilab"]["quantity_dynamic"] is False + + # 数量是入口引用:V1 只能给有限数,记 0 并标出来;含引用的需求推迟到节点就绪 + dynamic = by_node["node-c"] + assert dynamic["requirement_key"] == "node-c/water" + assert dynamic["required_quantity"] == 0.0 and dynamic["quantity_unit"] == "ul" + assert dynamic["meta_data"]["unilab"]["quantity_dynamic"] is True + assert dynamic["meta_data"]["unilab"]["deferred"] is True + + content = by_node["node-d"] + assert (content["target_type"], content["required_quantity"], content["quantity_unit"]) == ("current_substance", 4.0, "ml") + assert content["meta_data"]["unilab"]["material_source_node_uuid"] == "node-a" + + # 与 definition_graph 的可见性过滤配合:私有子图节点的需求不出现在本层 + assert definition_graph({**graph, "inventory_requirements": items})["inventory_requirements"] == items + + +def test_graph_without_node_requirements_keeps_an_empty_list() -> None: + graph = {"workflow": {"uuid": WORKFLOW}, "nodes": [{"uuid": "n", "meta_data": {}}], "edges": []} + assert project_inventory_requirements(graph) == [] + + +@pytest.fixture +def api(): + service = WorkflowService(":memory:") + try: + yield TestClient(create_workflow_app(service)), service + finally: + service.close() + + +def _ok(response, status: int = 200) -> Any: + assert response.status_code == status, response.text + body = response.json() + assert body["code"] == 0, body + return body.get("data") + + +def test_saved_node_requirements_come_back_in_the_v1_graph(api) -> None: + client, _service = api + workflow = _ok(client.post("/api/v1/workflows", json={"name": "加液", "workflow_type": "experiment_operation"}), 201) + node = { + "uuid": str(uuid4()), "name": "加液", "type": "device_action", "material_uuid": str(uuid4()), + "action_name": "fill_well", "action_type": "UniLabJsonCommand", "param": {"slot": "T1"}, + "pose": {"x": 0, "y": 0}, "execution_policy": {"depends_on": []}, + "meta_data": { + "target_device_id": "material_bench", + "inventory_requirements": [ + {"key": "water", "kind": "lot", "template_uuid": WATER_TEMPLATE, "quantity": 1200.0, "unit": "ul"} + ], + }, + } + saved = _ok(client.put(f"/api/v1/workflows/{workflow['uuid']}/graph", json={ + "revision": workflow["revision"], "nodes": [node], "edges": [], + })) + graph = _ok(client.get(f"/api/v1/workflows/{workflow['uuid']}/graph")) + for payload in (saved, graph): + [item] = payload["inventory_requirements"] + assert item["consume_node_uuid"] == node["uuid"] + assert item["workflow_uuid"] == workflow["uuid"] + assert (item["requirement_key"], item["target_type"], item["required_quantity"], item["quantity_unit"]) == ( + "water", "lot", 1200.0, "ul", + ) + # 节点上的原条目保持不变(调度据此预留) + assert graph["nodes"][0]["meta_data"]["inventory_requirements"][0]["key"] == "water" diff --git a/unilabos/server/api/runtime/workflow.py b/unilabos/server/api/runtime/workflow.py index 46b405a63..30136d552 100644 --- a/unilabos/server/api/runtime/workflow.py +++ b/unilabos/server/api/runtime/workflow.py @@ -518,7 +518,10 @@ def public_workflow(record: Dict[str, Any]) -> Dict[str, Any]: def with_workflow_status(payload: Any) -> Any: """V1 图投影:工作流补派生状态与类别,节点 / 连线只呈现当前层(组合调用私有子图隐藏)。""" - from unilabos.server.services.runtime.workflow.definition_edit import definition_graph + from unilabos.server.services.runtime.workflow.definition_edit import ( + definition_graph, + project_inventory_requirements, + ) if not isinstance(payload, dict): return payload @@ -527,7 +530,9 @@ def with_workflow_status(payload: Any) -> Any: return payload projected = dict(payload) projected["workflow"] = public_workflow(workflow) - projected.setdefault("inventory_requirements", []) + # 库存需求只存在节点 meta_data 里(调度唯一来源);V1 图根列表每次从节点派生,供客户端查看。 + if not projected.get("inventory_requirements"): + projected["inventory_requirements"] = project_inventory_requirements(projected) return definition_graph(projected) def write_payload(body: BaseModel) -> Dict[str, Any]: diff --git a/unilabos/server/services/runtime/workflow/definition_edit.py b/unilabos/server/services/runtime/workflow/definition_edit.py index 21e7c72fa..58c0ae339 100644 --- a/unilabos/server/services/runtime/workflow/definition_edit.py +++ b/unilabos/server/services/runtime/workflow/definition_edit.py @@ -2,10 +2,13 @@ from __future__ import annotations +import math +from collections import Counter from copy import deepcopy from typing import Any, Mapping -from uuid import uuid4 +from uuid import NAMESPACE_URL, uuid4, uuid5 +from unilabos.protocol.runtime.inventory import inventory_deferred from unilabos.protocol.runtime.workflow import ( normalize_json_object, normalize_manual_confirmation, @@ -297,6 +300,93 @@ def private_node_owners(nodes: list[dict[str, Any]]) -> dict[str, str]: return result +#: 节点库存需求 kind → V1 ``target_type``(content 是容器里的当前内容物) +_V1_TARGET_TYPES = {"material": "material", "lot": "lot", "content": "current_substance"} +#: 按件物料在 V1 列表里的数量与单位(V1 只有"数量 + 单位",按件即 1 件) +_MATERIAL_QUANTITY = (1.0, "件") +#: 数量 / 单位是运行时引用(workflow_input / node_output)时 V1 列表里的占位单位 +_DYNAMIC_UNIT = "运行时决定" + + +def _finite_number(value: Any) -> float | None: + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + number = float(value) + return number if math.isfinite(number) else None + + +def project_inventory_requirements(graph: Mapping[str, Any]) -> list[dict[str, Any]]: + """节点 ``meta_data.inventory_requirements`` → V1 图根 ``inventory_requirements``(只读投影)。 + + 节点级需求是调度、预检与绑定的唯一来源;V1 图根列表只给客户端看,每次读取都从节点派生, + 不单独存储。V1 形状没有 kind / 模板 / 批次 / 容器身份,原条目原样放进 + ``meta_data.unilab.inventory``;数量是运行时引用时记 0 并标 ``quantity_dynamic``。 + 同一 key 出现在多个节点时 ``requirement_key`` 写成 ``/``,与任务绑定的写法一致。 + """ + + workflow = graph.get("workflow") if isinstance(graph.get("workflow"), Mapping) else {} + workflow_uuid = str(workflow.get("uuid") or "") + entries: list[tuple[Mapping[str, Any], Mapping[str, Any]]] = [] + for node in graph.get("nodes") or []: + if not isinstance(node, Mapping): + continue + meta = node.get("meta_data") if isinstance(node.get("meta_data"), Mapping) else {} + for item in meta.get("inventory_requirements") or []: + if isinstance(item, Mapping) and item.get("kind") in _V1_TARGET_TYPES and str(item.get("key") or ""): + entries.append((node, item)) + key_counts = Counter(str(item["key"]) for _, item in entries) + + projected: list[dict[str, Any]] = [] + for node, item in entries: + node_uuid = str(node.get("uuid") or "") + if not node_uuid: + continue + meta = node.get("meta_data") if isinstance(node.get("meta_data"), Mapping) else {} + node_items = [entry for entry in meta.get("inventory_requirements") or [] if isinstance(entry, Mapping)] + policy = node.get("execution_policy") if isinstance(node.get("execution_policy"), Mapping) else {} + mode = str(meta.get("inventory_mode") or "task") + try: + deferred = inventory_deferred([dict(entry) for entry in node_items], policy=policy, mode=mode) + except ValueError: + deferred = True + kind = str(item["kind"]) + key = str(item["key"]) + if kind == "material": + quantity, unit = _MATERIAL_QUANTITY + dynamic = False + else: + number = _finite_number(item.get("quantity")) + raw_unit = item.get("unit") + dynamic = number is None or not isinstance(raw_unit, str) or not raw_unit.strip() + quantity = number if number is not None else 0.0 + unit = raw_unit.strip() if isinstance(raw_unit, str) and raw_unit.strip() else _DYNAMIC_UNIT + unilab: dict[str, Any] = { + "inventory": deepcopy(dict(item)), + "inventory_mode": mode, + "deferred": deferred, + "quantity_dynamic": dynamic, + } + source = item.get("material_uuid") + if isinstance(source, Mapping) and source.get("kind") == "node_output": + source_node = str(source.get("workflow_node_uuid") or "") + if source_node: + unilab["material_source_node_uuid"] = source_node + projected.append( + { + "uuid": str(uuid5(NAMESPACE_URL, f"unilabos://workflow/{workflow_uuid}/{node_uuid}/{key}")), + "workflow_uuid": workflow_uuid, + "consume_node_uuid": node_uuid, + "requirement_key": key if key_counts[key] == 1 else f"{node_uuid}/{key}", + "target_type": _V1_TARGET_TYPES[kind], + "required_quantity": quantity, + "quantity_unit": unit, + "allow_split": kind == "lot", + "meta_data": {"unilab": unilab}, + } + ) + return projected + + def definition_graph(graph: Mapping[str, Any]) -> dict[str, Any]: """返回本层节点和边,保留子操作合同 pin、具名实参及外部输出接线。""" owners = private_node_owners(graph["nodes"]) From 48be7ca40afa7660e6e4e1215f8131e3a5787e45 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:37:11 +0800 Subject: [PATCH 14/59] feat(events): name the changed materials in material.changed The materials page refreshes incrementally. It rereads only the ids a material.changed names, and a notice that names nothing reads nothing, so a bare {"sequence": N} never refreshed the page. The notice now carries material_uuids: every material row in the ledger window, plus the owner of every Site that was occupied, vacated, created or deleted (its Site list changed). When the list cannot be exact (more than 500 rows, a resource template change, a reset ledger) material_uuids is left out, which tells the client to reload everything. A test against a real MaterialsService places a sample on a device Site and gets back both the sample and the device. --- docs/developer_guide/interfaces/realtime.md | 6 +- .../test_runtime_events_material_notices.py | 169 ++++++++++++++---- unilabos/server/api/runtime/events.py | 99 +++++++--- 3 files changed, 212 insertions(+), 62 deletions(-) diff --git a/docs/developer_guide/interfaces/realtime.md b/docs/developer_guide/interfaces/realtime.md index 109d1ce54..fbe78dc1c 100644 --- a/docs/developer_guide/interfaces/realtime.md +++ b/docs/developer_guide/interfaces/realtime.md @@ -33,8 +33,10 @@ 三个游标相互独立:工作流 id、物料 sequence、日志 stream:offset。不能混用,也不能以最后日志通知替换工作流游标。 `/api/v1/events` 上的 `material.changed` 与日志通知一样**不带 id**:本进程持有物料权威时,后端约每秒比较一次 -账本末尾序号,变了就推 `event: material.changed` + `data: {"sequence": <账本末尾>}`。它只说明"物料变了、请重读", -不回放、不占工作流游标;断线期间的物料变化由重连后的 REST 补读覆盖。浏览器因此每个工站只需维持 +账本末尾序号,变了就推 `event: material.changed` + +`data: {"sequence": <账本末尾>, "material_uuids": [<这段账本里变了的物料>]}`(Site 的占用变化归到所属物料)。 +客户端只重读列出的物料;列不准时(一次超过 500 条、资源模板变化、库被重置)省略 `material_uuids`, +表示整体重读。它不回放、不占工作流游标;断线期间的物料变化由重连后的 REST 补读覆盖。浏览器因此每个工站只需维持 `/api/v1/events` 一条长连接(HTTP/1.1 下每个源最多约 6 条连接,多开标签页时第二条流会挤占 REST)。 后端内部检查账本不等于要求浏览器每秒 GET 全量数据;前端维持事件流,仅在失效时拉取。 diff --git a/tests/server/test_runtime_events_material_notices.py b/tests/server/test_runtime_events_material_notices.py index 6fe98e12f..e14885e0c 100644 --- a/tests/server/test_runtime_events_material_notices.py +++ b/tests/server/test_runtime_events_material_notices.py @@ -1,6 +1,7 @@ """/api/v1/events 的物料失效:账本前进就推一条无 id 的 material.changed,不动工作流游标。 前端每个工站只维持这一条事件流(HTTP/1.1 连接数有限),物料失效与工作流、日志通知走同一条。 +通知列出这段账本里变了的物料,前端只重读这些;列不准时省略,前端整体重读。 """ from __future__ import annotations @@ -23,74 +24,164 @@ def subscribe(self, listener): return lambda: None +class _Ledger: + """最小物料权威:账本末尾、账本条目、Site → 所属物料。""" + + def __init__(self, tail: int, rows=(), sites=None): + self.tail = tail + self.rows = [SimpleNamespace(sequence=s, aggregate_type=t, aggregate_uuid=u) for s, t, u in rows] + self.sites = dict(sites or {}) + + def latest_ledger_sequence(self) -> int: + return self.tail + + def changes(self, *, after_sequence: int = 0, limit: int = 100): + return [row for row in self.rows if row.sequence > after_sequence][:limit] + + def get_site(self, site_uuid: str, *, include_deleted: bool = False): + owner = self.sites.get(site_uuid) + return SimpleNamespace(owner_material_uuid=owner) if owner else None + + def _quiet(monkeypatch): monkeypatch.setattr(events, "log_notices", _NoLogNotices()) monkeypatch.setattr(events, "shutting_down", lambda: False) -def test_ledger_advance_emits_one_idless_material_changed(monkeypatch): - _quiet(monkeypatch) +def _workflow(events_window=None): workflow = Mock() - workflow.read_event_window.return_value = (1, 41, []) + workflow.read_event_window.return_value = events_window or (1, 41, []) + return workflow + +def _first_frame(materials, cursor: int, workflow=None) -> str: async def scenario(): stream = events.runtime_event_stream( - _Request(), workflow, cursor=41, material_sequence=lambda: 7, material_cursor=5 + _Request(), workflow or _workflow(), cursor=41, + materials=events.MaterialNotices(materials), material_cursor=cursor, ) assert "connected" in await anext(stream) frame = await asyncio.wait_for(anext(stream), 2) - assert frame.startswith("event: material.changed\n") - assert "id:" not in frame - assert json.loads(frame.split("data: ")[1]) == {"sequence": 7} await stream.aclose() + return frame - asyncio.run(scenario()) + return asyncio.run(scenario()) -def test_unchanged_ledger_sends_nothing_before_workflow_events(monkeypatch): +def _data(frame: str) -> dict: + return json.loads(frame.split("data: ")[1]) + + +def test_ledger_advance_lists_the_changed_materials_without_an_id(monkeypatch): _quiet(monkeypatch) - workflow = Mock() - workflow.read_event_window.return_value = (1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}]) + ledger = _Ledger( + 7, + rows=[(5, "material", "old"), (6, "site", "site-1"), (6, "material", "plate"), (7, "lot", "lot-1"), (7, "material", "plate")], + sites={"site-1": "deck"}, + ) + frame = _first_frame(ledger, cursor=5) + assert frame.startswith("event: material.changed\n") + assert "id:" not in frame # 不占工作流游标 + # 区间 (5, 7]:Site 归到所属台面,批次不进物料图,重复的物料去重 + assert _data(frame) == {"sequence": 7, "material_uuids": ["deck", "plate"]} + + +def test_template_change_asks_for_a_full_reload(monkeypatch): + _quiet(monkeypatch) + ledger = _Ledger(9, rows=[(8, "material", "plate"), (9, "resource_template", "tpl")]) + assert _data(_first_frame(ledger, cursor=7)) == {"sequence": 9} - async def scenario(): - stream = events.runtime_event_stream( - _Request(), workflow, cursor=41, material_sequence=lambda: 7, material_cursor=7 - ) - assert "connected" in await anext(stream) - frame = await asyncio.wait_for(anext(stream), 2) - assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") - await stream.aclose() - asyncio.run(scenario()) +def test_ledger_reset_asks_for_a_full_reload(monkeypatch): + _quiet(monkeypatch) + # 库被重置:末尾比基线小,列不准 + assert _data(_first_frame(_Ledger(2), cursor=40)) == {"sequence": 2} -def test_ledger_read_failure_does_not_break_the_workflow_stream(monkeypatch): +def test_unchanged_ledger_sends_nothing_before_workflow_events(monkeypatch): _quiet(monkeypatch) - workflow = Mock() - workflow.read_event_window.return_value = (1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}]) + workflow = _workflow((1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}])) + frame = _first_frame(_Ledger(7), cursor=7, workflow=workflow) + assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") - def broken(): - raise RuntimeError("materials.db is locked") - async def scenario(): - stream = events.runtime_event_stream( - _Request(), workflow, cursor=41, material_sequence=broken, material_cursor=3 +def test_ledger_read_failure_does_not_break_the_workflow_stream(monkeypatch): + _quiet(monkeypatch) + + class Broken(_Ledger): + def latest_ledger_sequence(self) -> int: + raise RuntimeError("materials.db is locked") + + workflow = _workflow((1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}])) + frame = _first_frame(Broken(0), cursor=3, workflow=workflow) + assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") + + +def test_real_authority_names_the_placed_material_and_the_site_owner(tmp_path): + from uuid import uuid4 + + from unilabos.client.materials import LocalMaterialsClient + from unilabos.protocol.materials import ( + InventoryMutation, + MaterialIdentityWrite, + MaterialNodeCreate, + MaterialPlacement, + MaterialTreeCreate, + ResourceTemplateWrite, + ) + from unilabos.resources.adapters.device_site import apply_device_authority_state + from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance + from unilabos.server.services.materials import MaterialsService + + def mutation(operation: str) -> InventoryMutation: + command = str(uuid4()) + return InventoryMutation( + command_uuid=command, effect_key=f"{operation}:{command}", operation=operation, + actor_type="test", actor_uuid="material-notices", ) - assert "connected" in await anext(stream) - frame = await asyncio.wait_for(anext(stream), 2) - assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") - await stream.aclose() - asyncio.run(scenario()) + service = MaterialsService(tmp_path / "materials.db") + try: + service.put_template( + mutation("put_template"), ResourceTemplateWrite(name="sample_tpl", display_name="sample", class_name="Resource") + ) + device_uuid = str(uuid4()) + device = ResourceDictInstance(ResourceDict.model_validate({ + "id": "notice-device", "uuid": device_uuid, "name": "notice-device", "type": "device", + "class": "notice_device", "template_name": "notice_device", "config": {}, "data": {}, "extra": {}, + "sites": None, "sites_initialized": False, + })) + apply_device_authority_state( + device, {"available_sites": [{"index": 1, "label": "s1"}]}, "notice_device", + gateway=LocalMaterialsClient(service), + ) + [site] = service.get_material(device_uuid).sites + notices = events.MaterialNotices(service) + before = notices.latest() + + created = service.create_tree( + mutation("create_material_tree"), + MaterialTreeCreate( + nodes=[MaterialNodeCreate(client_ref="sample", identity=MaterialIdentityWrite( + resource_id=f"sample-{uuid4().hex[:8]}", template_name="sample_tpl", config={"type": "Container"}, + ))], + placement=MaterialPlacement(parent_material_uuid=device_uuid, site=site.site_uuid), + ), + ) + sample_uuid = created.data.root_material_uuid + after = notices.latest() + assert after > before + assert set(notices.changed_materials(before, after)) == {sample_uuid, device_uuid} + finally: + service.close() -def test_reader_exists_only_where_the_materials_authority_lives(monkeypatch): +def test_notices_exist_only_where_the_materials_authority_lives(monkeypatch): from unilabos.server import execution_composition monkeypatch.setattr(execution_composition, "get_materials_service", lambda: None) - assert events.material_sequence_reader() is None + assert events.material_notices() is None - authority = SimpleNamespace(latest_ledger_sequence=lambda: 12) - monkeypatch.setattr(execution_composition, "get_materials_service", lambda: authority) - reader = events.material_sequence_reader() - assert reader is not None and reader() == 12 + monkeypatch.setattr(execution_composition, "get_materials_service", lambda: _Ledger(12)) + notices = events.material_notices() + assert notices is not None and notices.latest() == 12 diff --git a/unilabos/server/api/runtime/events.py b/unilabos/server/api/runtime/events.py index aad39bf18..c2c15148e 100644 --- a/unilabos/server/api/runtime/events.py +++ b/unilabos/server/api/runtime/events.py @@ -21,9 +21,10 @@ ``graph_saved`` / ``published``),都与变更同一事务写入。游标与 ``stream.reset`` 协议不变。 物料失效:本进程持有物料权威时,物料账本前进就推一条**不带 id** 的 ``material.changed`` -(``data: {"sequence": <账本末尾序号>}``),与日志通知一样不动工作流游标。只维持这一条事件流的 -前端据此重读物料;要按账本 sequence 续传、按 aggregate 精确失效的客户端仍用 -``/api/v1/materials/events``(``materials.changed``)。 +(``data: {"sequence": <账本末尾序号>, "material_uuids": [...]}``),与日志通知一样不动工作流游标。 +``material_uuids`` 是这段账本里变了的物料(Site 的变化归到所属物料);列不准时(条目过多、模板变化、 +库被重置)省略它,表示整体重读。只维持这一条事件流的前端据此重读物料;要按账本 sequence 续传的 +客户端仍用 ``/api/v1/materials/events``(``materials.changed``)。 """ from __future__ import annotations @@ -31,7 +32,6 @@ import asyncio import json import time -from collections.abc import Callable from typing import Any, Dict @@ -74,28 +74,80 @@ def to_v1_event(event: Dict[str, Any]) -> Dict[str, Any]: return {**event, "event": name, "data": data} -def material_sequence_reader() -> Callable[[], int] | None: - """本进程持有物料权威时返回"账本末尾序号"读取函数;Host 子进程等没有权威的进程返回 None。""" +#: 一次通知最多列出的账本条目;超过就不列物料,让客户端整体重读 +MATERIAL_NOTICE_WINDOW = 500 + + +class MaterialNotices: + """本进程物料权威的账本视图:末尾序号,以及一段区间里哪些物料变了。""" + + def __init__(self, service: Any): + self._service = service + + def latest(self) -> int: + return int(self._service.latest_ledger_sequence()) + + def changed_materials(self, after: int, upto: int) -> list[str] | None: + """``(after, upto]`` 里变了的物料 uuid(Site 的变化归到它的所属物料)。 + + 返回 None 表示列不准(条目超过窗口、模板变了),客户端应整体重读。 + """ + + rows = self._service.changes(after_sequence=after, limit=MATERIAL_NOTICE_WINDOW + 1) + rows = [row for row in rows if row.sequence <= upto] + if len(rows) > MATERIAL_NOTICE_WINDOW: + return None + changed: set[str] = set() + for row in rows: + if row.aggregate_type == "material": + changed.add(row.aggregate_uuid) + elif row.aggregate_type == "site": + site = self._service.get_site(row.aggregate_uuid, include_deleted=True) + if site is not None: + changed.add(site.owner_material_uuid) + elif row.aggregate_type == "resource_template": + # 模板变化可能改变很多物料的展示,不逐个列 + return None + return sorted(changed) + + +def material_notices() -> MaterialNotices | None: + """本进程持有物料权威时返回账本视图;Host 子进程等没有权威的进程返回 None。""" try: from unilabos.server.execution_composition import get_materials_service except ImportError: return None - reader = getattr(get_materials_service(), "latest_ledger_sequence", None) - return reader if callable(reader) else None + service = get_materials_service() + if service is None or not callable(getattr(service, "latest_ledger_sequence", None)): + return None + return MaterialNotices(service) -def _read_material_sequence(reader: Callable[[], int], fallback: int) -> int: +def _latest_material_sequence(materials: MaterialNotices, fallback: int) -> int: try: - return int(reader()) + return materials.latest() except Exception: # noqa: BLE001 - 读不到账本只是这一轮不发失效,不能断开工作流事件流 return fallback -def material_changed_frame(sequence: int) -> str: - """不写 SSE id:Last-Event-ID 只表示工作流持久事件的序号。""" +def _changed_materials(materials: MaterialNotices, after: int, upto: int) -> list[str] | None: + try: + return materials.changed_materials(after, upto) + except Exception: # noqa: BLE001 - 列不出来就让客户端整体重读 + return None + + +def material_changed_frame(sequence: int, material_uuids: list[str] | None = None) -> str: + """不写 SSE id:Last-Event-ID 只表示工作流持久事件的序号。 + + ``material_uuids`` 缺省表示"列不准,整体重读";给出时客户端只重读这些物料。 + """ - data = json.dumps({"sequence": sequence}, separators=(",", ":")) + payload: Dict[str, Any] = {"sequence": sequence} + if material_uuids is not None: + payload["material_uuids"] = material_uuids + data = json.dumps(payload, separators=(",", ":")) return f"event: {MATERIAL_CHANGED_EVENT}\ndata: {data}\n\n" @@ -106,7 +158,7 @@ async def runtime_event_stream( *, watermark: bool = False, replay: bool = False, - material_sequence: Callable[[], int] | None = None, + materials: MaterialNotices | None = None, material_cursor: int = 0, ): from unilabos.server.api.runtime.workflow import format_sse_event @@ -138,12 +190,17 @@ def receive(notice: RuntimeLogNotice): now = time.monotonic() if now >= next_workflow: next_workflow = now + 1 - if material_sequence is not None: - # 账本末尾变了(前进,或库被重置后变小)就发一次失效;只比较末尾,不回放账本。 - latest_material = _read_material_sequence(material_sequence, material_cursor) + if materials is not None: + # 账本末尾变了就发一次失效,列出这段区间里变了的物料;库被重置(末尾变小)时不列,整体重读。 + latest_material = _latest_material_sequence(materials, material_cursor) if latest_material != material_cursor: + changed = ( + _changed_materials(materials, material_cursor, latest_material) + if latest_material > material_cursor + else None + ) material_cursor = latest_material - yield material_changed_frame(latest_material) + yield material_changed_frame(latest_material, changed) if service is not None: oldest, latest, events = service.read_event_window(after_id=cursor, limit=101) reason = None @@ -206,8 +263,8 @@ async def events( # “快照 → 订阅”之间的变化。纯执行面的 Host 没有 Workflow Authority。 cursor = service.latest_event_sequence() if service is not None else 0 # 物料账本基线同样在响应头之前固定:onopen 后的 REST 补读覆盖此前的物料变化。 - material_sequence = material_sequence_reader() - material_cursor = _read_material_sequence(material_sequence, 0) if material_sequence is not None else 0 + materials = material_notices() + material_cursor = _latest_material_sequence(materials, 0) if materials is not None else 0 return StreamingResponse( runtime_event_stream( request, @@ -215,7 +272,7 @@ async def events( cursor, watermark=fresh and service is not None, replay=bool(value) and cursor == 0, - material_sequence=material_sequence, + materials=materials, material_cursor=material_cursor, ), media_type="text/event-stream", From 175577373c91837d214d14363958cc18b9e7be43 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:42:15 +0800 Subject: [PATCH 15/59] feat(materials): V1 material records carry inventory facts and honor the V1 filters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The frontend decides what a material is and whether it can be picked from inventory_status / inventory_presence / disposition. The V1 records only had lifecycle_status, so every material read 状态未知 and the material picker refused them all. It also sends V1 filters that the list and graph endpoints ignored. Inventory facts, derived from the lifecycle (V1 InstanceState words): - active -> warehouse, reserved -> reserved, in_use -> in_use, quarantined -> quarantined, consumed -> consumed, retired -> used. - Presence is always current: this backend has no station departure. - Disposition is active, or discarded once soft-deleted. - Devices are not inventory and get null facts. - Only warehouse (active) can be reserved by a new task, which is the same rule _select_inventory_material applies to an explicit material. Filters: - GET /materials: category=material|device by resource type; inventory_scope=current|history, where history is empty because nothing departs; empty_containers_only=true keeps materials with no content registration (a zero-quantity one still counts). Unknown values are a 1000. - GET /materials/graph: inventory_scope, and repeated material_uuid for an incremental reread. It returns those materials plus the owners of their current Sites, so current_site_uuid resolves in the same response, and only links between returned nodes. Deleted or unknown ids are absent, which the client reads as removed. --- tests/server/test_v1_resource_contract.py | 75 +++++++++++ unilabos/server/api/materials/resources.py | 14 +- .../services/materials/resource_contract.py | 121 +++++++++++++++++- 3 files changed, 202 insertions(+), 8 deletions(-) diff --git a/tests/server/test_v1_resource_contract.py b/tests/server/test_v1_resource_contract.py index 5fd489a52..aef237c09 100644 --- a/tests/server/test_v1_resource_contract.py +++ b/tests/server/test_v1_resource_contract.py @@ -172,6 +172,81 @@ def test_material_create_place_update_ledger_and_delete(client) -> None: error_of(client.get(f"/api/v1/materials/{bottle['uuid']}"), 6000) +def test_v1_material_records_carry_inventory_facts(client) -> None: + """V1 物料 DTO 带 inventory_status / inventory_presence / disposition,由生命周期派生。""" + + from unilabos.server.services.materials.resource_contract import inventory_facts + + identities = _templates(client) + bottle = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-1"}), status=201) + in_stock = {"inventory_status": "warehouse", "inventory_presence": "current", "disposition": "active"} + assert {key: bottle[key] for key in in_stock} == in_stock + listed = ok_data(client.get("/api/v1/materials"))["items"][0] + assert {key: listed[key] for key in in_stock} == in_stock + node = ok_data(client.get("/api/v1/materials/graph"))["nodes"][0]["material"] + assert {key: node[key] for key in in_stock} == in_stock + + # 只有在库(active)能被新任务预留;设备不是库存物料;软删记为废弃 + assert inventory_facts("plate", "reserved", None)["inventory_status"] == "reserved" + assert inventory_facts("plate", "in_use", None)["inventory_status"] == "in_use" + assert inventory_facts("plate", "quarantined", None)["inventory_status"] == "quarantined" + assert inventory_facts("plate", "consumed", None)["inventory_status"] == "consumed" + assert inventory_facts("plate", "retired", None)["inventory_status"] == "used" + assert inventory_facts("device", "active", None) == { + "inventory_status": None, "inventory_presence": None, "disposition": None, + } + assert inventory_facts("plate", "retired", 123)["disposition"] == "discarded" + + +def test_material_list_filters_by_category_scope_and_empty_containers(client) -> None: + identities = _templates(client) + empty = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "空瓶"}), status=201) + filled = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "样品瓶"}), status=201) + ok_data(client.post("/api/v1/samples", json={ + "material_uuid": filled["uuid"], "code": "S-01", "name": "血清", "quantity": 0, "quantity_unit": "ml"}), status=201) + + def uuids(**params) -> set[str]: + return {item["uuid"] for item in ok_data(client.get("/api/v1/materials", params=params))["items"]} + + assert uuids(category="material") == {empty["uuid"], filled["uuid"]} + assert uuids(category="device") == set() + # 数量为 0 的有效登记仍算非空 + assert uuids(empty_containers_only="true") == {empty["uuid"]} + history = ok_data(client.get("/api/v1/materials", params={"inventory_scope": "history"})) + assert history["items"] == [] and history["total"] == 0 + assert uuids(inventory_scope="current") == {empty["uuid"], filled["uuid"]} + error_of(client.get("/api/v1/materials", params={"inventory_scope": "bogus"}), 1000) + error_of(client.get("/api/v1/materials", params={"category": "bogus"}), 1000) + + +def test_material_graph_rereads_only_the_named_materials_and_their_site_owners(client) -> None: + identities = _templates(client) + rack = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["tube_rack_2"], "name": "架-1"}), status=201) + bottle = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-1", + "site_placement": {"action": "place", "site_uuid": rack["site_uuids"][0]}, + }), status=201) + ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "旁边的瓶"}), status=201) + + def graph(**params) -> dict: + return ok_data(client.get("/api/v1/materials/graph", params=params)) + + assert len(graph()["nodes"]) == 3 + # 瓶在架的库位上:客户端要在同一响应里解析 current_site_uuid,架也一起回来 + partial = graph(material_uuid=[bottle["uuid"]]) + assert {node["material"]["uuid"] for node in partial["nodes"]} == {bottle["uuid"], rack["uuid"]} + assert all(link["source_uuid"] in {bottle["uuid"], rack["uuid"]} for link in partial["links"]) + # 不存在 / 已删除的物料不返回:客户端据此从图里移除 + assert graph(material_uuid=["00000000-0000-4000-8000-000000000000"])["nodes"] == [] + assert graph(inventory_scope="history") == {"nodes": [], "links": []} + error_of(client.get("/api/v1/materials/graph", params={"inventory_scope": "bogus"}), 1000) + + def test_literal_dev_routes_are_not_captured_by_material_uuid_route(client) -> None: # dev 独有的字面量路由先于 V1 的 /materials/{material_uuid} 注册 assert isinstance(ok_data(client.get("/api/v1/materials/registry-classes")), list) diff --git a/unilabos/server/api/materials/resources.py b/unilabos/server/api/materials/resources.py index 9960811cd..98d2373ca 100644 --- a/unilabos/server/api/materials/resources.py +++ b/unilabos/server/api/materials/resources.py @@ -231,9 +231,14 @@ def list_materials( name: str = Query(default=""), barcode: str = Query(default=""), resource_template_uuid: Optional[str] = Query(default=None), + category: Optional[str] = Query(default=None, description="material = 非设备物料;device = 设备"), + inventory_scope: str = Query(default="current", description="current | history(离站物料,本后端恒为空)"), + empty_containers_only: bool = Query(default=False, description="只要没有任何内容登记的物料"), ) -> Any: return contract.list_materials(page=page, page_size=page_size, name=name, barcode=barcode, - resource_template_uuid=resource_template_uuid or None) + resource_template_uuid=resource_template_uuid or None, + category=category or None, inventory_scope=inventory_scope, + empty_containers_only=empty_containers_only) @router.get("/resources") def list_resources(page: int = Query(default=0), page_size: int = Query(default=0)) -> Any: @@ -242,8 +247,11 @@ def list_resources(page: int = Query(default=0), page_size: int = Query(default= return contract.list_resources(page=page, page_size=page_size) @router.get("/materials/graph") - def material_graph() -> Any: - return contract.material_graph() + def material_graph( + inventory_scope: str = Query(default="current", description="current | history(本后端恒为空)"), + material_uuid: list[str] = Query(default=[], description="增量重读:只要这些物料(连同库位所属祖先)"), + ) -> Any: + return contract.material_graph(inventory_scope=inventory_scope, material_uuids=material_uuid) @router.post("/materials/sites/resolve-identities") def resolve_site_identities(body: SiteIdentityResolveRequest) -> Any: diff --git a/unilabos/server/services/materials/resource_contract.py b/unilabos/server/services/materials/resource_contract.py index 73d5ff85b..c97e01e36 100644 --- a/unilabos/server/services/materials/resource_contract.py +++ b/unilabos/server/services/materials/resource_contract.py @@ -42,6 +42,48 @@ _HANDLE_NAMESPACE = uuid5(NAMESPACE_URL, "unilabos://resource-template-handles") _NIL_UUID = "00000000-0000-0000-0000-000000000000" +#: V1 ``inventory_scope``:current = 仍在本站;history = 已物理离站(Uni-Lab-OS 没有离站概念,恒为空) +INVENTORY_SCOPE_CURRENT = "current" +INVENTORY_SCOPE_HISTORY = "history" +INVENTORY_SCOPES = (INVENTORY_SCOPE_CURRENT, INVENTORY_SCOPE_HISTORY) + +#: 物料生命周期 → V1 ``inventory_status``(V1 InstanceState 词表;退役记为已使用,同 ``material.mark_used``) +_V1_INVENTORY_STATUS = { + "active": "warehouse", + "reserved": "reserved", + "in_use": "in_use", + "quarantined": "quarantined", + "consumed": "consumed", + "retired": "used", +} + + +def _check_inventory_scope(scope: str) -> None: + if scope not in INVENTORY_SCOPES: + raise MaterialValidationError("inventory_scope must be current or history") + + +def inventory_facts( + resource_type: str, lifecycle_status: str, deleted_at_ms: Optional[int] +) -> dict[str, Optional[str]]: + """V1 物料 DTO 的库存事实:``inventory_status`` / ``inventory_presence`` / ``disposition``。 + + - 设备不是库存物料:三项都为 null; + - 在册物料 ``inventory_presence`` 恒为 ``current``(没有离站),``disposition`` 为 ``active``; + 只有 ``warehouse``(生命周期 active)能被新任务预留,与 ``_select_inventory_material`` 一致; + - 已删除(软删)物料 ``disposition`` 为 ``discarded``。 + """ + + if resource_type == "device": + return {"inventory_status": None, "inventory_presence": None, "disposition": None} + if deleted_at_ms is not None: + return {"inventory_status": "discarded", "inventory_presence": "current", "disposition": "discarded"} + return { + "inventory_status": _V1_INVENTORY_STATUS.get(lifecycle_status, lifecycle_status), + "inventory_presence": "current", + "disposition": "active", + } + def new_mutation(operation: str, *, actor_type: str = ACTOR_HUMAN, actor_uuid: Optional[str] = None, payload: Optional[Mapping[str, Any]] = None) -> InventoryMutation: @@ -390,6 +432,7 @@ def _capacity(self, config: Mapping[str, Any], template: Optional[ResourceTempla def material_row(self, aggregate: Any, *, template: Optional[ResourceTemplateRead] = None) -> dict[str, Any]: material = aggregate.material + facts = inventory_facts(material.resource_type, material.lifecycle_status, material.deleted_at_ms) template = template or self._template_meta(material.template_uuid) result: dict[str, Any] = { "uuid": material.material_uuid, @@ -406,6 +449,7 @@ def material_row(self, aggregate: Any, *, template: Optional[ResourceTemplateRea "config": dict(material.config), "data": dict(aggregate.data.data), "revision": material.version, + **facts, # dev 超集 "resource_id": material.resource_id, "display_name": material.display_name, @@ -438,11 +482,29 @@ def material_detail(self, material_uuid: str) -> dict[str, Any]: def list_materials( self, *, page: int, page_size: int, name: str = "", barcode: str = "", resource_template_uuid: Optional[str] = None, + category: Optional[str] = None, + inventory_scope: str = INVENTORY_SCOPE_CURRENT, + empty_containers_only: bool = False, ) -> dict[str, Any]: page = max(page, 1) page_size = 20 if page_size <= 0 else min(page_size, 100) + _check_inventory_scope(inventory_scope) + if inventory_scope == INVENTORY_SCOPE_HISTORY: + # 历史范围是已物理离站的物料;Uni-Lab-OS 没有离站概念,恒为空 + return {"items": [], "total": 0, "page": page, "page_size": page_size, "has_more": False} where = ["deleted_at_ms IS NULL"] params: list[Any] = [] + if category == "device": + where.append("resource_type = 'device'") + elif category == "material": + where.append("resource_type <> 'device'") + elif category: + raise MaterialValidationError("category must be material or device") + if empty_containers_only: + # 没有任何内容登记(试剂 / 样品 / 当前内容物);数量为 0 的有效登记仍算非空 + where.append( + "NOT EXISTS (SELECT 1 FROM material_content c WHERE c.material_uuid = material.material_uuid)" + ) if name: # V1 的 name 筛选按人读标签匹配 where.append("display_name LIKE ?") @@ -911,13 +973,59 @@ def latest_material_state(self, material_uuid: str) -> dict[str, Any]: # -- 物料图 ---------------------------------------------------- - def material_graph(self) -> dict[str, Any]: - """V1 ``GET /materials/graph``:全部活动物料 + 相对位置 + 库位 + 模板摘要 + handle。""" + def _graph_closure(self, material_uuids: Sequence[str]) -> list[str]: + """请求的物料 + 沿"当前库位的所属物料"补齐的祖先(客户端按同一响应解析 current_site_uuid)。 + + 已删除或不存在的物料不返回:客户端把响应里缺的 uuid 当作已删除 / 离站。 + """ connection = self.materials.connection - rows = connection.execute( - "SELECT material_uuid FROM material WHERE deleted_at_ms IS NULL ORDER BY created_at_ms, material_uuid" - ).fetchall() + selected: list[str] = [] + seen: set[str] = set() + queue = list(dict.fromkeys(str(uuid) for uuid in material_uuids if str(uuid or "").strip())) + while queue: + uuid = queue.pop(0) + if uuid in seen: + continue + seen.add(uuid) + alive = connection.execute( + "SELECT 1 FROM material WHERE material_uuid=? AND deleted_at_ms IS NULL", (uuid,) + ).fetchone() + if alive is None: + continue + selected.append(uuid) + site = self.materials.occupied_site(uuid) + if site is not None and site.owner_material_uuid not in seen: + queue.append(site.owner_material_uuid) + return selected + + def material_graph( + self, + *, + inventory_scope: str = INVENTORY_SCOPE_CURRENT, + material_uuids: Sequence[str] = (), + ) -> dict[str, Any]: + """V1 ``GET /materials/graph``:活动物料 + 相对位置 + 库位 + 模板摘要 + handle。 + + 给了 ``material_uuids`` 是增量重读:只返回这些物料及其库位所属祖先,连线只留两端都在其中的。 + """ + + _check_inventory_scope(inventory_scope) + if inventory_scope == INVENTORY_SCOPE_HISTORY: + return {"nodes": [], "links": []} + connection = self.materials.connection + if material_uuids: + wanted = self._graph_closure(material_uuids) + placeholders = ",".join("?" for _ in wanted) + rows = connection.execute( + f"SELECT material_uuid FROM material WHERE material_uuid IN ({placeholders}) " + "ORDER BY created_at_ms, material_uuid", + tuple(wanted), + ).fetchall() if wanted else [] + else: + rows = connection.execute( + "SELECT material_uuid FROM material WHERE deleted_at_ms IS NULL ORDER BY created_at_ms, material_uuid" + ).fetchall() templates: dict[str, Optional[ResourceTemplateRead]] = {} nodes = [] for row in rows: @@ -948,6 +1056,9 @@ def material_graph(self) -> dict[str, Any]: } for link in self.materials.list_links() ] + if material_uuids: + returned = {node["material"]["uuid"] for node in nodes} + links = [link for link in links if link["source_uuid"] in returned and link["target_uuid"] in returned] return {"nodes": nodes, "links": links} From d53b74ed4ecd96cadbe67a02ecedab114ff5e8a1 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:57:12 +0800 Subject: [PATCH 16/59] fix(inventory): reject malformed typed-command payloads with 1000 Typed inventory command handlers parse their payload in place: dict(), int(), float() and pydantic model construction. A payload of the wrong shape (spec as a string, node_requirements as a list, a non-numeric count, a payload that is not an object) raised ValueError or TypeError. That escaped as a bare HTTP 500 with no envelope and left no processed-command record, so a retry ran the handler again. Such errors are now rejected like any other invalid parameter: a failure envelope with code 1000, recorded and replayed under the same command_id. --- tests/server/test_v1_inventory_api.py | 29 +++++++++++++++++++ .../services/materials/inventory_commands.py | 12 ++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/tests/server/test_v1_inventory_api.py b/tests/server/test_v1_inventory_api.py index 4bced5854..9e2117c3f 100644 --- a/tests/server/test_v1_inventory_api.py +++ b/tests/server/test_v1_inventory_api.py @@ -108,6 +108,35 @@ def test_command_entry_runs_materials_v1_mutations_idempotently(stack) -> None: error_of(client.get("/api/v1/inventory/instances/missing"), 6000) +@pytest.mark.parametrize( + ("command_type", "payload"), + [ + ("inventory.template.upsert", {"template_id": "probe", "spec": "not-an-object"}), + ("inventory.reserve", {"workflow_id": "wf-1", "node_requirements": [{"quantity": "lots"}]}), + ("inventory.reconcile_count", {"lot_id": "lot-x", "measured_count": "many"}), + ("material.move", [1, 2]), + ], +) +def test_typed_command_with_malformed_payload_is_a_recorded_rejection(stack, command_type, payload) -> None: + """载荷字段类型不对(处理器里 dict() / int() / pydantic 校验失败)是参数错误:失败信封 1000、记账可重放, + 不是不带信封的 500。""" + + _service, client = stack + if command_type == "inventory.reconcile_count": + template = ResourceTemplateWrite(template_uuid="tip-template", name="tip", resource_type="consumable", class_name="Tip") + assert command_body(client.post("/api/v1/inventory/commands", json=_command("put_template", template)))["status"] == "completed" + lot = InventoryLotInbound(lot_uuid="lot-x", template_uuid="tip-template", unit="count", quantity=5) + assert command_body(client.post("/api/v1/inventory/commands", json=_command("inbound_inventory_lot", lot)))["status"] == "completed" + body = {"command_id": f"bad-{command_type}", "type": command_type, "payload": payload} + first = command_body(client.post("/api/v1/inventory/commands", json=body)) + assert first["status"] == "rejected" and first["code"] == 1000 and first["replayed"] is False, first + assert first["error_code"] == "invalid_material" + replay = command_body(client.post("/api/v1/inventory/commands", json=body)) + assert replay["status"] == "rejected" and replay["code"] == 1000 and replay["replayed"] is True + processed = ok_data(client.get("/api/v1/inventory/commands/processed"))["commands"] + assert [item["status"] for item in processed if item["command_id"] == body["command_id"]] == ["rejected"] + + def test_typed_lot_commands_inbound_correct_reconcile_and_reads(stack) -> None: service, client = stack _seed(client) diff --git a/unilabos/server/services/materials/inventory_commands.py b/unilabos/server/services/materials/inventory_commands.py index 4a4010ad8..0d7ad78a5 100644 --- a/unilabos/server/services/materials/inventory_commands.py +++ b/unilabos/server/services/materials/inventory_commands.py @@ -227,8 +227,16 @@ def typed_command(self, body: Mapping[str, Any], code_of: CodeOf) -> dict[str, A return self._replay(existing) if handler is None: raise UnsupportedCommand(f"unsupported inventory command type: {command_type}") - result = handler(dict(body.get("payload") or {}), command_id=command_id, actor=actor, - expected_version=body.get("expected_version")) + payload = body.get("payload") + if payload is not None and not isinstance(payload, Mapping): + raise MaterialValidationError("payload must be an object") + try: + result = handler(dict(payload or {}), command_id=command_id, actor=actor, + expected_version=body.get("expected_version")) + except (ValueError, TypeError) as exc: + # 处理器就地解析载荷(int() / float() / dict()、构造 pydantic 模型):字段类型不对是参数错误, + # 与业务拒绝一样记账并回 1000,不当未知异常变成不带信封的 500。 + raise MaterialValidationError(f"invalid {command_type} payload: {exc}") from exc connection.execute( "INSERT INTO inventory_processed_command(command_id, command_type, request_hash, status, result_json, " "actor, processed_at_ms) VALUES (?,?,?,'completed',?,?,?)", From ae82295c0d989b5638446abe2bf67790102d6533 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:15:15 +0800 Subject: [PATCH 17/59] docs(materials): document MaterialTreeCreate's tree-level placement A tree create can place its root on a site of its parent in the same transaction. Clients that build payloads by hand must still send `placement: null`, because the command entry compares the payload with the full typed dump. OpenLabSite's createTree is synced to this. --- docs/developer_guide/interfaces/materials.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/developer_guide/interfaces/materials.md b/docs/developer_guide/interfaces/materials.md index 142bfa20c..858b35dd3 100644 --- a/docs/developer_guide/interfaces/materials.md +++ b/docs/developer_guide/interfaces/materials.md @@ -56,6 +56,10 @@ Site 的 category 匹配由画布提示/拦截;权威仍校验身份、父子 2. `POST /trees`:payload 为 `MaterialTreeCreate`。适合驱动/图同步提交已经序列化的完整草稿。 `nodes` 必须非空、仅一个根、父节点在前、`client_ref` 唯一。 Site 初始占用用 `occupied_client_ref` 引用树内节点,不携带自行分配的 site_uuid。 + 可选的树级 `placement`(`MaterialPlacement`:`parent_material_uuid` + 可选 `site`,即父物料上的 Site uuid、 + label 或数字索引)让根物料在建树的同一事务里落到父物料的库位上。落位规则与 move 相同(库位占用、模板类别、 + 入口预留、环检测、设备子树只收 PLR 物料),不满足时整棵树一起回滚。命令入口按完整 dump 比对 payload, + 不落位也要显式带 `placement: null`。 `MaterialNodeCreate.material_uuid` 默认不填,由权威分配;开机图等需保留外部身份的场景可显式填写, 这表示**有条件创建**,不是覆盖已存在同 UUID 的记录。 From 6f371ddbb57b3f969e533807c796f2596ceb3f28 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:22:32 +0800 Subject: [PATCH 18/59] fix(host): assign onto a device Site moves in the authority first and detaches locally materials.assign(node, material, slot=/site=) onto one of the device's own Sites had three defects: - A material nested under a local PLR parent stayed under it locally, while the authority moved it onto the device Site. From then on every strict snapshot of the old parent's tree was refused with "runtime tree contains material UUIDs outside downloaded tree", and that tree stopped syncing. - The local mount happened before the authority move. When the authority refused (occupied Site, category, ingress reservation, PLR-only device subtree), the material stayed mounted as a device root that the authority never placed. - A Site uuid passed as `site` was trusted without checking it is one of this device's Sites. A Site of another device put the material under that device in the authority while it was mounted here. The selector, uuid or label, now goes through the same match against the device's own Sites. The authority move runs right after the commit point, before anything local changes. Only then is the material detached from its local PLR parent and registered as a device root. The old parent's tree, now one child short, is reported in the same snapshot step. ResourceTracker.add_resource drops a stale parent index entry when a former child is registered as a root. --- .../test_materials_create_and_place.py | 60 +++++++++++++++++++ unilabos/client/host/runtime/node.py | 43 +++++++++---- unilabos/resources/resource_tracker.py | 2 + 3 files changed, 92 insertions(+), 13 deletions(-) diff --git a/tests/resources/test_materials_create_and_place.py b/tests/resources/test_materials_create_and_place.py index b0b6a67e8..4f14df644 100644 --- a/tests/resources/test_materials_create_and_place.py +++ b/tests/resources/test_materials_create_and_place.py @@ -222,3 +222,63 @@ def test_assign_puts_at_most_one_material_on_a_site(device) -> None: with pytest.raises(ValueError, match="一个库位只能放一个物料"): materials.assign(device["node"], [first, second], slot="slot_a") + + +def test_assign_onto_an_occupied_device_site_leaves_nothing_mounted(device) -> None: + """权威拒绝(库位被占)时本地还没动:物料不进设备 tracker,权威父物料不变。""" + + service, node, gateway = device["service"], device["node"], device["gateway"] + first = materials.create(plate("first"), node=node, site="slot_a", gateway=gateway) + loose = materials.create(plate("loose"), gateway=gateway) + + with pytest.raises(Exception, match="occupied"): + materials.assign(node, loose, slot="slot_a") + + assert loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources + assert [res.name for res in node.resource_tracker.resources] == ["first"] + assert service.get_material(loose.unilabos_uuid).material.parent_material_uuid is None + assert _site(service, device["device_uuid"], "slot_a").occupied_material_uuid == first.unilabos_uuid + + +def test_assign_moves_a_nested_material_off_its_plr_parent_onto_a_device_site(device) -> None: + """本地 PLR 父物料下的孩子放到设备库位:本地也从原父物料卸下,原父树之后照常快照。""" + + from pylabrobot.resources import Coordinate, Resource + + service, node, gateway = device["service"], device["node"], device["gateway"] + holder = Resource("holder", size_x=200, size_y=200, size_z=10, category="container") + holder.assign_child_resource(plate("inner"), location=Coordinate(0, 0, 0)) + created = materials.create(holder, node=node, site="slot_a", gateway=gateway) + inner = next(child for child in created.children if child.name == "inner") + + materials.assign(node, inner, slot="slot_b") + + assert service.get_material(inner.unilabos_uuid).material.parent_material_uuid == device["device_uuid"] + assert _site(service, device["device_uuid"], "slot_b").occupied_material_uuid == inner.unilabos_uuid + assert inner.parent is None and created.children == [] + assert {res.name for res in node.resource_tracker.resources} == {"holder", "inner"} + assert node.resource_tracker.parent_resource(inner) is None + # 原父树与权威一致:严格快照不再因为「本地多一个孩子」被拒 + materials.update(node, created) + materials.update(node, inner) + + +def test_assign_rejects_another_devices_site_uuid(device) -> None: + """``site`` 给的 uuid 必须是本设备的库位;别的设备的 Site 不会被当成本设备的。""" + + service, node, gateway = device["service"], device["node"], device["gateway"] + other_uuid = str(uuid4()) + other = ResourceDictInstance(ResourceDict.model_validate({ + **_device_config(other_uuid).res_content.model_dump(by_alias=True), "id": "other", "name": "other", + })) + apply_device_authority_state(other, {"available_sites": [{"index": 1, "label": "o1"}]}, DEVICE_TEMPLATE, + gateway=gateway) + foreign = _site(service, other_uuid, "o1") + loose = materials.create(plate("wanderer"), gateway=gateway) + + with pytest.raises(ValueError, match="不存在"): + materials.assign(node, loose, site=foreign.site_uuid) + + assert loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources + assert service.get_material(loose.unilabos_uuid).material.parent_material_uuid is None + assert _site(service, other_uuid, "o1").occupied_material_uuid is None diff --git a/unilabos/client/host/runtime/node.py b/unilabos/client/host/runtime/node.py index 368ea4bc3..bb64ab15e 100644 --- a/unilabos/client/host/runtime/node.py +++ b/unilabos/client/host/runtime/node.py @@ -957,15 +957,28 @@ async def append_resource( parent_uuid = self.resource_tracker.figure_resource({"name": bind_parent_id}).unilabos_uuid device_site_uuid: Optional[str] = None if parent_uuid == self.resource_uuid and self.resource_uuid: - # 设备自身的库位在提交点之前解析:选择器无效时什么都不改 + # 设备自身的库位在提交点之前解析:选择器无效、或给的 Site uuid 不是本设备的库位时 + # 什么都不改(site 与 slot 走同一套匹配,别的设备的 Site 不会被当成本设备的) stage = "解析设备库位" - device_site_uuid = site_uuid or await self._device_site_uuid(additional_params.get("slot")) + device_site_uuid = await self._device_site_uuid( + site_uuid if site_uuid is not None else additional_params.get("slot") + ) if device_site_uuid is not None and len(resource_uuids) != 1: raise ValueError("一个库位只能放一个物料:指定设备库位时一次只能挂一个物料") drafts = tree_set.to_plr_resources() # 提交点:此后本地 PLR 挂载、权威 move 与快照回报必须一起走完 if commit_point is not None and not commit_point.enter(): raise TimeoutError("等待方已超时放弃,挂载未执行") + if device_site_uuid is not None: + # 设备库位先在权威落占用:库位被占、类别不符、入口预留、设备子树只收 PLR 物料都由 + # 权威校验。被拒时本地还没动,不会留下「本地已挂、权威没放」的物料。 + stage = "权威 move" + await self._require_resource_service().move_resource( + self.device_id, + self.resource_uuid, + resource_uuids[0], + destination_site_uuid=device_site_uuid, + ) stage = "本地挂载" plr_instances: List[Any] = [] added_instances: List[Any] = [] @@ -993,6 +1006,18 @@ async def append_resource( extra = getattr(plr_instance, "unilabos_extra", None) or {} extra[EXTRA_BOUND_DEVICE] = self._short_device_id() plr_instance.unilabos_extra = extra + old_parent = getattr(plr_instance, "parent", None) + if device_site_uuid is not None and old_parent is not None: + # 权威已把它放到设备库位、父物料是设备:本地也从原 PLR 父物料卸下, + # 作为本设备的根树登记。原父树少了这个孩子,随第 4 步一起快照。 + old_root = old_parent + while getattr(old_root, "parent", None) is not None: + old_root = old_root.parent + self.lab_logger().info(f"[AR:{tag}] 物料 {root_uuid} 从 {old_parent} 卸下,放到设备库位") + old_parent.unassign_child_resource(plr_instance) + self.resource_tracker.add_resource(plr_instance) + if all(id(old_root) != id(existing) for existing in report_roots): + report_roots.append(old_root) plr_instances.append(plr_instance) parent = self.transfer_to_new_resource(plr_instance, tree, dict(additional_params)) if parent is None and parent_uuid != self.resource_uuid: @@ -1026,18 +1051,10 @@ async def append_resource( report_tree_set, parent_uuid, material_uuid ), ) - elif self.resource_uuid: - # 设备自身的库位:给了 site/slot 就经权威 move 占用设备库位;否则只落父子关系 + elif self.resource_uuid and device_site_uuid is None: + # 挂到设备自身、没指定库位:只落父子关系(指定了库位的已在本地挂载前 move 过) for material_uuid in resource_uuids: - if device_site_uuid is None: - await self._attach_root_to_device(material_uuid) - continue - await self._require_resource_service().move_resource( - self.device_id, - self.resource_uuid, - material_uuid, - destination_site_uuid=device_site_uuid, - ) + await self._attach_root_to_device(material_uuid) # 4. 同步:挂载后的父树经 update_resource 直连权威(权威已有 create 记录,严禁 add) stage = "快照回报" for tree in report_tree_set.trees: diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index 727bfdde0..49c60ea30 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -2108,6 +2108,8 @@ def add_resource(self, resource: Any) -> None: logger.warning(f"资源{resource}已存在,旧资源: {duplicate}") self.resources.append(resource) self._index(resource) + # 登记成根树:它此前若是某棵树的孩子(已从 PLR 父物料卸下),父索引作废 + self._parents.pop(id(resource), None) observer = getattr(self, "_material_snapshot_observer", None) if observer is not None: observer.observe(resource) From 500f0f77d7919d933eedab5e7419a266b57f5f8d Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:25:39 +0800 Subject: [PATCH 19/59] fix(host): move legacy non-PLR materials out of device subtrees in the authority Device init prunes materials without config.type from the local tree, but left the authority untouched. That tree's node set then never matched the authority, so every strict snapshot of it was refused ("runtime tree does not match downloaded material UUID set"). The observer dropped them as drift, and all PLR state changes on that deck (volumes, tips) were lost until the legacy row was removed by hand. The pruned branch roots are now recorded on the device's tracker (legacy_material_uuids). When the node gets its resource service, it moves each one out of the device subtree in the authority, making it an independent root and freeing the Site it held. This runs for both backends: HostLink and ROS 2 create the driver first and set the service afterwards. A failed move is logged and stays pending. The init error log now says the material is moved out, and asks to recreate it from the registry and delete the old row. --- .../runtime/test_legacy_material_detach.py | 98 +++++++++++++++++++ .../client/host/runtime/driver_creator.py | 15 ++- unilabos/client/host/runtime/node.py | 27 +++++ unilabos/resources/resource_tracker.py | 3 + 4 files changed, 140 insertions(+), 3 deletions(-) create mode 100644 tests/client/host/runtime/test_legacy_material_detach.py diff --git a/tests/client/host/runtime/test_legacy_material_detach.py b/tests/client/host/runtime/test_legacy_material_detach.py new file mode 100644 index 000000000..34d363e9b --- /dev/null +++ b/tests/client/host/runtime/test_legacy_material_detach.py @@ -0,0 +1,98 @@ +"""初始化时拆下的非 PLR 物料在权威里移出设备子树,这棵树之后的严格快照照常对得上。 + +升级前的旧数据里,PLR 物料下面可能挂着没有 ``config.type`` 的物料。设备初始化把它从本地树拆掉; +权威那棵树里若还挂着它,本地树与权威永远对不上,严格快照(观察者的整树提交)全被拒,这棵树上的 +状态变化都会丢。节点拿到物料服务时把拆下的各枝移成独立根物料,两边重新一致。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +from pylabrobot.resources import Coordinate, Resource + +from unilabos.client.host.hostlink.local_runtime import HostLinkDriverSpec, HostLinkLocalRuntime +from unilabos.client.host.runtime.resource import AuthorityResourceService +from unilabos.client.materials import LocalMaterialsClient +from unilabos.resources import materials +from unilabos.resources.adapters.device_site import apply_device_authority_state +from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance +from unilabos.server.services.materials import MaterialsService +from tests.plr_fixtures import plate + +DEVICE_TEMPLATE = "legacy_detach_test_device" + + +class _Device: + def __init__(self, **_kwargs) -> None: + pass + + +def _device_config(device_uuid: str, gateway) -> ResourceDictInstance: + config = ResourceDictInstance( + ResourceDict.model_validate( + { + "id": "placer", "uuid": device_uuid, "name": "placer", "type": "device", + "class": DEVICE_TEMPLATE, "template_name": DEVICE_TEMPLATE, + "config": {}, "data": {}, "extra": {}, "sites": None, "sites_initialized": False, + } + ) + ) + apply_device_authority_state( + config, {"available_sites": [{"index": 1, "label": "slot_a"}]}, DEVICE_TEMPLATE, gateway=gateway + ) + return config + + +def _start(device_uuid: str, gateway) -> tuple[HostLinkLocalRuntime, object]: + runtime = HostLinkLocalRuntime() + node = runtime.add_driver( + HostLinkDriverSpec( + "placer", _Device, {}, resource_uuid=device_uuid, device_config=_device_config(device_uuid, gateway) + ) + ) + runtime.set_resource_service(AuthorityResourceService(gateway)) + runtime.start() + return runtime, node + + +def test_a_legacy_child_is_moved_out_so_its_tree_snapshots_strictly_again(tmp_path) -> None: + service = MaterialsService(tmp_path / "materials.db") + gateway = LocalMaterialsClient(service) + device_uuid = str(uuid4()) + try: + runtime, node = _start(device_uuid, gateway) + holder = Resource("holder", size_x=300, size_y=100, size_z=10, category="container") + holder.assign_child_resource(plate("keep"), location=Coordinate(0, 0, 0)) + holder.assign_child_resource( + Resource("legacy", size_x=10, size_y=10, size_z=10, category="container"), + location=Coordinate(200, 0, 0), + ) + created = materials.create(holder, node=node, site="slot_a", gateway=gateway) + holder_uuid = created.unilabos_uuid + legacy_uuid = next(child.unilabos_uuid for child in created.children if child.name == "legacy") + runtime.stop() + # 升级前留下的行:没有 config.type + with service.write(): + service.connection.execute( + "UPDATE material SET config_json=json_remove(config_json,'$.type') WHERE material_uuid=?", + (legacy_uuid,), + ) + + runtime, node = _start(device_uuid, gateway) + try: + local_holder = node.resource_tracker.uuid_to_resources[holder_uuid] + assert legacy_uuid not in node.resource_tracker.uuid_to_resources + assert node.resource_tracker.legacy_material_uuids == [] + # 权威里它已是独立根物料,holder 那棵树与本地一致 + assert service.get_material(legacy_uuid).material.parent_material_uuid is None + assert legacy_uuid not in { + item.material.material_uuid for item in service.get_tree(holder_uuid).nodes + } + AuthorityResourceService(gateway)._update_sync( + "placer", device_uuid, local_holder, allow_partial=False, conflict_retries=1 + ) + finally: + runtime.stop() + finally: + service.close() diff --git a/unilabos/client/host/runtime/driver_creator.py b/unilabos/client/host/runtime/driver_creator.py index a097bbccd..6d34b0eef 100644 --- a/unilabos/client/host/runtime/driver_creator.py +++ b/unilabos/client/host/runtime/driver_creator.py @@ -36,13 +36,19 @@ def create_instance(self, *args: Any, **kwargs: Any) -> T: def _plr_children( - device_cls: Type[Any], children: List[ResourceDictInstance] + device_cls: Type[Any], + children: List[ResourceDictInstance], + resource_tracker: Optional[DeviceNodeResourceTracker] = None, ) -> List[ResourceDictInstance]: """设备初始化拿到的子树先拆一遍:每棵物料子树只留能按 PLR 反序列化的部分。 挂载用的物料、构造设备要一起带上的物料(液体工作站的台面、工作站的 deck)都从这里取, 同一套拆法。拆下来的非 PLR 物料(升级前遗留,没有 ``config.type``)连同挂在它下面的物料 不挂到设备本地,逐个点名报错;整台设备照常初始化。子设备由它自己的构造器处理,不在这里拆。 + + 拆下的各枝记在 ``resource_tracker.legacy_material_uuids``:节点拿到物料服务时把它们在权威里 + 移出设备子树(成为独立根物料)。否则权威的树里还挂着它们,与本地树永远对不上,这棵树的 + 严格快照全被拒,设备运行中的状态变化(体积、枪头……)都会丢。 """ device_name = getattr(device_cls, "__name__", str(device_cls)) @@ -55,11 +61,14 @@ def _plr_children( for content in pruned: logger.error( "设备 %s 下的物料 %s(%s)不是 PLR 物料(没有 config.type),连同挂在它下面的物料" - "没有挂到设备本地;请移走或删除它,再按注册表资源类经 materials.create 重新创建", + "没有挂到设备本地,并会在权威里移出设备子树(成为独立根物料);请按注册表资源类经 " + "materials.create 重新创建它,再删除这条旧物料", device_name, content.id, content.uuid, ) + if resource_tracker is not None and content.uuid: + resource_tracker.legacy_material_uuids.append(str(content.uuid)) if tree is not None: result.append(tree) return result @@ -76,8 +85,8 @@ def __init__( ) -> None: self.device_cls = cls self.device_instance: Optional[T] = None - self.children = _plr_children(cls, children) self.resource_tracker = resource_tracker + self.children = _plr_children(cls, children, resource_tracker) def attach_resource(self) -> None: if self.device_instance is None: diff --git a/unilabos/client/host/runtime/node.py b/unilabos/client/host/runtime/node.py index bb64ab15e..290d7b217 100644 --- a/unilabos/client/host/runtime/node.py +++ b/unilabos/client/host/runtime/node.py @@ -162,6 +162,33 @@ def set_resource_service(self, service: "ResourceService") -> None: observer.set_service(service) self.__dict__["_material_snapshot_observer"] = observer observer.observe_all(list(tracker.resources)) + self._detach_legacy_materials(service, tracker) + + def _detach_legacy_materials(self, service: Any, tracker: Any) -> None: + """初始化时拆下的非 PLR 物料在权威里移出设备子树(移成独立根物料,释放占着的库位)。 + + 本地树已经没有它们;权威那棵树里若还挂着,两边永远对不上,这棵树的严格快照全被拒。 + 移成功的从待办里去掉;失败的留着报错,下次拿到物料服务时再试。设备构造期就可能走到这里 + (ROS 2 节点在 ``Node.__init__`` 之前设物料服务),所以用模块 logger。 + """ + + from unilabos.utils import logger + + pending = getattr(tracker, "legacy_material_uuids", None) + move = getattr(service, "move_resource_sync", None) + if not pending or not callable(move): + return + for material_uuid in list(pending): + try: + move(str(self.device_id), str(self.resource_uuid or ""), material_uuid, parent_material_uuid=None) + except Exception as exc: # noqa: BLE001 - 失败只影响这棵树的快照,设备照常运行 + logger.error( + f"设备 {self.device_id} 的非 PLR 物料 {material_uuid} 没能移出设备子树({exc});" + "在它被移走或删除之前,它所在那棵树的快照会被权威拒绝" + ) + continue + pending.remove(material_uuid) + logger.warning(f"设备 {self.device_id} 的非 PLR 物料 {material_uuid} 已在权威里移出设备子树,成为独立根物料") def _invalidate_material_baselines(self) -> None: """权威侧结构已变(下行投影 / 挂载):本地缓存的根树基线作废,下次 flush 重拉一次。""" diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index 49c60ea30..7201a4aaf 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -2056,6 +2056,9 @@ def __init__(self): self.uuid_to_resources: Dict[str, Any] = {} self._names: Dict[str, List[Any]] = {} self._parents: Dict[int, Any] = {} + #: 设备初始化时从子树拆下、还没在权威里移出设备子树的非 PLR 物料(各枝的根 uuid); + #: 节点拿到物料服务时逐个移出(见 ``DeviceNode.set_resource_service``) + self.legacy_material_uuids: List[str] = [] # ── 索引维护 ────────────────────────────────────────────── From 0650d866f6e30ccfc41c334f93e09af7220912dd Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:25:39 +0800 Subject: [PATCH 20/59] fix(devices): heater gives each new sample a free resource_id and a device-specific barcode A new sample always used resource_id -sample- and barcode OPENLAB-HEAT-. Both must be unique among undeleted materials. So: - When the sample on a site was moved away (or, on upgrade, a legacy sample was moved out of the device subtree), the site could never be provisioned again. heat_site failed with "site N has no heating sample". - A second heater in the same lab got no samples at all, because its barcodes collided with the first heater's. Barcodes now carry the device id (OPENLAB-HEAT--). When -sample- is still taken by the sample that left, the new sample gets -2, -3, ... on both its resource_id and its barcode. The sample that left is not touched. --- .../devices/test_virtual_heating_platform.py | 50 ++++++++++++++++++- unilabos/devices/virtual/heating_platform.py | 25 +++++++++- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/tests/devices/test_virtual_heating_platform.py b/tests/devices/test_virtual_heating_platform.py index 251729a64..9db55e51e 100644 --- a/tests/devices/test_virtual_heating_platform.py +++ b/tests/devices/test_virtual_heating_platform.py @@ -155,7 +155,7 @@ def test_heater_creates_plr_samples_on_its_own_sites_and_heats_them(heater) -> N assert sample.material.template_name == SAMPLE_TEMPLATE assert sample.material.resource_id == f"heater-demo-sample-{index}" assert sample.material.display_name == f"加热样品 {index}" - assert sample.material.barcode == f"OPENLAB-HEAT-{index}" + assert sample.material.barcode == f"OPENLAB-HEAT-heater-demo-{index}" assert sample.material.meta_data["display_color"] == SAMPLE_DISPLAY_COLORS[index - 1] # uuid → 实例唯一:驱动拿着的就是设备 tracker 登记的那一份 instance = tracker.uuid_to_resources[sample.material.material_uuid] @@ -246,6 +246,54 @@ def test_material_temperature_is_latest_passive_device_projection(heater) -> Non assert platform.site_1_temperature_c == 27.0 +def test_an_emptied_site_gets_a_new_sample_without_touching_the_one_that_left(heater) -> None: + """样品被移走后(还在别处),工位再用时放一个新样品:身份加序号,不和移走的那个撞。""" + + from unilabos.protocol.materials import InventoryMutation, MaterialMove + + platform = heater.start() + moved = heater.sites()["site_1"].occupied_material_uuid + command = str(uuid4()) + heater.service.move_material( + InventoryMutation(command_uuid=command, effect_key=f"move_material:{command}", operation="move_material", + actor_type="human", actor_uuid="test"), + MaterialMove(material_uuid=moved, parent_material_uuid=None), + ) + + result = platform.heat_site( + site_id=1, target_temperature_c=50.0, duration_seconds=0.1, action_context=ActionContext(action_id="refill") + ) + + fresh = heater.sites()["site_1"].occupied_material_uuid + assert fresh and fresh != moved and result["material_uuid"] == fresh + sample = heater.service.get_material(fresh).material + assert (sample.resource_id, sample.barcode) == ("heater-demo-sample-1-2", "OPENLAB-HEAT-heater-demo-1-2") + assert heater.service.get_material(fresh).data.data["temperature_c"] == 50.0 + # 移走的那个原样留着 + left = heater.service.get_material(moved).material + assert (left.resource_id, left.parent_material_uuid) == ("heater-demo-sample-1", None) + + +def test_two_heaters_in_one_lab_each_get_their_samples(tmp_path, monkeypatch) -> None: + service = MaterialsService(tmp_path / "materials.db") + monkeypatch.setattr(BasicConfig, "is_host_mode", True) + set_materials_gateway(LocalMaterialsClient(service)) + first, second = _Heater(service, "heater-a"), _Heater(service, "heater-b") + try: + first.start() + second.start() + for rig in (first, second): + occupants = [site.occupied_material_uuid for site in rig.sites().values()] + assert len(occupants) == 3 and all(occupants) + barcodes = {item.material.barcode for item in service.list_materials() if item.material.barcode} + assert len(barcodes) == 6 + finally: + second.stop() + first.stop() + set_materials_gateway(None) + service.close() + + def test_heater_needs_its_device_node() -> None: with pytest.raises(RuntimeError, match="post_init"): VirtualHeatingPlatform("orphan-heater").initialize() diff --git a/unilabos/devices/virtual/heating_platform.py b/unilabos/devices/virtual/heating_platform.py index e1e21eca2..480e82a6a 100644 --- a/unilabos/devices/virtual/heating_platform.py +++ b/unilabos/devices/virtual/heating_platform.py @@ -392,14 +392,35 @@ def _refresh_sites(self) -> None: occupied, ) + @not_action + def _sample_identity(self, site_id: int) -> tuple[str, str]: + """新样品的 resource_id 与条码,两者在未删除的物料里都要唯一。 + + 按设备与工位区分(同一实验室的第二台加热平台不和第一台撞条码)。工位原来的样品被移走 + 但还在(或升级时被移出设备子树的旧样品)时,``<设备>-sample-<工位>`` 已被占用:加序号 + ``-2``、``-3``……建一个新样品,不去动那一个。 + """ + + resource_id = f"{self.device_id}-sample-{site_id}" + barcode = f"OPENLAB-HEAT-{self.device_id}-{site_id}" + gateway = self._gateway() + for attempt in range(1, 100): + suffix = "" if attempt == 1 else f"-{attempt}" + try: + gateway.get_material_by_resource_id(resource_id + suffix) + except Exception: # noqa: BLE001 - 查不到即可用;权威读不到时交给建树报错 + return resource_id + suffix, barcode + suffix + raise RuntimeError(f"{self.device_id} 工位 {site_id} 找不到可用的样品 resource_id") + @not_action def _new_sample(self, site_id: int) -> VirtualHeatingSample: from unilabos.resources.resource_tracker import set_plr_template_name + resource_id, barcode = self._sample_identity(site_id) sample = VirtualHeatingSample( - f"{self.device_id}-sample-{site_id}", + resource_id, barcode=Barcode( - data=f"OPENLAB-HEAT-{site_id}", + data=barcode, symbology="CODE128", position_on_resource="front", ), From 1bfeba6fe228b0ab186b142e0f5f355f597d9115 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:27:08 +0800 Subject: [PATCH 21/59] fix(events): read the materials ledger off the event loop /api/v1/events polled the materials ledger once a second directly on the event loop: latest(), changes() and one get_site per Site row. These reads take the materials store lock, which a writer holds for its whole transaction. While another thread held a write for 2 s, the loop stalled for 1.3 s. Every open /api/v1/events connection did this every second, and that stream is now the one each browser tab keeps. The poll, and the baseline read before the response headers, now run in asyncio.to_thread. A Site that appears several times in the ledger window is looked up once. --- .../test_runtime_events_material_notices.py | 36 +++++++++++++++++++ unilabos/server/api/runtime/events.py | 34 ++++++++++++------ 2 files changed, 60 insertions(+), 10 deletions(-) diff --git a/tests/server/test_runtime_events_material_notices.py b/tests/server/test_runtime_events_material_notices.py index e14885e0c..be22c0bfd 100644 --- a/tests/server/test_runtime_events_material_notices.py +++ b/tests/server/test_runtime_events_material_notices.py @@ -86,6 +86,42 @@ def test_ledger_advance_lists_the_changed_materials_without_an_id(monkeypatch): assert _data(frame) == {"sequence": 7, "material_uuids": ["deck", "plate"]} +def test_a_slow_ledger_read_does_not_stall_the_event_loop(monkeypatch): + """读账本要拿物料库的锁,写事务持锁时读会等;这段等待在工作线程里,不卡住事件循环上的其它连接。""" + + import time + + _quiet(monkeypatch) + + class _SlowLedger(_Ledger): + def latest_ledger_sequence(self) -> int: + time.sleep(0.6) + return self.tail + + async def scenario(): + stream = events.runtime_event_stream( + _Request(), _workflow(), cursor=41, + materials=events.MaterialNotices(_SlowLedger(3, rows=[(3, "material", "m")])), material_cursor=2, + ) + assert "connected" in await anext(stream) + ticks: list[float] = [] + + async def ticker(): + for _ in range(30): + ticks.append(time.monotonic()) + await asyncio.sleep(0.02) + + beat = asyncio.create_task(ticker()) + frame = await asyncio.wait_for(anext(stream), 3) + await beat + await stream.aclose() + return frame, max(later - earlier for earlier, later in zip(ticks, ticks[1:])) + + frame, worst_gap = asyncio.run(scenario()) + assert _data(frame) == {"sequence": 3, "material_uuids": ["m"]} + assert worst_gap < 0.3 + + def test_template_change_asks_for_a_full_reload(monkeypatch): _quiet(monkeypatch) ledger = _Ledger(9, rows=[(8, "material", "plate"), (9, "resource_template", "tpl")]) diff --git a/unilabos/server/api/runtime/events.py b/unilabos/server/api/runtime/events.py index c2c15148e..bacd774e3 100644 --- a/unilabos/server/api/runtime/events.py +++ b/unilabos/server/api/runtime/events.py @@ -98,16 +98,20 @@ def changed_materials(self, after: int, upto: int) -> list[str] | None: if len(rows) > MATERIAL_NOTICE_WINDOW: return None changed: set[str] = set() + sites: set[str] = set() for row in rows: if row.aggregate_type == "material": changed.add(row.aggregate_uuid) elif row.aggregate_type == "site": - site = self._service.get_site(row.aggregate_uuid, include_deleted=True) - if site is not None: - changed.add(site.owner_material_uuid) + sites.add(row.aggregate_uuid) elif row.aggregate_type == "resource_template": # 模板变化可能改变很多物料的展示,不逐个列 return None + # 同一个 Site 在一段账本里常出现多次(占用、释放),每个只查一次所属物料 + for site_uuid in sorted(sites): + site = self._service.get_site(site_uuid, include_deleted=True) + if site is not None: + changed.add(site.owner_material_uuid) return sorted(changed) @@ -138,6 +142,19 @@ def _changed_materials(materials: MaterialNotices, after: int, upto: int) -> lis return None +def _poll_materials(materials: MaterialNotices, cursor: int) -> tuple[int, list[str] | None]: + """账本末尾,以及 ``(cursor, 末尾]`` 里变了的物料;末尾变小(库被重置)时不列。 + + 在工作线程里跑(``asyncio.to_thread``):读账本要拿物料库的锁,写事务持锁期间读会等, + 放在事件循环上会卡住这个进程的全部连接。 + """ + + latest = _latest_material_sequence(materials, cursor) + if latest <= cursor: + return latest, None + return latest, _changed_materials(materials, cursor, latest) + + def material_changed_frame(sequence: int, material_uuids: list[str] | None = None) -> str: """不写 SSE id:Last-Event-ID 只表示工作流持久事件的序号。 @@ -192,13 +209,8 @@ def receive(notice: RuntimeLogNotice): next_workflow = now + 1 if materials is not None: # 账本末尾变了就发一次失效,列出这段区间里变了的物料;库被重置(末尾变小)时不列,整体重读。 - latest_material = _latest_material_sequence(materials, material_cursor) + latest_material, changed = await asyncio.to_thread(_poll_materials, materials, material_cursor) if latest_material != material_cursor: - changed = ( - _changed_materials(materials, material_cursor, latest_material) - if latest_material > material_cursor - else None - ) material_cursor = latest_material yield material_changed_frame(latest_material, changed) if service is not None: @@ -264,7 +276,9 @@ async def events( cursor = service.latest_event_sequence() if service is not None else 0 # 物料账本基线同样在响应头之前固定:onopen 后的 REST 补读覆盖此前的物料变化。 materials = material_notices() - material_cursor = _latest_material_sequence(materials, 0) if materials is not None else 0 + material_cursor = ( + await asyncio.to_thread(_latest_material_sequence, materials, 0) if materials is not None else 0 + ) return StreamingResponse( runtime_event_stream( request, From 80d556e52e7c594714374395c38f5258405496de Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:29:06 +0800 Subject: [PATCH 22/59] fix(workflow): an exported graph imports again despite its derived inventory_requirements MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /workflows/{uuid}/graph now derives the V1 root inventory_requirements from the nodes. POST /workflows/import refused any non-empty list, so a graph with node requirements could no longer be exported and imported back. The request failed with 1000 "暂不支持在导入图中携带 inventory_requirements". Import now accepts the list when it is exactly what the read derives from the imported nodes. That list is a read echo: it is dropped, and the imported workflow derives its own list from its new nodes. The comparison ignores uuid and workflow_uuid, which follow the workflow identity. Any other list (an edited quantity, an extra or hand-written entry) is still refused, because requirements live in the nodes' meta_data.inventory_requirements. --- ...kflow_inventory_requirements_projection.py | 37 +++++++++++++++++++ .../runtime/workflow/definition_edit.py | 18 +++++++++ .../services/runtime/workflow/service.py | 15 ++++++-- 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/tests/server/test_workflow_inventory_requirements_projection.py b/tests/server/test_workflow_inventory_requirements_projection.py index a1d04024a..20e6845dc 100644 --- a/tests/server/test_workflow_inventory_requirements_projection.py +++ b/tests/server/test_workflow_inventory_requirements_projection.py @@ -142,3 +142,40 @@ def test_saved_node_requirements_come_back_in_the_v1_graph(api) -> None: ) # 节点上的原条目保持不变(调度据此预留) assert graph["nodes"][0]["meta_data"]["inventory_requirements"][0]["key"] == "water" + + +def test_an_exported_graph_imports_again_and_a_handwritten_root_list_is_still_refused(api) -> None: + """读图带回派生的图根列表;原样导入时它只是回声,导入后从新节点重新派生。改过的列表不是回声,照旧拒绝。""" + + client, _service = api + workflow = _ok(client.post("/api/v1/workflows", json={"name": "导出", "workflow_type": "experiment_operation"}), 201) + node = { + "uuid": str(uuid4()), "name": "加液", "type": "device_action", "material_uuid": str(uuid4()), + "action_name": "fill_well", "action_type": "UniLabJsonCommand", "param": {"slot": "T1"}, + "pose": {"x": 0, "y": 0}, "execution_policy": {"depends_on": []}, + "meta_data": { + "target_device_id": "material_bench", + "inventory_requirements": [ + {"key": "water", "kind": "lot", "template_uuid": WATER_TEMPLATE, "quantity": 1200.0, "unit": "ul"} + ], + }, + } + _ok(client.put(f"/api/v1/workflows/{workflow['uuid']}/graph", json={ + "revision": workflow["revision"], "nodes": [node], "edges": [], + })) + exported = _ok(client.get(f"/api/v1/workflows/{workflow['uuid']}/graph")) + assert len(exported["inventory_requirements"]) == 1 + + response = client.post("/api/v1/workflows/import", json={**exported, "name": "导出副本"}) + assert response.status_code in (200, 201) and response.json()["code"] == 0, response.text + imported = response.json()["data"] + copy_uuid = (imported.get("workflow") or imported)["uuid"] + copy = _ok(client.get(f"/api/v1/workflows/{copy_uuid}/graph")) + [item] = copy["inventory_requirements"] + assert item["workflow_uuid"] == copy_uuid and item["consume_node_uuid"] == copy["nodes"][0]["uuid"] + assert (item["requirement_key"], item["required_quantity"]) == ("water", 1200.0) + + edited = [{**exported["inventory_requirements"][0], "required_quantity": 5.0}] + refused = client.post("/api/v1/workflows/import", json={**exported, "name": "手写", "inventory_requirements": edited}) + assert refused.status_code == 200 and refused.json()["code"] == 1000 + assert "inventory_requirements" in refused.json()["error"]["msg"] diff --git a/unilabos/server/services/runtime/workflow/definition_edit.py b/unilabos/server/services/runtime/workflow/definition_edit.py index 58c0ae339..e5f25b52e 100644 --- a/unilabos/server/services/runtime/workflow/definition_edit.py +++ b/unilabos/server/services/runtime/workflow/definition_edit.py @@ -387,6 +387,22 @@ def project_inventory_requirements(graph: Mapping[str, Any]) -> list[dict[str, A return projected +def is_derived_inventory_requirements(graph: Mapping[str, Any], requirements: Any) -> bool: + """图根 ``inventory_requirements`` 是不是读图时从节点派生的那份(导出后原样导入的回声)。 + + 比较时不看 ``uuid`` / ``workflow_uuid``:它们按工作流身份生成,导入会换身份。别的任何不同 + (改了数量、多一条、手写一条)都不是回声。 + """ + + if not isinstance(requirements, list) or not all(isinstance(item, Mapping) for item in requirements): + return False + + def essence(items: list[Mapping[str, Any]]) -> list[dict[str, Any]]: + return [{key: value for key, value in item.items() if key not in ("uuid", "workflow_uuid")} for item in items] + + return essence(requirements) == essence(project_inventory_requirements(graph)) + + def definition_graph(graph: Mapping[str, Any]) -> dict[str, Any]: """返回本层节点和边,保留子操作合同 pin、具名实参及外部输出接线。""" owners = private_node_owners(graph["nodes"]) @@ -481,7 +497,9 @@ def restore_private_subgraphs( "create_node", "duplicate_graph", "duplicate_node", + "is_derived_inventory_requirements", "patch_node", "private_node_owners", + "project_inventory_requirements", "restore_private_subgraphs", ] diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index d6ea6d658..21a32f119 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -3373,7 +3373,10 @@ def import_python_workflow(self, *, file_name: str, python_source: str) -> Dict[ def import_legacy_workflow(self, *, payload: Dict[str, Any]) -> Dict[str, Any]: """V1 ``POST /workflows/import``:旧版 JSON 图(直接或 ``data`` 包装)重建身份后原子导入。""" - from unilabos.server.services.runtime.workflow.definition_edit import duplicate_graph + from unilabos.server.services.runtime.workflow.definition_edit import ( + duplicate_graph, + is_derived_inventory_requirements, + ) definition = payload.get("data") if isinstance(payload.get("data"), dict) else payload name = definition.get("name") or definition.get("workflow_name") @@ -3383,8 +3386,14 @@ def import_legacy_workflow(self, *, payload: Dict[str, Any]) -> Dict[str, Any]: edges = definition.get("edges") or [] if not isinstance(nodes, list) or not nodes or not isinstance(edges, list): raise WorkflowError("invalid_input", detail="nodes 必须是至少包含一个节点的数组,edges 必须是数组") - if definition.get("inventory_requirements") not in (None, []): - raise WorkflowError("invalid_input", detail="暂不支持在导入图中携带 inventory_requirements") + requirements = definition.get("inventory_requirements") + # 读图返回的图根列表是从节点派生的只读投影:导出后原样导入时它是回声,忽略即可(导入后照样从 + # 节点派生);与节点对不上的列表是手写的图根需求,仍不支持——需求写在节点 meta_data 上。 + if requirements not in (None, []) and not is_derived_inventory_requirements(definition, requirements): + raise WorkflowError( + "invalid_input", + detail="暂不支持在导入图中携带与节点不一致的 inventory_requirements(需求写在节点 meta_data.inventory_requirements)", + ) try: for index, node in enumerate(nodes): if not isinstance(node, dict): From 54592c6682a71f066549aa25358d91cf039205ec Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:29:06 +0800 Subject: [PATCH 23/59] fix(materials): an empty material_uuid does not turn the graph into an empty reread GET /api/v1/materials/graph?material_uuid= (an empty value) counted as an incremental reread of no materials and returned an empty graph. Empty values are now dropped. Only empty values means the full graph; mixed with real uuids, only the real ones are reread. --- tests/server/test_v1_resource_contract.py | 5 +++++ unilabos/server/services/materials/resource_contract.py | 2 ++ 2 files changed, 7 insertions(+) diff --git a/tests/server/test_v1_resource_contract.py b/tests/server/test_v1_resource_contract.py index aef237c09..f3d602137 100644 --- a/tests/server/test_v1_resource_contract.py +++ b/tests/server/test_v1_resource_contract.py @@ -243,6 +243,11 @@ def graph(**params) -> dict: assert all(link["source_uuid"] in {bottle["uuid"], rack["uuid"]} for link in partial["links"]) # 不存在 / 已删除的物料不返回:客户端据此从图里移除 assert graph(material_uuid=["00000000-0000-4000-8000-000000000000"])["nodes"] == [] + # 空值不算点名(``?material_uuid=``):仍是全量 + assert len(graph(material_uuid=[""])["nodes"]) == 3 + assert {node["material"]["uuid"] for node in graph(material_uuid=["", bottle["uuid"]])["nodes"]} == { + bottle["uuid"], rack["uuid"], + } assert graph(inventory_scope="history") == {"nodes": [], "links": []} error_of(client.get("/api/v1/materials/graph", params={"inventory_scope": "bogus"}), 1000) diff --git a/unilabos/server/services/materials/resource_contract.py b/unilabos/server/services/materials/resource_contract.py index c97e01e36..8ff61940c 100644 --- a/unilabos/server/services/materials/resource_contract.py +++ b/unilabos/server/services/materials/resource_contract.py @@ -1014,6 +1014,8 @@ def material_graph( if inventory_scope == INVENTORY_SCOPE_HISTORY: return {"nodes": [], "links": []} connection = self.materials.connection + # 空值(``?material_uuid=``)不算点名:只剩空值时按全量读,不返回空图 + material_uuids = [item.strip() for item in material_uuids if item and item.strip()] if material_uuids: wanted = self._graph_closure(material_uuids) placeholders = ",".join("?" for _ in wanted) From 246e38c1a512c8ef78902c0edd60fcd891d3e7e0 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:29:06 +0800 Subject: [PATCH 24/59] docs: material.changed lists material_uuids; the graph derives inventory_requirements api_v1_migration.md described material.changed with only the sequence. api_v1_route_map.md still said the graph's inventory_requirements list was always empty, and that import refused it unconditionally. --- docs/developer_guide/api_v1_migration.md | 5 +++-- docs/developer_guide/api_v1_route_map.md | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index 3a28209ad..4db785faa 100644 --- a/docs/developer_guide/api_v1_migration.md +++ b/docs/developer_guide/api_v1_migration.md @@ -149,8 +149,9 @@ dev 内部异常到业务码的映射集中在 `envelope.py`,不在各路由 (`task` / `node_run` / `node_job` / `manual_confirmation` / `resource`)放进 V1 事件,不再单独发事件名; 原载荷字段保留。换名在 API 层(`api/runtime/events.py:to_v1_event`)做,`frontend_event` 表仍存 dev 名。 `runtime.logs.changed`(无 id 的日志通知)与物料的 `/api/v1/materials/events`(`materials.changed`)不在 - V1 合同里,暂保持原名。物料失效另以 V1 名 `material.changed`(无 id,`data.sequence` 为账本末尾)随 - `/api/v1/events` 推送,前端每个工站只维持这一条事件流。CLI `workflow watch` 同步修改。 + V1 合同里,暂保持原名。物料失效另以 V1 名 `material.changed`(无 id,`data.sequence` 为账本末尾, + `data.material_uuids` 列出这段账本里变了的物料,Site 的变化归到所属物料;超过 500 条、涉及模板或账本重置时 + 省略,表示整体重读)随 `/api/v1/events` 推送,前端每个工站只维持这一条事件流。CLI `workflow watch` 同步修改。 ## 库存与工作区(p7-c 落地) diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index 35d01522b..bc5d752b0 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -207,7 +207,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | MISSING | `GET /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1664 | - | **Done (p7-a)**: | | MISSING | `PATCH /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1676 | - | **Done (p7-a)**: Only explicitly sent fields are applied. | | MISSING | `POST /api/v1/workflow-nodes/{node_uuid}/duplicate` | unilabos/app/workflow_api.py:1693 | - | **Done (p7-a)**: | -| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`); `workflow_type` honoured; `inventory_requirements` rejected as in V1. Was: Legacy JSON import. Used by the V1 console | +| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`); `workflow_type` honoured; a root `inventory_requirements` list is rejected as in V1 unless it is exactly the list the graph read derives from the imported nodes (an exported graph imports again; uuids are ignored in the comparison). Was: Legacy JSON import. Used by the V1 console | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/batch-delete` | unilabos/app/workflow_api.py:1532 | - | **Done (p7-a)**: | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/duplicate` | unilabos/app/workflow_api.py:1549 | - | **Done (p7-a)**: Copies kind/category too. | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/edges` | unilabos/app/workflow_api.py:1515 | (whole-graph PUT only) | **Done (p7-a)**: Returns the saved graph (201). Was: Used by the V1 console | @@ -220,7 +220,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | DTO-DIFF | `PUT /api/v1/workflows/{workflow_uuid}` | unilabos/app/workflow_api.py:1420 | PUT /api/v1/workflows/{workflow_uuid} | **Done (p7-a)**: Type cannot change (1000); category omitted keeps, null clears. Was: Same as POST /workflows | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/authoring/apply` | unilabos/app/workflow_api.py:2218 | POST /api/v1/workflows/{workflow_uuid}/authoring/apply | **Done (p7-a)**: Body `{candidate_hash}` only; draft hash and base revision are derived from the stored candidate (`WorkflowService.apply_authoring_by_candidate`). The triple-CAS body is rejected (1000). Was: V1 {candidate_hash} vs DEV {expected_draft_hash, expected_workflow_revision, expected_candidate_hash}. Both strict | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/composite-invocations` | unilabos/app/workflow_api.py:1597 | POST /api/v1/workflows/{workflow_uuid}/composite-invocations | **Done (p7-a)**: V1 body `{revision, contract_uuid, invocation_uuid, device_bindings, pose, param}`; child = the contract's workflow, child revision = the contract's revision; child must be an experiment operation (1000) whose current revision is published (3003); dev publications have no executor requirements, so `device_bindings` must be `{}`. Returns the parent graph (current layer), HTTP 200. Dev body removed. Was: V1 {revision, contract_uuid, invocation_uuid, device_bindings, pose, param} vs DEV {revision, child_workflow_uuid, child_revision, invocation_uuid, pose, arguments}. Both strict, so each rejects the other's body. V1 returns 200, DEV 201 | -| DTO-DIFF | `GET /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1449 | GET /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `workflow` gains `status`/`workflow_type`/`operation_category_uuid`; current layer only (V1 `definition_graph`); `inventory_requirements` present (dev keeps node-level requirements in `meta_data`, so the list is empty). Was: V1 returns {workflow(+status, category), nodes, edges, inventory_requirements} for the current layer only. DEV returns {workflow, nodes, edges, node_templates, handle_templates} | +| DTO-DIFF | `GET /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1449 | GET /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `workflow` gains `status`/`workflow_type`/`operation_category_uuid`; current layer only (V1 `definition_graph`); `inventory_requirements` is derived on every read from the nodes' `meta_data.inventory_requirements` (the single source; content→current_substance, lot→lot with allow_split, material→material 1 件; a key used by several nodes becomes `/`; the original entry is in `meta_data.unilab.inventory`). Was: V1 returns {workflow(+status, category), nodes, edges, inventory_requirements} for the current layer only. DEV returns {workflow, nodes, edges, node_templates, handle_templates} | | DTO-DIFF | `PUT /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1461 | PUT /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `site_binding_mode` defaults to `preserve` (V1 plain save); programmatic import (`client/runtime/workflow.py`, from-template) sends `resolve` explicitly. `node.manual_confirmation` persisted (runtime.db column). Composite private sub-graphs are restored when the client sends the current layer only. Was: DEV defaults site_binding_mode to 'resolve' (its own doc says browsers must send 'preserve'), so a V1 client's save can fail with site_binding_invalid. DEV also drops node.manual_confirmation | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/publications` | unilabos/app/workflow_api.py:1563 | POST /api/v1/workflows/{workflow_uuid}/publications | **Done (p7-a)**: Returns the V1 contract (`uuid` = contract_uuid, `workflow_revision`, `version`, `input_contract`, `output_contract`, `executor_requirements: []`, `node_template_uuid`, `node_count`, `edge_count`, `revision_fingerprint`) plus dev's palette fields (`revision`, `inputs`, `outputs`, `node_template`, `handle_templates`). Was: Request is the same ({revision}). V1 returns a public contract whose contract_uuid feeds composite-invocations; DEV returns a publication record. Field-level diff UNVERIFIED | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/run-preflight` | unilabos/app/workflow_api.py:1639 | POST /api/v1/workflows/{workflow_uuid}/run-preflight | **Done (p7-a)**: V1 body (`run_mode` string, `inventory_bindings` V1 DTO, extra fields ignored); bindings are applied to the candidate plan like task creation (an unmatched binding is an `invalid_inventory_binding` check, the inventory check reports against the bound source) and echoed in the report. `Cache-Control: no-store`. Was: F02. DEV is strict, forbids inventory_bindings and restricts run_mode to a Literal | From b6159d8c009fb9b21bdb11efffcf7e0f7d206cb1 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:31:41 +0800 Subject: [PATCH 25/59] fix(materials): V1 POST /materials creates, places and fills in one transaction V1 POST /api/v1/materials did three separate transactions: create the tree, move it onto the requested Site or parent, then create the reagent. When a later step failed, a compensating delete removed the material, but it swallowed its own errors. A crash or a failed delete could leave a material that was created but not placed, and the intermediate state was visible in between. The placement now uses the tree's own MaterialPlacement: the Site's owner as parent, with the Site as the selector, or the parent alone. The tree create and the optional reagent run under one outer materials write, which is re-entrant, so inner mutations do not commit. Any failure rolls everything back, and the compensating delete is gone. --- tests/server/test_v1_resource_contract.py | 29 +++++++++++ .../services/materials/resource_contract.py | 50 +++++++++---------- 2 files changed, 52 insertions(+), 27 deletions(-) diff --git a/tests/server/test_v1_resource_contract.py b/tests/server/test_v1_resource_contract.py index f3d602137..9c1aceb2c 100644 --- a/tests/server/test_v1_resource_contract.py +++ b/tests/server/test_v1_resource_contract.py @@ -172,6 +172,35 @@ def test_material_create_place_update_ledger_and_delete(client) -> None: error_of(client.get(f"/api/v1/materials/{bottle['uuid']}"), 6000) +def test_v1_create_places_and_fills_in_one_transaction(client) -> None: + """建物料、放入库位与装液是同一个事务:装液失败时物料与落位一起回滚,库位仍空、不留半成品。""" + + identities = _templates(client) + rack = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["tube_rack_2"], "name": "架-T"}), status=201) + site_uuid = rack["site_uuids"][0] + + def total() -> int: + return ok_data(client.get("/api/v1/materials", params={"page": 1, "page_size": 100}))["total"] + + before = total() + failed = client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-坏", + "site_placement": {"action": "place", "site_uuid": site_uuid}, + "reagent": {"quantity": 5}, # 缺 quantity_unit:装液被拒 + }) + assert failed.json()["code"] == 1000, failed.text + assert total() == before + assert ok_data(client.get(f"/api/v1/sites/{site_uuid}"))["occupied_material_uuid"] is None + + placed = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-好", + "site_placement": {"action": "place", "site_uuid": site_uuid}, + }), status=201) + assert placed["current_site"]["uuid"] == site_uuid and placed["parent_uuid"] == rack["uuid"] + assert ok_data(client.get(f"/api/v1/sites/{site_uuid}"))["occupied_material_uuid"] == placed["uuid"] + + def test_v1_material_records_carry_inventory_facts(client) -> None: """V1 物料 DTO 带 inventory_status / inventory_presence / disposition,由生命周期派生。""" diff --git a/unilabos/server/services/materials/resource_contract.py b/unilabos/server/services/materials/resource_contract.py index 8ff61940c..7ab47ce51 100644 --- a/unilabos/server/services/materials/resource_contract.py +++ b/unilabos/server/services/materials/resource_contract.py @@ -22,6 +22,7 @@ MaterialMove, MaterialNodeCreate, MaterialPatch, + MaterialPlacement, MaterialPosition, MaterialTreeCreate, ResourceTemplateRead, @@ -616,7 +617,13 @@ def create_material(self, values: Mapping[str, Any]) -> dict[str, Any]: if isinstance(relative, Mapping): position = self._position_from_v1(relative) material_uuid = str(uuid4()) - tree = MaterialTreeCreate(nodes=[MaterialNodeCreate( + # 放入库位 = 挂到库位的所属物料并占用它;只给父物料 = 只落父子关系。与建树同一事务(MaterialPlacement) + tree_placement: Optional[MaterialPlacement] = None + if site_uuid: + tree_placement = MaterialPlacement(parent_material_uuid=site.owner_material_uuid, site=site_uuid) + elif parent_uuid: + tree_placement = MaterialPlacement(parent_material_uuid=parent_uuid) + tree = MaterialTreeCreate(placement=tree_placement, nodes=[MaterialNodeCreate( client_ref="material", material_uuid=material_uuid, identity=MaterialIdentityWrite( @@ -633,39 +640,28 @@ def create_material(self, values: Mapping[str, Any]) -> dict[str, Any]: ), position=position, )]) + reagent = values.get("reagent") + content: Optional[dict[str, Any]] = None try: - self.materials.create_tree( - new_mutation("create_material_tree", payload=tree.model_dump(mode="json", exclude_none=False)), tree - ) + # 建树、落位与装液在同一个外层事务里(写入口可重入,内层不提交):任一步失败整体回滚, + # 不留下建了一半、没落位或没装液的物料,也不需要事后补偿删除 + with self.materials.write(): + self.materials.create_tree( + new_mutation("create_material_tree", payload=tree.model_dump(mode="json", exclude_none=False)), + tree, + ) + if isinstance(reagent, Mapping): + from unilabos.server.services.materials.contents import ContentContract + + content = ContentContract(self.materials).create_reagent( + {**reagent, "material_uuid": material_uuid} + ) except MaterialConflictError as exc: if exc.conflict is None: raise MaterialConflictError( "Material barcode or sibling name conflicts with an existing material", conflict="identity" ) from None raise - try: - if site_uuid or parent_uuid: - move = MaterialMove(material_uuid=material_uuid, destination_site_uuid=site_uuid, - parent_material_uuid=None if site_uuid else parent_uuid) - self.materials.move_material( - new_mutation("move_material", payload=move.model_dump(mode="json", exclude_none=False)), move - ) - reagent = values.get("reagent") - content: Optional[dict[str, Any]] = None - if isinstance(reagent, Mapping): - from unilabos.server.services.materials.contents import ContentContract - - content = ContentContract(self.materials).create_reagent({**reagent, "material_uuid": material_uuid}) - except Exception: - # 物料与放置 / 装液不是同一事务:后续步骤失败时撤销刚创建的空物料,不留半成品 - delete = MaterialDelete(material_uuid=material_uuid, recursive=True) - try: - self.materials.delete_material( - new_mutation("delete_material", payload=delete.model_dump(mode="json")), delete - ) - except Exception: # noqa: BLE001 - 补偿失败不掩盖原错误 - pass - raise result = self.material_detail(material_uuid) aggregate = self.materials.get_material(material_uuid) result["children"] = [] From e125c66cbedc629c1c82d9c5efaa6f945e684a2e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:30:50 +0800 Subject: [PATCH 26/59] fix(materials): the materials event stream resets a cursor it cannot resume After a restart on a new data directory, a browser reconnects to /api/v1/materials/events with its old Last-Event-ID. When that id was ahead of the new ledger, the stream sent nothing until the new ledger grew past it, so pages that rely on this stream went stale. When the new ledger had already grown past it, the stream resumed in the middle of another database's history. The stream now follows /api/v1/events: - a fresh connection gets an id-only watermark frame; - a cursor it cannot resume gets stream.reset with the new watermark as its id and data.reason, and the connection stays open. The reason is cursor_ahead when the cursor is past the ledger tail, and epoch_changed when the cursor came from another ledger. To tell ledgers apart, the SSE id is now :. The epoch is a 16-hex digest of the ledger's first event_uuid: fixed for one database (the ledger is append-only) and different for any other. An empty ledger has no epoch, and its id stays . Old clients keep working. Browsers echo the id without parsing it, and a page that ignores stream.reset still gets the new watermark from that frame, so later materials.changed events arrive. A plain numeric Last-Event-ID is still accepted, with only the cursor_ahead check. A client that parsed the id as an integer should read data.sequence. The realtime, materials and API catalog docs describe the epoch and the reset. An invalid cursor answers with the 1000 envelope, not HTTP 422, as it already did. --- .../developer_guide/interfaces/api-catalog.md | 2 +- docs/developer_guide/interfaces/materials.md | 3 +- docs/developer_guide/interfaces/realtime.md | 31 ++- tests/server/test_materials_events.py | 249 +++++++++++++++++- unilabos/server/api/materials/core.py | 100 +++++-- unilabos/server/services/materials/store.py | 15 ++ 6 files changed, 368 insertions(+), 32 deletions(-) diff --git a/docs/developer_guide/interfaces/api-catalog.md b/docs/developer_guide/interfaces/api-catalog.md index b3c6bb400..a49feda24 100644 --- a/docs/developer_guide/interfaces/api-catalog.md +++ b/docs/developer_guide/interfaces/api-catalog.md @@ -276,7 +276,7 @@ ResourceTreeNotify 为 device_id、action、resource_uuids,动作值及设备 | POST | `/api/v1/materials/snapshots/delta` | B: `M` | 应用差量并产生账本记录 | | GET | `/api/v1/materials/changes` | Q: after_sequence=0(>=0)、limit=100(1..1000) | 增量账本,供同步消费者补读 | | POST | `/api/v1/materials/changes/ack` | B: LedgerAcknowledge | `{acknowledged:数量}`;through_sequence>=0,普通浏览器不替同步消费者 ACK | -| GET | `/api/v1/materials/events` | H: Last-Event-ID? | text/event-stream;物料变更提醒,收到后拉取正文 | +| GET | `/api/v1/materials/events` | H: Last-Event-ID?(`:` 或旧格式 ``) | text/event-stream;物料变更提醒,收到后拉取正文;游标无法续传时 `stream.reset` | 材料写入失败常见 404(目标不存在)、409(幂等/版本/占用等冲突)、422(模型或操作不合法); transfer 还需识别设备投影失败。不要收到错误后直接改数据库或更换幂等键重放物理动作。 diff --git a/docs/developer_guide/interfaces/materials.md b/docs/developer_guide/interfaces/materials.md index 858b35dd3..d035d3a97 100644 --- a/docs/developer_guide/interfaces/materials.md +++ b/docs/developer_guide/interfaces/materials.md @@ -256,7 +256,8 @@ delta 用 MaterialDelta 描述允许变化的片段;不能把任意 JSON patch 本地 observer 对 assign/unassign 与状态变化形成快照/diff,然后通过权威写入;普通 Python 属性赋值本身不是远端写入确认。 -前端订阅 `/materials/events` 的 `materials.changed`,收到通知后 HTTP 拉实例/树/列表。 +前端订阅 `/materials/events` 的 `materials.changed`,收到通知后 HTTP 拉实例/树/列表; +收到 `stream.reset`(游标来自另一个库或超前于账本)时整体重读。 创建完成后“API 有物料但地图没有”应依次检查:权威读结果、parent/Site 归属、SSE 通知、前端缓存、设备 load。 具体重连与首次快照顺序见 [实时通信](realtime.md),不要刷新页面或重复创建来修补丢失通知。 diff --git a/docs/developer_guide/interfaces/realtime.md b/docs/developer_guide/interfaces/realtime.md index fbe78dc1c..9f96db8ab 100644 --- a/docs/developer_guide/interfaces/realtime.md +++ b/docs/developer_guide/interfaces/realtime.md @@ -22,12 +22,13 @@ | 项目 | `/api/v1/events` | `/api/v1/materials/events` | | --- | --- | --- | -| 无 Last-Event-ID 首连 | 固定当前最新序号,先发只含 `id` 的水位帧,仅推之后变化 | 固定当前账本末尾,仅推之后变化 | -| 持久 SSE id | 工作流事件 id | inventory ledger sequence | -| 恢复方式 | Last-Event-ID,从该 id 之后重放;显式 `0` 回放全部保留历史 | Last-Event-ID,从该 sequence 之后重放 | -| 游标大于最新序号 | `stream.reset`(`reason: cursor_ahead`,`id` 为新水位),连接保持 | 无 | -| 游标早于保留窗口 | `stream.reset`(`reason: cursor_expired`,`id` 为新水位),连接保持 | 无 | -| 非法游标 | Workflow code=1000,HTTP 200 JSON | HTTP 422 | +| 无 Last-Event-ID 首连 | 固定当前最新序号,先发只含 `id` 的水位帧,仅推之后变化 | 固定当前账本末尾,先发只含 `id` 的水位帧,仅推之后变化 | +| 持久 SSE id | 工作流事件 id | `:<账本纪元>`;账本为空时只有 `` | +| 恢复方式 | Last-Event-ID,从该 id 之后重放;显式 `0` 回放全部保留历史 | Last-Event-ID,从该 sequence 之后重放;旧格式的纯数字游标照常接受 | +| 游标大于最新序号 | `stream.reset`(`reason: cursor_ahead`,`id` 为新水位),连接保持 | 同左 | +| 游标来自另一个库 | 无 | `stream.reset`(`reason: epoch_changed`,`id` 为新水位),连接保持;纯数字游标不带纪元,无法判断 | +| 游标早于保留窗口 | `stream.reset`(`reason: cursor_expired`,`id` 为新水位),连接保持 | 无(账本不清理) | +| 非法游标 | Workflow code=1000,HTTP 200 JSON | code=1000,HTTP 200 JSON | | 无事件时 | keepalive 注释;工作流检查约 1 秒,心跳约 15 秒 | keepalive 注释;约 1 秒检查账本 | 三个游标相互独立:工作流 id、物料 sequence、日志 stream:offset。不能混用,也不能以最后日志通知替换工作流游标。 @@ -43,13 +44,26 @@ ### 物料通知 ```text -id: 42 +id: 42:3f9c0a1b7d2e4c55 event: materials.changed data: {"sequence":42,"operation":"update_position","aggregate_type":"material","aggregate_uuid":"..."} ``` -通知只说明什么发生了变化,不带完整树、液体或模板正文。 +通知只说明什么发生了变化,不带完整树、液体或模板正文。需要账本序号时读 `data.sequence`, +不要解析 SSE id。 + +SSE id 冒号后的**账本纪元**是由这个库第一条账本记录派生的 16 位十六进制不透明标识:账本只追加, +同一个库的纪元不变;换了数据目录或全量重置后重建,纪元随之改变。重连时 Last-Event-ID 的纪元与当前库 +不同(`epoch_changed`)或序号超过账本末尾(`cursor_ahead`),服务端发 +`event: stream.reset` + `data: {"reason": "..."}`,`id` 为新水位,连接保持;客户端必须重读 HTTP, +之后的变更照常推送。没有这一帧时,换库后旧游标要么超前(之后的变更全被挡住),要么落在新库账本的中间 +(从别人的历史中途续传)。 + +旧客户端:浏览器的 EventSource 不解析 id,原样回传,所以不用改代码;不监听 `stream.reset` 的页面也会 +在这一帧拿到新水位,之后的 `materials.changed` 照常到达,只是少一次重置触发的重读(重连本身的 `onopen` +仍会重读)。仍发送纯数字 Last-Event-ID 的客户端照常续传,只做 `cursor_ahead` 检查;续传后收到的 id +都带纪元。自己把 SSE id 当整数解析的客户端需要改读 `data.sequence`。 初次应**先建立 SSE,在 onopen 后读取 HTTP 快照**。重连同样重新读快照, 避免“首次取数据 → 开始订阅”之间的变更遗漏。 @@ -83,6 +97,7 @@ function subscribeMaterials(baseUrl, render, reportError) { events.onopen = refresh; events.addEventListener("materials.changed", refresh); + events.addEventListener("stream.reset", refresh); // 游标无法续传(换库 / 超前):整体重读 events.onerror = () => { if (!closed) reportError(new Error("事件流重连中")); }; return () => { closed = true; events.close(); }; } diff --git a/tests/server/test_materials_events.py b/tests/server/test_materials_events.py index 247ea3173..f48551722 100644 --- a/tests/server/test_materials_events.py +++ b/tests/server/test_materials_events.py @@ -1,4 +1,4 @@ -"""物料 SSE 的首连边界、双订阅及重连补偿;通知后以 HTTP 为准。""" +"""物料 SSE 的首连边界、双订阅、重连补偿与游标重置;通知后以 HTTP 为准。""" from __future__ import annotations @@ -7,12 +7,14 @@ from uuid import uuid4 import httpx +import pytest from fastapi import FastAPI from tests.api_envelope import command_result, error_of, ok_data from unilabos.client.materials import bind_payload from unilabos.protocol.materials import InventoryMutation, MaterialDelete, MaterialTreeCreate from unilabos.server.api.materials import install_materials_api +from unilabos.server.api.materials.core import format_materials_cursor, parse_materials_cursor from unilabos.server.services.materials import MaterialsService @@ -46,6 +48,8 @@ def __init__(self, app, *, last_id=None, on_headers=None): self.disconnect = asyncio.Event() self.rows = asyncio.Queue() self.received = [] + #: 每个 SSE 帧的字段(``id`` / ``event`` / ``data``),注释帧不记 + self.frames: list[dict] = [] self.task = None async def start(self): @@ -70,6 +74,13 @@ async def send(message): body = message.get("body", b"").decode() if ": connected" in body: self.connected.set() + for block in body.split("\n\n"): + fields = dict( + line.split(": ", 1) for line in block.splitlines() + if ": " in line and not line.startswith(":") + ) + if fields: + self.frames.append(fields) for line in body.splitlines(): if line.startswith("data: "): row = json.loads(line[6:]) @@ -84,10 +95,18 @@ async def until(self, uuid: str): async def find(): while True: row = await self.rows.get() - if row["aggregate_uuid"] == uuid and row["aggregate_type"] == "material": + if row.get("aggregate_uuid") == uuid and row.get("aggregate_type") == "material": return row return await asyncio.wait_for(find(), 3) + def frame(self, event: str | None) -> dict: + """第一帧给定事件名的帧;``None`` 取只含 ``id`` 的水位帧。""" + + return next(frame for frame in self.frames if frame.get("event") == event and "retry" not in frame) + + def ids(self, event: str) -> list[str]: + return [frame["id"] for frame in self.frames if frame.get("event") == event] + async def close(self): self.disconnect.set() if self.task: @@ -161,3 +180,229 @@ async def scenario(): asyncio.run(scenario()) finally: service.close() + + +def _app(service: MaterialsService) -> FastAPI: + app = FastAPI() + install_materials_api(app, service) + return app + + +def _client(app: FastAPI) -> httpx.AsyncClient: + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") + + +def test_cursor_format_round_trip_and_legacy_numbers(): + assert format_materials_cursor(42, "0123abcd0123abcd") == "42:0123abcd0123abcd" + assert format_materials_cursor(0, None) == "0" + assert parse_materials_cursor("42:0123abcd0123abcd") == (42, "0123abcd0123abcd") + # 旧格式的纯数字游标照常接受,不带纪元 + assert parse_materials_cursor(" 42 ") == (42, None) + assert parse_materials_cursor(None) == (None, None) + assert parse_materials_cursor(" ") == (None, None) + for bad in ("-1", "abc", "42:", ":abcd", "42:ab cd", "1.5"): + with pytest.raises(ValueError): + parse_materials_cursor(bad) + + +def test_ledger_epoch_is_stable_per_database_and_differs_between_databases(tmp_path): + first = MaterialsService(tmp_path / "a" / "materials.db") + second = MaterialsService(tmp_path / "b" / "materials.db") + try: + # 空账本没有纪元 + assert first.ledger_epoch() is None + + async def fill(): + async with _client(_app(first)) as client: + await _create(client, "epoch-a1") + epoch = first.ledger_epoch() + await _create(client, "epoch-a2") + # 只追加的账本:后续写入不改变纪元 + assert first.ledger_epoch() == epoch + async with _client(_app(second)) as client: + await _create(client, "epoch-b1") + + asyncio.run(fill()) + epoch = first.ledger_epoch() + assert isinstance(epoch, str) and len(epoch) == 16 + assert second.ledger_epoch() not in (None, epoch) + finally: + first.close() + second.close() + reopened = MaterialsService(tmp_path / "a" / "materials.db") + try: + assert reopened.ledger_epoch() == epoch + finally: + reopened.close() + + +def test_fresh_connection_sends_watermark_with_epoch(tmp_path): + service = MaterialsService(tmp_path / "materials.db") + app = _app(service) + + async def scenario(): + async with _client(app) as client: + await _create(client, "before-open") + watermark = format_materials_cursor(service.latest_ledger_sequence(), service.ledger_epoch()) + stream = await _Stream(app).start() + try: + uuid = await _create(client, "after-open") + await stream.until(uuid) + assert stream.frame(None) == {"id": watermark} + assert "stream.reset" not in {frame.get("event") for frame in stream.frames} + epoch = service.ledger_epoch() + assert all(item.endswith(f":{epoch}") for item in stream.ids("materials.changed")) + finally: + await stream.close() + + try: + asyncio.run(scenario()) + finally: + service.close() + + +def test_empty_ledger_watermark_has_no_epoch_and_later_ids_do(tmp_path): + service = MaterialsService(tmp_path / "materials.db") + app = _app(service) + + async def scenario(): + async with _client(app) as client: + stream = await _Stream(app).start() + try: + uuid = await _create(client, "first-row") + await stream.until(uuid) + assert stream.frame(None) == {"id": "0"} + epoch = service.ledger_epoch() + assert stream.ids("materials.changed")[0] == f"1:{epoch}" + finally: + await stream.close() + # 空账本时拿到的 "0" 仍从头续传(同一个库里此后的记录都是新的) + resumed = await _Stream(app, last_id="0").start() + try: + await resumed.until(uuid) + assert resumed.received[0]["sequence"] == 1 + assert "stream.reset" not in {frame.get("event") for frame in resumed.frames} + finally: + await resumed.close() + + try: + asyncio.run(scenario()) + finally: + service.close() + + +@pytest.mark.parametrize("with_epoch", [True, False], ids=["epoch", "legacy-number"]) +def test_cursor_ahead_resets_to_latest_and_keeps_streaming(tmp_path, with_epoch): + service = MaterialsService(tmp_path / "materials.db") + app = _app(service) + + async def scenario(): + async with _client(app) as client: + await _create(client, "existing") + latest = service.latest_ledger_sequence() + epoch = service.ledger_epoch() + ahead = format_materials_cursor(latest + 100, epoch if with_epoch else None) + stream = await _Stream(app, last_id=ahead).start() + try: + uuid = await _create(client, "after-reset") + row = await stream.until(uuid) + reset = stream.frame("stream.reset") + assert reset["id"] == format_materials_cursor(latest, epoch) + assert json.loads(reset["data"]) == {"reason": "cursor_ahead"} + # 新水位之后的变更照常推送,不再被旧游标挡住 + assert row["sequence"] > latest + assert stream.ids("materials.changed")[-1] == format_materials_cursor(row["sequence"], epoch) + finally: + await stream.close() + + try: + asyncio.run(scenario()) + finally: + service.close() + + +def test_cursor_from_another_ledger_resets_even_when_behind(tmp_path): + """换了数据目录:新库的账本已经长过旧游标,旧游标的纪元对不上,必须重置而不是从中间续传。""" + + old = MaterialsService(tmp_path / "old" / "materials.db") + new = MaterialsService(tmp_path / "new" / "materials.db") + old_app, new_app = _app(old), _app(new) + + async def scenario(): + async with _client(old_app) as client: + await _create(client, "old-root") + old_cursor = format_materials_cursor(old.latest_ledger_sequence(), old.ledger_epoch()) + async with _client(new_app) as client: + for index in range(3): + await _create(client, f"new-root-{index}") + latest = new.latest_ledger_sequence() + assert latest > old.latest_ledger_sequence() + stream = await _Stream(new_app, last_id=old_cursor).start() + try: + uuid = await _create(client, "after-restart") + row = await stream.until(uuid) + reset = stream.frame("stream.reset") + assert json.loads(reset["data"]) == {"reason": "epoch_changed"} + assert reset["id"] == format_materials_cursor(latest, new.ledger_epoch()) + # 不从旧游标的位置补发新库的历史,只推送新水位之后的变更 + assert [item["sequence"] for item in stream.received if "sequence" in item] == [row["sequence"]] + finally: + await stream.close() + # 同一个库的游标(新格式)照常续传,不重置 + same = await _Stream(new_app, last_id=format_materials_cursor(latest, new.ledger_epoch())).start() + try: + assert (await same.until(uuid))["sequence"] == row["sequence"] + assert "stream.reset" not in {frame.get("event") for frame in same.frames} + finally: + await same.close() + + try: + asyncio.run(scenario()) + finally: + old.close() + new.close() + + +def test_cursor_into_empty_ledger_resets_as_epoch_changed(tmp_path): + old = MaterialsService(tmp_path / "old" / "materials.db") + new = MaterialsService(tmp_path / "new" / "materials.db") + new_app = _app(new) + + async def scenario(): + async with _client(_app(old)) as client: + await _create(client, "old-root") + stream = await _Stream(new_app, last_id=format_materials_cursor(1, old.ledger_epoch())).start() + try: + async with _client(new_app) as client: + uuid = await _create(client, "first-in-new") + await stream.until(uuid) + reset = stream.frame("stream.reset") + assert reset["id"] == "0" + assert json.loads(reset["data"]) == {"reason": "epoch_changed"} + epoch = new.ledger_epoch() + expected = [f"{sequence}:{epoch}" for sequence in range(1, new.latest_ledger_sequence() + 1)] + assert stream.ids("materials.changed") == expected + finally: + await stream.close() + + try: + asyncio.run(scenario()) + finally: + old.close() + new.close() + + +@pytest.mark.parametrize("value", ["abc", "-1", "1:bad epoch", "1:"]) +def test_invalid_last_event_id_is_rejected(tmp_path, value): + service = MaterialsService(tmp_path / "materials.db") + + async def scenario(): + async with _client(_app(service)) as client: + # 信封路由把参数错误换成 HTTP 200 + 1000 失败信封,不开流 + response = await client.get("/api/v1/materials/events", headers={"Last-Event-ID": value}) + assert error_of(response, 1000)["msg"] == "invalid Last-Event-ID" + + try: + asyncio.run(scenario()) + finally: + service.close() diff --git a/unilabos/server/api/materials/core.py b/unilabos/server/api/materials/core.py index c1fc9558f..6ee47e562 100644 --- a/unilabos/server/api/materials/core.py +++ b/unilabos/server/api/materials/core.py @@ -16,6 +16,7 @@ from __future__ import annotations import json +import re from typing import Literal, Optional from fastapi import APIRouter, FastAPI, Header, HTTPException, Query, Request @@ -69,6 +70,36 @@ class MaterialLinksEnsure(ServerObject): links: list[dict] = Field(default_factory=list) +#: 物料账本前进的失效通知(不在 V1 合同里,保持原名) +MATERIALS_CHANGED_EVENT = "materials.changed" +#: 游标无法续传:与 ``/api/v1/events`` 的重置帧同名同形(``id`` 为新水位,``data.reason`` 为原因) +STREAM_RESET_EVENT = "stream.reset" + +_MATERIALS_CURSOR = re.compile(r"(\d{1,19})(?::([0-9A-Za-z_-]{1,64}))?") + + +def format_materials_cursor(sequence: int, epoch: Optional[str]) -> str: + """物料 SSE id:``:``;账本为空、还没有纪元时只有 ````。""" + + return f"{sequence}:{epoch}" if epoch else str(sequence) + + +def parse_materials_cursor(value: Optional[str]) -> tuple[Optional[int], Optional[str]]: + """解析 Last-Event-ID,返回 ``(sequence, epoch)``;缺省或空白返回 ``(None, None)``。 + + 接受 ``:`` 与旧格式的纯数字 ````(epoch 为 None,不做纪元检查); + 其他形式抛 ``ValueError``。 + """ + + text = (value or "").strip() + if not text: + return None, None + match = _MATERIALS_CURSOR.fullmatch(text) + if match is None: + raise ValueError(f"invalid materials cursor: {text!r}") + return int(match.group(1)), match.group(2) + + def _call(function, *args, **kwargs): """调用物料服务;领域异常原样上抛,由信封路由按 ``DOMAIN_ERRORS`` 换算业务码。""" @@ -179,30 +210,50 @@ async def acknowledge_changes(value: LedgerAcknowledge): @router.get("/events") async def events( request: Request, - last_event_id: Optional[str] = Header(default=None, alias="Last-Event-ID"), + last_event_id: Optional[str] = Header( + default=None, + alias="Last-Event-ID", + description=( + "不填时只接收新通知;填上次收到的 id(`:`,或旧格式 ``)" + "从其之后续传,无法续传时收到 stream.reset。" + ), + ), ) -> StreamingResponse: """物料变更 SSE 失效通知(与 workflow ``/api/v1/events`` 同范式)。 以 inventory_ledger 的 sequence 为游标推送 ``materials.changed``; 浏览器只把事件当失效信号并回 HTTP 重取,payload 不承载业务正文。 - 首连(无 Last-Event-ID)静默追平账本尾部,只推送此后的增量; - 重连带 Last-Event-ID 时从该游标续传,补齐离线期间的变更。 + + - 首连(无 Last-Event-ID)在响应头之前固定账本尾部,先发一个只含 ``id`` 的水位帧, + 只推送此后的增量; + - 重连带 Last-Event-ID 时从该游标续传,补齐离线期间的变更; + - 游标无法续传时发 ``stream.reset``(``id`` 为新水位,连接保持,客户端必须重读 HTTP): + 游标大于账本尾部为 ``cursor_ahead``;游标带的账本纪元与当前库不同(换了数据目录、 + 库被重置)为 ``epoch_changed``。 + + SSE id 是 ``:``(纪元见 ``MaterialsRepository.ledger_epoch``),账本为空时只有 + ````。旧格式的纯数字游标照常接受,只做 ``cursor_ahead`` 检查;续传后发出的 id + 都带纪元,浏览器的 EventSource 自动换成新格式。 """ - replay = False - cursor = 0 - if last_event_id is not None and last_event_id.strip(): - try: - cursor = int(last_event_id.strip()) - if cursor < 0: - raise ValueError - replay = True - except ValueError: - raise HTTPException(status_code=422, detail="invalid Last-Event-ID") - - if not replay: - # 必须在发出响应头/onopen 之前固定基线。否则浏览器已校准 HTTP 快照后, - # 首连再追平账本会吞掉这期间的创建/移动;用 MAX 查询也避免全量扫描历史。 - cursor = service.latest_ledger_sequence() + reset_reason: Optional[str] = None + try: + cursor, cursor_epoch = parse_materials_cursor(last_event_id) + except ValueError: + raise HTTPException(status_code=422, detail="invalid Last-Event-ID") + + # 必须在发出响应头/onopen 之前固定基线与新水位。否则浏览器已校准 HTTP 快照后, + # 首连再追平账本会吞掉这期间的创建/移动;用 MAX 查询也避免全量扫描历史。 + latest = service.latest_ledger_sequence() + epoch = service.ledger_epoch() + fresh = cursor is None + if cursor is None: + cursor = latest + elif cursor_epoch is not None and cursor_epoch != epoch: + reset_reason = "epoch_changed" + elif cursor > latest: + reset_reason = "cursor_ahead" + if reset_reason is not None: + cursor = latest def _format_event(row) -> str: data = json.dumps( @@ -215,14 +266,23 @@ def _format_event(row) -> str: ensure_ascii=False, separators=(",", ":"), ) - return f"id: {row.sequence}\nevent: materials.changed\ndata: {data}\n\n" + return f"id: {format_materials_cursor(row.sequence, epoch)}\nevent: {MATERIALS_CHANGED_EVENT}\ndata: {data}\n\n" async def stream(): - nonlocal cursor + nonlocal cursor, epoch yield "retry: 3000\n: connected\n\n" + if reset_reason is not None: + data = json.dumps({"reason": reset_reason}, separators=(",", ":")) + yield f"id: {format_materials_cursor(cursor, epoch)}\nevent: {STREAM_RESET_EVENT}\ndata: {data}\n\n" + elif fresh: + # 只设置浏览器续传水位,不触发业务失效;空闲连接断线后也能从这里续传或被重置。 + yield f"id: {format_materials_cursor(cursor, epoch)}\n\n" # 停机开始就主动结束:浏览器按 retry 自动重连,uvicorn 不必超时取消 while not shutting_down() and not await request.is_disconnected(): rows = service.changes(after_sequence=cursor, limit=500) + if rows and epoch is None: + # 连接时账本为空:第一条记录写入后纪元才确定 + epoch = service.ledger_epoch() for row in rows: cursor = row.sequence yield _format_event(row) diff --git a/unilabos/server/services/materials/store.py b/unilabos/server/services/materials/store.py index 99bc1e08b..16f796dd5 100644 --- a/unilabos/server/services/materials/store.py +++ b/unilabos/server/services/materials/store.py @@ -7,6 +7,7 @@ from __future__ import annotations +import hashlib import json import sqlite3 import threading @@ -1018,6 +1019,20 @@ def latest_ledger_sequence(self) -> int: ).fetchone() return int(row[0]) + def ledger_epoch(self) -> Optional[str]: + """账本纪元:由第一条账本记录的 ``event_uuid`` 派生的 16 位十六进制不透明标识。 + + 账本只追加、从不删除,所以同一个库的纪元恒定;换了库(新的数据目录、全量重置后 + 重建)第一条记录不同,纪元随之改变。账本为空时没有纪元,返回 None。 + """ + + row = self.connection.execute( + "SELECT event_uuid FROM inventory_ledger ORDER BY sequence LIMIT 1" + ).fetchone() + if row is None: + return None + return hashlib.sha256(str(row[0]).encode("utf-8")).hexdigest()[:16] + def list_ledger( self, *, after_sequence: int = 0, limit: int = 100 ) -> list[InventoryLedgerRecord]: From b6eb4f01c7cb5bdb2519add806c52a6a3e1efe55 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:53:33 +0800 Subject: [PATCH 27/59] fix(graph): a carrier's slot holders do not occupy its own Sites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A carrier's direct children are its slot holders, and each holder sits at the position of its Site; the material is placed on the holder. The graph reconciliation that fills Site occupancy by matching child positions took the holders for occupants, so every empty Site of a carrier loaded from a graph file (the shape ResourceTreeSet itself exports) was recorded as occupied by its own holder, and the Host refused to restore the carrier ("占用关系冲突"). Holders (type resource_holder) are skipped when matching occupants. --- tests/server/test_graph_carrier_holders.py | 52 +++++++++++++++++++++ unilabos/server/services/materials/graph.py | 4 ++ 2 files changed, 56 insertions(+) create mode 100644 tests/server/test_graph_carrier_holders.py diff --git a/tests/server/test_graph_carrier_holders.py b/tests/server/test_graph_carrier_holders.py new file mode 100644 index 000000000..f791cb0de --- /dev/null +++ b/tests/server/test_graph_carrier_holders.py @@ -0,0 +1,52 @@ +"""设备图里的载架:槽位 holder 是 Site 的结构节点,不是 Site 的占用物料。 + +载架(``ItemizedCarrier`` / ``WareHouse``)的直接子节点只能是槽位 holder,holder 就放在它 +那个 Site 的位置上;占用物料挂在 holder 下。图里按位置补占用时把 holder 当成占用物料,空 Site +就被记成「被自己的 holder 占着」,Host 反序列化载架时按 canonical 快照核对占用直接失败。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +from pylabrobot.resources import Coordinate + +from unilabos.resources.presets.itemized_carrier import Bottle +from unilabos.resources.presets.warehouse import warehouse_factory +from unilabos.resources.resource_tracker import ResourceTreeSet +from unilabos.server.services.materials.graph import graph_resource_tree, reconcile_graph_payload + + +def _carrier_graph_nodes() -> tuple[list[dict], str]: + """三个 Site 的仓库,A01 上有一个瓶子;按 ResourceTreeSet 导出成图节点。""" + + draft = warehouse_factory("wh", num_items_x=3, num_items_y=1, num_items_z=1) + bottle = Bottle("wh_bottle", diameter=20, height=50, max_volume=100) + bottle.location = Coordinate.zero() + draft["A01"] = bottle + nodes = [node for group in ResourceTreeSet.from_plr_resources([draft], known_random_uuid=True).dump() for node in group] + return nodes, bottle.unilabos_uuid + + +def test_carrier_holders_do_not_occupy_their_own_sites() -> None: + nodes, bottle_uuid = _carrier_graph_nodes() + + normalized, _ = reconcile_graph_payload({"nodes": nodes, "links": []}, None, str(uuid4())) + + (carrier,) = [node for node in normalized["nodes"] if node.get("sites")] + assert {site["label"]: site["occupied_material_uuid"] for site in carrier["sites"]} == { + "A01": bottle_uuid, + "A02": None, + "A03": None, + } + + +def test_carrier_graph_with_holders_restores_on_the_host() -> None: + nodes, bottle_uuid = _carrier_graph_nodes() + normalized, _ = reconcile_graph_payload({"nodes": nodes, "links": []}, None, str(uuid4())) + + (restored,) = graph_resource_tree(list(normalized["nodes"])).to_plr_resources() + + assert restored["A01"].resource.unilabos_uuid == bottle_uuid + assert restored["A02"].resource is None + assert restored["A03"].resource is None diff --git a/unilabos/server/services/materials/graph.py b/unilabos/server/services/materials/graph.py index cc4eb83ea..647abaeb5 100644 --- a/unilabos/server/services/materials/graph.py +++ b/unilabos/server/services/materials/graph.py @@ -423,6 +423,10 @@ def previous_for(node: Mapping[str, Any]) -> Optional[Mapping[str, Any]]: 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") From 3451a7433f423e2b07d98bd3bc07473fa91dbc03 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:07:24 +0800 Subject: [PATCH 28/59] fix(database): reset the runtime and materials baselines instead of repairing old data main is not released yet, so old development databases are rebuilt rather than migrated or repaired. runtime and materials move to contract_version 2 (schema v1 stays the baseline): a database written before the reset is refused with the existing "incompatible, needs rebuild" error, or backed up and rebuilt when database_rebuild_on_mismatch is set. With the reset, the code that existed only for old data goes away: MaterialsService.repair_site_occupant_parents and its call in ServerServices.open (it moved legacy occupants under carrier holders and could keep the authority from starting), and the in-place re-parent branch of a move onto the Site a material already occupies, which only that repair used. Such a move is now "already at destination". The database guide notes that schema upgrades move to versioned, Flyway-like migrations after main is released. --- docs/developer_guide/databases.md | 6 ++ .../examples/materials_operations_guide.md | 4 +- .../v1_file_index/scheduler.md | 4 +- tests/server/test_database_schema_versions.py | 36 ++++++++++- tests/server/test_site_holder_placement.py | 59 ------------------- unilabos/server/composition.py | 2 - unilabos/server/database/tables/materials.py | 6 +- .../database/tables/runtime/__init__.py | 3 + unilabos/server/services/materials/core.py | 57 +----------------- 9 files changed, 52 insertions(+), 125 deletions(-) diff --git a/docs/developer_guide/databases.md b/docs/developer_guide/databases.md index f36d9911a..25700f012 100644 --- a/docs/developer_guide/databases.md +++ b/docs/developer_guide/databases.md @@ -138,6 +138,12 @@ Uni-Lab-OS 的持久状态放在四个**相互独立的 SQLite 文件**里。本 0.13 发布线是基线:四个库都是 schema v1、`migrations=()`。`tests/server/test_database_schema_versions.py` 把每个库的 `(schema_version, checksum)` 固定在 `PINNED` 里:改了 DDL 或 `contract_version` 而不提升版本,测试失败。 + +**main 发布之前旧库一律重建,不迁移也不修复。** runtime / materials 的 `contract_version` 提到 2 重置了基线 +(设备子树只收格式合规的 PLR 物料等新规则不为旧数据补救):之前的开发库按「库内版本与代码版本相同,但结构指纹不同」 +拒绝启动,设 `database_rebuild_on_mismatch = True` 则备份后重建。只为旧数据存在的修复代码随之删除。 +之后的结构升级改为版本化、Flyway 式的迁移(下面的步骤),在 main 发布后启用。 + 发布后改结构的步骤: 1. 该库 `schema_version` +1; diff --git a/docs/developer_guide/examples/materials_operations_guide.md b/docs/developer_guide/examples/materials_operations_guide.md index 5606de8a0..2c4b726a0 100644 --- a/docs/developer_guide/examples/materials_operations_guide.md +++ b/docs/developer_guide/examples/materials_operations_guide.md @@ -344,9 +344,7 @@ slave→slave、slave→host、host→host 三种形态完全一致。 目标 Site 属于载架(仓库等 PLR `Carrier`)时,权威把物料挂在该库位的 holder 下(与本地整树 `create` 同形,见 2.4),目标设备 load 时经载架放到库位上;不给 Site 直接挂到载架下会被权威拒绝。 -旧版本 transfer 曾把物料直接挂在载架下,这样的树设备反序列化不了:权威打开时 -(`ServerServices.open` → `MaterialsService.repair_site_occupant_parents`)一次性把它们改挂到 -对应 holder 下,账本记一次 `move`,并打印 WARNING。 +旧版本写下的坏树不做修复:main 发布前旧库一律重建(见 `databases.md` 第 4.1 节)。 ## 3. 三种创建来源规范 diff --git a/docs/developer_guide/v1_file_index/scheduler.md b/docs/developer_guide/v1_file_index/scheduler.md index 630dfcbee..9c9c8ec97 100644 --- a/docs/developer_guide/v1_file_index/scheduler.md +++ b/docs/developer_guide/v1_file_index/scheduler.md @@ -83,13 +83,13 @@ DROPPED 的依据分布:#4 / D05(可替换引擎宿主、插件传输与协 | `unilabos/app/scheduler/inventory/resource_graph_bootstrap.py` | 1181 | PORTED | Graph Authority `server/services/materials/graph.py`(`GraphService.upsert_graph(on_existing="adopt")` 发号 / 节点身份对账、`load_graph_payload`、`adopt_graph_payload`)+ 物料权威 `core.py:create_tree` / `apply_snapshot` / `ensure_links` | 已定 #2 / #4:图只认 node-link JSON、经 Graph Authority 落 materials.db;开机图的节点与连线都经 Host 的物料客户端写进持有物料的权威(默认拓扑的 Host 子进程走 HTTP,连线经 `POST /api/v1/materials/links/ensure` 落权威的 `material_link`)。差异:V1 以“来源 + 指纹”一次性导入且已存在时要求同指纹(否则拒绝),dev 以权威为准只补权威缺的节点(adopt);V1 隐式追加 Host 执行器节点、3D 模型渲染快照写入物料 config 未逐项比对 | | `unilabos/app/scheduler/inventory/resource_reference.py` | 108 | PORTED | `materials/core.py:get_material_by_resource_id`(material 的 `resource_id` 列 = 图节点 ID);`runtime/workflow/site_bindings.py:SiteBindingIndex.device` / `owner_ref`(按 uuid 或 resource_id 唯一解析,歧义报错);`run_preflight.py:validate_resource_values`(设备字符串 ID 经权威校验) | V1 给作者源码里的 `resource_ref("业务 ID")` 在编译时解析为物料 UUID / 模板;统一分支编译器没有 `resource_ref()` 帮助函数(属工作流作者区),设备 / 物料按 resource_id 字符串在派发 / 预检时解析 | | `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`、`repair_site_occupant_parents`)+ `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/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/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` 冻结测量前版本;统一分支命令丢弃这些字段,按人工盘点处理。影响:设备计数测量后无法自动修正库存 | -| `unilabos/app/scheduler/inventory/store.py` | 2261 | PORTED | `server/services/materials/store.py`(`MaterialsRepository`)+ `server/database/tables/materials.py`(materials.db 表、触发器,如 `trg_site_occupant_requires_descendant_*`);写锁 / 事务 `MaterialsService.write()`;父关系一致性 `core.py:repair_site_occupant_parents`(`server/composition.py:45` 启动时修复) | 单写者 WAL + 业务 / 账本同事务沿用 dev;V1 的 v1–v17 迁移链属 已定 #8;outbox / sync cursor → materials 账本 `delivery_status` + `acknowledge_changes`;运行时设备模板目录 → dev Registry Authority | +| `unilabos/app/scheduler/inventory/store.py` | 2261 | PORTED | `server/services/materials/store.py`(`MaterialsRepository`)+ `server/database/tables/materials.py`(materials.db 表、触发器,如 `trg_site_occupant_requires_descendant_*`);写锁 / 事务 `MaterialsService.write()` | 单写者 WAL + 业务 / 账本同事务沿用 dev;V1 的 v1–v17 迁移链属 已定 #8;outbox / sync cursor → materials 账本 `delivery_status` + `acknowledge_changes`;运行时设备模板目录 → dev Registry Authority | | `unilabos/app/scheduler/inventory/sync.py` | 282 | PORTED | dev 机制:materials.db `inventory_ledger.delivery_status` + `POST /api/v1/materials/changes/ack`(`MaterialsService.acknowledge_changes`)+ `unilabos/client/host/legacy_adaptor/legacy/sync.py` `LegacyMaterialMirror`(启动全量 + 消费账本的增量推送);只读视图 `/inventory/outbox/*`、`/inventory/sync/cursors`、`/inventory/snapshot` | V1 的 `OutboxWorker` → `POST /edge/sync/events` / `/edge/sync/snapshot` 新云端协议没有实现;但 V1 产品从不传 `sync_sender`(`integration.py` 记 "cloud sync disabled; outbox retained locally",`make_http_sync_sender` 只有测试调用),实际行为没有损失。`CloudProjectionReference` 是云端参考实现,只用于测试 | | `unilabos/app/scheduler/inventory/warehouse.py` | 158 | PORTED | `unilabos/server/services/materials/lab.py` `LabLayout.warehouse` / `zone_storage_summary` / `STORAGE_CLASSES` | 按品类聚合批次、数量、在库实例与库位分布,`storage_class` 取自模板,与 V1 一致;`GET /lab/warehouse`(11-17 起类名 `LabViews`;布局视图里的 `zone_storage_summary` 随布局删除) | | `unilabos/app/scheduler/inventory/workflow_quantity.py` | 1269 | PORTED | `materials/core.py:reserve_task_inventory` / `preview_inventory` / `_plan_inventory` / `_plan_content`;`materials/contents.py:reserve_content` / `finish_content_reservation` / `adjust_consumed_content`(不吃他任务预留、单位换算失败即拒绝);`materials/quantity.py:convert_quantity`;`scheduler/inventory_recovery.py`(孤儿 / 终态对账);读模型 `materials/consumption.py`(task / job / reagent consumptions)、material-events | 对账表 I02(内容物多任务共享、随作业结算与恢复)。`WorkflowQuantityShortageError` 交补料分支、`content_for_material_source` 属 #6,统一分支改为 `plan_not_executable`(scope=task)/ `preflight` 决策(scope=action,`scheduler/service.py:RuntimeInventoryShortage`)。另:V1 任务创建时 `inventory_bindings` 指定的具体试剂 / 内容物与数量参与整任务预留(V1 `workflow/quantity_inventory.py`),统一分支只冻结不消费,见 material_source_resolution 行 | diff --git a/tests/server/test_database_schema_versions.py b/tests/server/test_database_schema_versions.py index 24faab8b6..60406f800 100644 --- a/tests/server/test_database_schema_versions.py +++ b/tests/server/test_database_schema_versions.py @@ -1,19 +1,25 @@ """各库结构指纹与 schema_version 绑定:改了 DDL / contract_version 就必须提升版本并写迁移。 0.13 发布线上四个库都以 v1 为基线(没有迁移);发布前的结构变化直接并进 v1,发布后从 v2 起追加迁移。 +main 发布前 runtime / materials 的 contract_version 提到 2,重置基线:之前的开发库不迁移、不修复,按指纹不符 +拒绝启动(或按 ``database_rebuild_on_mismatch`` 重建)。 """ from __future__ import annotations +import dataclasses + import pytest -from unilabos.server.database import DATABASE_SPECS +from unilabos.config.config import BasicConfig +from unilabos.server.database import DATABASE_SPECS, initialize_database +from unilabos.server.database.schema import DatabaseMigrationRequired #: (schema_version, checksum)。DDL 或 contract_version 变化会改变 checksum: #: 把对应库的 schema_version +1,在其 migrations 里补上迁移,再更新这里。 PINNED = { - "runtime": (1, "188e6daf8617eb453afb4686babedd63d62717fbd6a7f04271f9b11ac158fd6f"), - "materials": (1, "d4d087e28ca32d98ba7c8248da5f57b24523f1b7abd8682024ad3752e0450969"), + "runtime": (1, "bea876e21df263c620db697c4eb74a959bb9b8b4f73866f089a223dfe4b5eb63"), + "materials": (1, "c35dd5def14fe03dcfa7d9355acd0b8d4fb8901b0ba8640fc2c35bae36eaba77"), "telemetry": (1, "a0e00118c131bbae1e4a693563977d7ffff49c17c482ebad0e5ad2b224b548af"), "history": (1, "5005469f86db3fe747ab1f30ea32d0c0c8f2f2779202a81bedb8d8254217f4cc"), } @@ -40,3 +46,27 @@ def test_release_policy_refuses_runtime_and_materials_without_migration() -> Non assert {key: spec.on_unmigratable for key, spec in DATABASE_SPECS.items()} == { "runtime": "refuse", "materials": "refuse", "telemetry": "rebuild", "history": "rebuild", } + + +@pytest.mark.parametrize("key", ["runtime", "materials"]) +def test_a_database_from_before_the_baseline_reset_is_refused_or_rebuilt(tmp_path, monkeypatch, key: str) -> None: + """重置前(contract v1)的开发库:默认拒绝启动、旧库原样保留;允许重建时改名备份后建新库。""" + + spec = DATABASE_SPECS[key] + old = dataclasses.replace(spec, contract_version=1) + path = tmp_path / spec.filename + initialize_database(path, old).close() + monkeypatch.setattr(BasicConfig, "database_rebuild_on_mismatch", False, raising=False) + + with pytest.raises(DatabaseMigrationRequired, match="需要重建"): + initialize_database(path, spec) + assert path.exists() + + monkeypatch.setattr(BasicConfig, "database_rebuild_on_mismatch", True, raising=False) + connection = initialize_database(path, spec) + try: + stored = connection.execute("SELECT checksum FROM schema_identity").fetchone()[0] + finally: + connection.close() + assert stored == spec.checksum + assert list(tmp_path.glob(f"{spec.filename}.bak-*")) diff --git a/tests/server/test_site_holder_placement.py b/tests/server/test_site_holder_placement.py index 389a8869c..619d864cb 100644 --- a/tests/server/test_site_holder_placement.py +++ b/tests/server/test_site_holder_placement.py @@ -177,65 +177,6 @@ def test_deck_sites_without_holders_keep_the_occupant_under_the_deck(authority) assert _site(service, deck_uuid, "T2").occupied_material_uuid == bottle.unilabos_uuid -def _break_like_the_old_transfer(service: MaterialsService, material_uuid: str, site) -> None: - """复现旧版 transfer 写下的坏树:物料直接挂在仓库下,并占用仓库的 Site。""" - - with service.write(): - service.connection.execute( - "UPDATE material SET parent_material_uuid=? WHERE material_uuid=?", - (site.owner_material_uuid, material_uuid), - ) - service.connection.execute( - "UPDATE site SET occupied_material_uuid=? WHERE site_uuid=?", - (material_uuid, site.site_uuid), - ) - - -def test_existing_bad_trees_are_repaired_once_when_the_authority_opens(tmp_path) -> None: - from unilabos.server.composition import ServerServices - from unilabos.server.database import ServerDatabasePaths - - paths = ServerDatabasePaths.resolve(tmp_path) - service = MaterialsService(paths.materials_db) - gateway = LocalMaterialsClient(service) - try: - warehouse = _warehouse(gateway) - deck_uuid = str(uuid4()) - materials.ensure(site_deck(deck_uuid, "Bench_Deck", ("T1",)), gateway=gateway) - bottle = materials.create(_bottle("broken"), gateway=gateway) - on_deck = materials.create(_bottle("deck_bottle"), gateway=gateway) - service.move_material( - _mutation("move_material"), - MaterialMove(material_uuid=on_deck.unilabos_uuid, destination_site_uuid=_site(service, deck_uuid, "T1").site_uuid), - ) - _break_like_the_old_transfer(service, bottle.unilabos_uuid, _site(service, warehouse.unilabos_uuid, "A02")) - with pytest.raises(TypeError, match="ResourceHolder"): - materials.get(warehouse.unilabos_uuid, gateway=gateway).to_plr_resources() - holder_name = warehouse["A02"].name - deck_version = service.get_material(on_deck.unilabos_uuid).material.version - finally: - service.close() - - services = ServerServices.open(paths) - try: - service = services.materials - assert _shape(service, warehouse.unilabos_uuid) == { - "A01": ("wh_local", warehouse["A01"].name), - "A02": ("broken", holder_name), - } - assert [change.operation for change in service.changes(limit=10_000) - if change.aggregate_uuid == bottle.unilabos_uuid][-1] == "move" - restored = materials.get(warehouse.unilabos_uuid, gateway=LocalMaterialsClient(service)).to_plr_resources()[0] - assert restored["A02"].resource.name == "broken" - # 台面型 Site 的占用物料不是坏树,不动 - assert service.get_material(on_deck.unilabos_uuid).material.version == deck_version - assert service.get_material(on_deck.unilabos_uuid).material.parent_material_uuid == deck_uuid - # 幂等:再修一次什么也不做 - assert service.repair_site_occupant_parents() == [] - finally: - services.close() - - def test_physical_move_off_a_warehouse_site_finds_the_site_through_the_holder(authority) -> None: """调度的物理搬运合同:来源库位在载架上、物料挂在 holder 下,也要找到来源并结算。""" diff --git a/unilabos/server/composition.py b/unilabos/server/composition.py index 1740dacf5..7e8822058 100644 --- a/unilabos/server/composition.py +++ b/unilabos/server/composition.py @@ -38,8 +38,6 @@ def open(cls, paths: ServerDatabasePaths) -> "ServerServices": opened.append(runtime) materials = MaterialsService(paths.materials_db) opened.append(materials) - # 旧版 transfer 把载架 Site 的物料直接挂在载架下,设备反序列化不了:打开时一次性修复 - materials.repair_site_occupant_parents() telemetry = TelemetryService(paths.telemetry_db) opened.append(telemetry) history = HistoryService(paths.history_db) diff --git a/unilabos/server/database/tables/materials.py b/unilabos/server/database/tables/materials.py index b294f600b..93f5b8e85 100644 --- a/unilabos/server/database/tables/materials.py +++ b/unilabos/server/database/tables/materials.py @@ -1729,9 +1729,11 @@ class InventoryProcessedCommandRecord(TableObject, table=True): role="resource, material, site, topology link and lab graph authority", synchronous="FULL", tables=MATERIALS_TABLES, - # 0.13 发布线的基线:schema v1、contract v1,没有迁移。之后改 DDL 或行内容契约 + # 0.13 发布线的基线:schema v1,没有迁移。之后改 DDL 或行内容契约 # (contract_version)时提升 schema_version 并在 migrations 里补 v2 起的迁移。 - contract_version=1, + # contract 2:main 发布前重置基线(设备子树只收格式合规的 PLR 物料、旧数据不做修复), + # 之前的开发库按指纹不符拒绝启动或按 database_rebuild_on_mismatch 重建。 + contract_version=2, schema_version=1, migrations=(), # 物料是实验室的物理事实:结构或契约变化必须 schema_version +1 并给出迁移。 diff --git a/unilabos/server/database/tables/runtime/__init__.py b/unilabos/server/database/tables/runtime/__init__.py index 13f0edd4e..c40684361 100644 --- a/unilabos/server/database/tables/runtime/__init__.py +++ b/unilabos/server/database/tables/runtime/__init__.py @@ -116,6 +116,9 @@ # 0.13 发布线的基线:schema v1,没有迁移。发布前的结构变化直接并进 v1 基线;发布后改 DDL / # contract_version 时提升 schema_version、在 migrations 里补 v2 起的迁移,并把 v1 的结构指纹 # 登记进 released_checksums。 + # contract 2:main 发布前重置基线(设备子树只收格式合规的 PLR 物料、旧数据不做修复), + # 之前的开发库按指纹不符拒绝启动或按 database_rebuild_on_mismatch 重建。 + contract_version=2, schema_version=1, migrations=(), # 工作流定义、任务与注册表记录:结构变化必须带迁移。没有迁移路径时拒绝启动、保留旧库; diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index 551244ba1..2bdaa74a2 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -34,7 +34,6 @@ from unilabos.protocol.base import canonical_hash from unilabos.protocol.materials import AggregatePrecondition, AggregateVersion, InventoryChange, InventoryMutation, MutationResult from unilabos.protocol.materials import ( - ACTOR_BACKEND, ChemicalSummary, InventoryAllocation, InventoryLotCorrection, @@ -3100,8 +3099,8 @@ def _site_holder_uuids( ``holder.location`` 生成 Site 位姿)。权威里按同一结构识别,规则全部满足才算: - 所属物料不是设备,至少有一个 Site; - - 直接子物料里,除去占着它自己 Site 的(台面型 Site 的物料直接挂在台面下, - 旧版 transfer 的坏树也是这样)和 ``exclude``(正在移动的物料),剩下的与 + - 直接子物料里,除去占着它自己 Site 的(台面型 Site 的物料直接挂在台面下) + 和 ``exclude``(正在移动的物料),剩下的与 Site 一一对应:数量相同,按顺序第 k 个子物料对应第 k 个 Site; - 每个这样的子物料没有自己的 Site、最多一个子物料,且位置就是对应 Site 的位置。 @@ -3173,52 +3172,6 @@ def site_parent_material_uuid( return holders[site.site_uuid] return site.owner_material_uuid - def repair_site_occupant_parents(self) -> list[str]: - """一次性修复旧版 transfer 写下的坏树,返回改挂的物料 uuid。 - - 旧版 move / transfer 把载架型 Site 的占用物料直接挂在载架下(应挂在该 Site 的 - holder 下):设备反序列化时载架拒收物料,快照也改不了占用物料的父节点。权威 - 打开时(``ServerServices.open``)把这样的物料原位改挂到 holder 下,Site 占用 - 不变,账本记一次 ``move``。没有坏树时只做一次查询,可重复调用。 - """ - - from unilabos.utils.log import logger - - rows = self.connection.execute( - """ - SELECT site.site_uuid, site.occupied_material_uuid - FROM site JOIN material ON material.material_uuid = site.occupied_material_uuid - WHERE site.deleted_at_ms IS NULL AND material.deleted_at_ms IS NULL - AND material.parent_material_uuid = site.owner_material_uuid - ORDER BY site.owner_material_uuid, site.ordinal - """ - ).fetchall() - repaired: list[str] = [] - for site_uuid, material_uuid in rows: - site = self.get_site(site_uuid) - if site is None: - continue - parent_uuid = self.site_parent_material_uuid(site, moving_material_uuid=material_uuid) - if parent_uuid == site.owner_material_uuid: - continue - command_uuid = str(uuid4()) - self.move_material( - InventoryMutation( - command_uuid=command_uuid, - effect_key=f"repair_site_occupant_parent:{command_uuid}", - operation="move_material", - actor_type=ACTOR_BACKEND, - actor_uuid="materials-repair", - ), - MaterialMove(material_uuid=material_uuid, destination_site_uuid=site_uuid), - ) - logger.warning( - f"[物料权威] 修复旧版 transfer 的坏树:物料 {material_uuid} 从载架 " - f"{site.owner_material_uuid} 改挂到 Site {site.label} 的 holder {parent_uuid}" - ) - repaired.append(material_uuid) - return repaired - def assert_site_accepts(self, site: SiteRecord, *, template_uuid: str, template_name: str) -> None: """一件该模板的物料能否放进空库位:模板白名单(``site_template``,6008)与活动入口预留。""" @@ -3397,7 +3350,7 @@ def _apply_material_move( and destination is not None and source.site_uuid == destination.site_uuid ) - if same_site and material.parent_material_uuid == parent_uuid: + if same_site: raise MaterialNoChangeError("material is already at destination") if ( source is None @@ -3456,10 +3409,6 @@ def _apply_material_move( "version": material.version + 1, } ) - if same_site: - # 原位换父(修复旧版坏树:物料从载架改挂到 Site 的 holder 下)。触发器要求 - # 先解除占用再改父;同一事务内随后重新占用,Site 版本照常 +1。 - self.clear_site_occupants([destination.site_uuid]) self.update_material(updated_material) if destination is not None: From 022bda54a5256a1385403c9a05d177e2539d08c6 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:18:04 +0800 Subject: [PATCH 29/59] fix(materials): check config.type format and PLR key uniqueness on every write path The authority only checked that config.type was a non-empty string, and only on create and move. A V1 PUT /materials/{id} config without type, a patch, or a device snapshot could drop or blank the type of a material a device holds, and a PLR key that clashed with another one in the same tree was committed, then failed the Host's local load. One check (_assert_plr_tree_rules) now runs on the final state of every write that changes a material's parent or config: create_tree (after its placement, plus every device the new tree contains), move and transfer (and so instantiate, material.io and placements), patch_material (and so V1 PUT) and apply_snapshot. apply_delta changes neither parent nor config. A PLR tree is what one device holds (sub-devices hold their own) or the whole tree of a root material that is not under a device: - every material a device holds carries a well-formed config.type: a Python identifier, the PLR class name. Missing, blank or malformed is rejected with 1000. Whether the class exists is left to the Host, which can see driver packages the authority cannot; - PLR keys (config.name) are unique within the tree; a clash is an identity conflict naming the key and the materials. --- .../test_materials_device_subtree_plr_only.py | 162 +++++++++++++++++- unilabos/server/services/materials/core.py | 120 +++++++++---- 2 files changed, 245 insertions(+), 37 deletions(-) diff --git a/tests/server/test_materials_device_subtree_plr_only.py b/tests/server/test_materials_device_subtree_plr_only.py index 318d26b3c..f43e663bc 100644 --- a/tests/server/test_materials_device_subtree_plr_only.py +++ b/tests/server/test_materials_device_subtree_plr_only.py @@ -1,9 +1,9 @@ -"""设备子树只收 PLR 物料(权威在每一次落位上把关)。 +"""设备持有的物料只收格式合规的 PLR 物料,一棵 PLR 树里 PLR 键不重复(权威在每一条写路径上把关)。 设备启动时按 ``ResourceTreeSet`` 把设备子树整棵反序列化成 PLR 实例,靠每个节点的 -``config.type``(PLR 自己的类型名)找类。只有身份的物料(网关手写、模板实例化不了)一旦挂进 -设备子树,设备重启就起不来;所以 move / transfer / 结算 / 设备挂载 / 建树即落位都走 -``_apply_material_move`` 的同一道检查,在落位时就拒绝。 +``config.type``(PLR 自己的类型名)找类,PLR 还要求一棵树里名字唯一。权威只核对格式(Python 标识符 +形式的类名),不判断类是否存在(类不存在由 Host 发现,那台设备进入维护模式)。建树即落位、move / +transfer、patch config(含 V1 PUT)与设备快照都按写入后的最终状态走同一道检查。 """ from __future__ import annotations @@ -18,14 +18,16 @@ MaterialIdentityWrite, MaterialMove, MaterialNodeCreate, + MaterialPatch, MaterialPlacement, + MaterialSnapshot, MaterialTreeCreate, ResourceTemplateWrite, ) from unilabos.resources.adapters.device_site import apply_device_authority_state from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance from unilabos.server.services.materials import MaterialsService -from unilabos.server.services.materials.core import MaterialValidationError +from unilabos.server.services.materials.core import MaterialConflictError, MaterialValidationError DEVICE_TEMPLATE = "plr_only_test_device" @@ -86,14 +88,19 @@ def device(service): } -def _node(ref: str, *, plr_type: str | None, parent_ref: str | None = None) -> MaterialNodeCreate: +def _node( + ref: str, *, plr_type: str | None, parent_ref: str | None = None, plr_name: str | None = None +) -> MaterialNodeCreate: + config: dict = {"type": plr_type} if plr_type else {} + if plr_name: + config["name"] = plr_name return MaterialNodeCreate( client_ref=ref, parent_client_ref=parent_ref, identity=MaterialIdentityWrite( resource_id=f"{ref}-{uuid4().hex[:8]}", template_name="sample_tpl", - config={"type": plr_type} if plr_type else {}, + config=config, ), ) @@ -123,7 +130,7 @@ def test_identity_only_material_cannot_be_placed_on_a_device_site(service, devic def test_identity_only_material_cannot_be_mounted_on_the_device_itself(service, device) -> None: bare = _create(service, _node("bare", plr_type=None)) - with pytest.raises(MaterialValidationError, match="只收 PLR 物料"): + with pytest.raises(MaterialValidationError, match="config.type"): _move(service, bare, parent_material_uuid=device["uuid"]) @@ -229,3 +236,142 @@ def test_create_and_place_on_a_device_site_commits_plr_trees(service, device) -> sites = {site.label: site for site in service.get_material(device["uuid"]).sites} assert sites["s2"].occupied_material_uuid == plate assert service.get_material(plate).material.parent_material_uuid == device["uuid"] + + +def _on_device(service, device, site: str = "s1", **node) -> str: + return _create( + service, + _node("plate", **{"plr_type": "Plate", **node}), + placement=MaterialPlacement(parent_material_uuid=device["uuid"], site=device["sites"][site]), + ) + + +@pytest.mark.parametrize("config", [{"note": "edited"}, {"type": ""}, {"type": " "}, {"type": "Not a class"}]) +def test_patch_cannot_drop_or_break_config_type_on_a_device(service, device, config) -> None: + plate = _on_device(service, device) + before = service.get_material(plate).material + + with pytest.raises(MaterialValidationError, match="config.type"): + service.patch_material(_mutation("patch_material"), plate, MaterialPatch(config=config)) + + after = service.get_material(plate).material + assert after.config == before.config and after.version == before.version + + +def test_patch_with_a_well_formed_but_unknown_type_is_left_to_the_host(service, device) -> None: + """权威只核对格式:类是否存在由 Host 在设备启动时判断(不存在时那台设备进入维护模式)。""" + + plate = _on_device(service, device) + + service.patch_material(_mutation("patch_material"), plate, MaterialPatch(config={"type": "NotAPlrClass"})) + + assert service.get_material(plate).material.config["type"] == "NotAPlrClass" + + +def test_patch_outside_device_subtrees_is_not_restricted(service) -> None: + loose = _create(service, _node("loose", plr_type="Plate")) + + service.patch_material(_mutation("patch_material"), loose, MaterialPatch(config={"note": "edited"})) + + assert "type" not in service.get_material(loose).material.config + + +def test_v1_put_config_cannot_drop_config_type_inside_a_device(service, device) -> None: + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from unilabos.server.api.materials import install_materials_api + + plate = _on_device(service, device) + app = FastAPI() + install_materials_api(app, service) + with TestClient(app) as client: + response = client.put(f"/api/v1/materials/{plate}", json={"config": {"note": "edited"}}) + + assert response.json()["code"] == 1000 + assert "config.type" in str(response.json()) + assert service.get_material(plate).material.config["type"] == "Plate" + + +def test_create_on_a_device_site_rejects_a_malformed_type(service, device) -> None: + before = len(service.list_materials()) + + with pytest.raises(MaterialValidationError, match="config.type"): + _on_device(service, device, plr_type="plate type") + + assert len(service.list_materials()) == before + + +def test_snapshot_cannot_drop_config_type_inside_a_device(service, device) -> None: + plate = _on_device(service, device) + node = service.get_tree(plate).nodes[0] + observed = node.model_copy(update={"material": node.material.model_copy(update={"config": {"note": "x"}})}) + + with pytest.raises(MaterialValidationError, match="config.type"): + service.apply_snapshot( + _mutation("apply_material_snapshot"), + MaterialSnapshot(root_material_uuid=plate, nodes=[observed]), + ) + + assert service.get_material(plate).material.config["type"] == "Plate" + + +# ── 一棵 PLR 树里 PLR 键唯一 ───────────────────────────────────── + + +def test_create_onto_a_device_rejects_a_plr_key_already_held_by_that_device(service, device) -> None: + _on_device(service, device, site="s1", plr_name="other") + before = len(service.list_materials()) + + with pytest.raises(MaterialConflictError, match="other"): + _on_device(service, device, site="s2", plr_name="other") + + assert len(service.list_materials()) == before + sites = {site.label: site for site in service.get_material(device["uuid"]).sites} + assert sites["s2"].occupied_material_uuid is None + + +def test_the_same_plr_key_on_different_devices_is_fine(service, device) -> None: + other_uuid = str(uuid4()) + config = ResourceDictInstance(ResourceDict.model_validate({ + "id": "plr-only-other", "uuid": other_uuid, "name": "plr-only-other", "type": "device", + "class": DEVICE_TEMPLATE, "template_name": DEVICE_TEMPLATE, "config": {}, "data": {}, "extra": {}, + "sites": None, "sites_initialized": False, + })) + apply_device_authority_state(config, {"available_sites": [{"index": 1, "label": "o1"}]}, DEVICE_TEMPLATE, + gateway=LocalMaterialsClient(service)) + _on_device(service, device, plr_name="shared") + + _create( + service, + _node("plate", plr_type="Plate", plr_name="shared"), + placement=MaterialPlacement(parent_material_uuid=other_uuid), + ) + + +def test_move_into_a_tree_that_already_uses_the_plr_key_is_rejected(service) -> None: + rack = _create( + service, + _node("rack", plr_type="TubeRack", plr_name="rack"), + _node("tube", plr_type="Tube", parent_ref="rack", plr_name="tube_1"), + ) + loose = _create(service, _node("loose", plr_type="Tube", plr_name="tube_1")) + + with pytest.raises(MaterialConflictError, match="tube_1"): + _move(service, loose, parent_material_uuid=rack) + + assert service.get_material(loose).material.parent_material_uuid is None + + +def test_a_tree_created_with_duplicate_plr_keys_is_rejected(service) -> None: + before = len(service.list_materials()) + + with pytest.raises(MaterialConflictError, match="A1"): + _create( + service, + _node("rack", plr_type="TubeRack", plr_name="rack-dup"), + _node("t1", plr_type="Tube", parent_ref="rack", plr_name="A1"), + _node("t2", plr_type="Tube", parent_ref="rack", plr_name="A1"), + ) + + assert len(service.list_materials()) == before diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index 2bdaa74a2..a444e73d3 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -2723,14 +2723,22 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: for node in value.nodes if node.parent_client_ref is None ) - # 设备连同下挂物料一起建(开机图对齐):与挂进设备子树同一条规则 - self._assert_device_subtree_accepts(client_map[root_ref], client_map[root_ref]) if value.placement is not None: placed = self._place_created_root( mutation, client_map[root_ref], value.placement, timestamp ) affected.extend(placed.affected) sequences.extend(placed.sequences) + # 落位之后按最终位置核对:新树所在的 PLR 树,以及新树里每台设备(开机图对齐时 + # 设备连同下挂物料一起建)各自持有的那一棵 + self._assert_plr_tree_rules([ + client_map[root_ref], + *( + client_map[node.client_ref] + for node in value.nodes + if node.identity.resource_type == "device" + ), + ]) tree = self.get_tree(client_map[root_ref], client_ref_map=client_map) return _Applied(data=tree, affected=affected, sequences=sequences) @@ -2910,6 +2918,8 @@ def apply(timestamp: int) -> _Applied[MaterialAggregateRead]: } ) self.update_material(updated) + if "config_json" in changes: + self._assert_plr_tree_rules([material_uuid]) aggregate = self.get_material(material_uuid) sequence = self._ledger( mutation, @@ -3208,49 +3218,94 @@ def _device_ancestor(self, material_uuid: Optional[str]) -> Optional[MaterialRec cursor = record.parent_material_uuid return None - def _assert_device_subtree_accepts(self, material_uuid: str, parent_uuid: Optional[str]) -> None: - """设备子树只收 PLR 物料:设备启动时按 ``ResourceTreeSet`` 把整棵子树反序列化成 PLR 实例。 + def _plr_tree_root(self, material_uuid: str) -> Optional[MaterialRecord]: + """物料所在 PLR 树的根:最近的设备(物料自己是设备时就是它),不在设备下时是顶层根物料。""" + + cursor, seen, found = material_uuid, set(), None + while cursor is not None and cursor not in seen: + seen.add(cursor) + record = MaterialsRepository.get_material(self, cursor) + if record is None: + break + found = record + if record.resource_type == "device": + break + cursor = record.parent_material_uuid + return found + + def _assert_plr_tree_rules(self, material_uuids: Sequence[str]) -> None: + """写入改了父物料或 config 之后,按最终状态核对物料所在 PLR 树的两条规则。 + + PLR 树是一台设备持有的物料(不含设备本身,子设备各管自己的一棵),或一个不在设备下的根物料的 + 整棵树。设备启动时按 ``ResourceTreeSet`` 把它反序列化成 PLR 实例,所以: - 新父物料是设备或设备的后代时,挂进来的整棵树里每个物料节点都要有 ``config.type`` - (PLR 自己的类型名,反序列化靠它找类);子设备本身不受限。只有身份的物料(网关手写、 - 模板实例化不了)在这里被拒绝,而不是等设备重启时整台设备起不来。 + - 设备持有的物料都要带格式合规的 ``config.type``:Python 标识符形式的 PLR 类名(如 ``Plate``)。 + 权威不判断这个类是否存在(外部驱动包的类权威看不到);类不存在由 Host 在设备启动时发现, + 那台设备进入维护模式。缺失、空白或不是类名一律拒绝(1000),而不是等设备重启时才起不来; + - 一棵 PLR 树里 PLR 键(``config.name``)不重复:PLR 自己要求整棵树里名字唯一,权威放行了重名, + Host 本地加载就会失败,两边从此对不上。物料 ``name`` 是 uuid,本来就唯一,这里查的是 PLR 键。 + + 建树(含落位)、move / transfer / 实例化 / material.io、patch config(含 V1 PUT)与设备快照都经这里; + 设备增量(apply_delta)只改内容 / 位姿 / 库位元数据,不改父物料和 config,不受影响。 """ - device = self._device_ancestor(parent_uuid) - if device is None: - return + roots: dict[str, MaterialRecord] = {} + for material_uuid in material_uuids: + root = self._plr_tree_root(material_uuid) + if root is not None: + roots.setdefault(root.material_uuid, root) + for root in roots.values(): + self._check_plr_tree(root) + + def _check_plr_tree(self, root: MaterialRecord) -> None: rows = self.connection.execute( """ - WITH RECURSIVE subtree(material_uuid) AS ( - SELECT ? + WITH RECURSIVE tree(material_uuid, resource_type) AS ( + SELECT material_uuid, resource_type FROM material WHERE material_uuid = ? UNION ALL - SELECT m.material_uuid FROM material m - JOIN subtree s ON m.parent_material_uuid = s.material_uuid + SELECT m.material_uuid, m.resource_type FROM material m + JOIN tree t ON m.parent_material_uuid = t.material_uuid WHERE m.deleted_at_ms IS NULL + AND (t.resource_type <> 'device' OR t.material_uuid = ?) ) - SELECT m.resource_id, m.resource_type, m.config_json - FROM material m JOIN subtree s ON m.material_uuid = s.material_uuid + SELECT m.material_uuid, m.resource_id, m.resource_type, m.config_json + FROM material m JOIN tree USING (material_uuid) """, - (material_uuid,), + (root.material_uuid, root.material_uuid), ).fetchall() - missing: list[str] = [] - for resource_id, resource_type, config_json in rows: + held_by_device = root.resource_type == "device" + malformed: list[str] = [] + keys: dict[str, list[str]] = {} + for material_uuid, resource_id, resource_type, config_json in rows: if resource_type == "device": continue try: config = json.loads(config_json or "{}") except (TypeError, ValueError): config = {} - plr_type = config.get("type") if isinstance(config, dict) else None - if not isinstance(plr_type, str) or not plr_type.strip(): - missing.append(str(resource_id)) - if missing: - shown = "、".join(missing[:5]) + (f" 等 {len(missing)} 个" if len(missing) > 5 else "") + config = config if isinstance(config, dict) else {} + plr_type = config.get("type") + if held_by_device and not (isinstance(plr_type, str) and plr_type.isidentifier()): + shown_type = "缺少 config.type" if plr_type in (None, "") else f"config.type={plr_type!r}" + malformed.append(f"{resource_id}({material_uuid},{shown_type})") + key = plr_key(config) + if key: + keys.setdefault(key, []).append(str(material_uuid)) + if malformed: + shown = "、".join(malformed[:5]) + (f" 等 {len(malformed)} 个" if len(malformed) > 5 else "") raise MaterialValidationError( - f"设备 {device.resource_id} 的子树只收 PLR 物料:{shown} 没有 config.type" - "(PLR 类型名),设备启动时无法反序列化。请按注册表资源类经 materials.create" - "(ResourceTreeSet)创建物料再放上设备", - subject="material", + f"设备 {root.resource_id} 持有的物料必须带格式合规的 config.type(PLR 类名,Python 标识符," + f"如 Plate):{shown}。设备启动时按它反序列化物料;请按注册表资源类经 materials.create" + "(ResourceTreeSet)创建物料,或改正 config.type", + ) + duplicated = {key: uuids for key, uuids in keys.items() if len(uuids) > 1} + if duplicated: + key, uuids = next(iter(sorted(duplicated.items()))) + owner = f"设备 {root.resource_id}" if held_by_device else f"根物料 {root.resource_id}" + raise MaterialConflictError( + f"{owner} 的 PLR 树里 PLR 键 config.name={key!r} 重复(物料 {'、'.join(uuids)}):" + "PLR 要求一棵树里的名字唯一,请换一个名字", + conflict="identity", ) def _assert_no_parent_cycle(self, material_uuid: str, parent_uuid: Optional[str]) -> None: @@ -3358,7 +3413,6 @@ def _apply_material_move( and material.parent_material_uuid == parent_uuid ): raise MaterialNoChangeError("material is already at destination") - self._assert_device_subtree_accepts(value.material_uuid, parent_uuid) affected: list[AggregateVersion] = [] sequences: list[int] = [] @@ -3410,6 +3464,7 @@ def _apply_material_move( } ) self.update_material(updated_material) + self._assert_plr_tree_rules([value.material_uuid]) if destination is not None: destination_changed_at = max(timestamp, destination.updated_at_ms) @@ -4173,6 +4228,13 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: current_record, updated_record, ) + # 设备快照同样不能去掉 / 写坏 config.type 或造出重名的 PLR 键 + self._assert_plr_tree_rules([ + material_uuid + for material_uuid, (before, after) in changed_material_records.items() + if before.config_json != after.config_json + or before.parent_material_uuid != after.parent_material_uuid + ]) changed_site_records: dict[str, tuple[SiteRecord, SiteRecord]] = {} for site_uuid in sorted(changed_site_uuids): From 60dc1b9455a7a7fd6d517e86bc97d0e279cdfc7e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:34:06 +0800 Subject: [PATCH 30/59] fix(host): a device whose materials cannot be built enters maintenance mode An unknown config.type made require_plr_config_type raise inside the driver creator and took the device (on HostLink: the whole startup) down, while a material without config.type was silently cut off and later moved out of the device subtree in the authority. Every driver creator now builds the device's material subtrees first (build_device_materials). If one cannot be built (missing or malformed type, unknown class, deserialization error) it raises DeviceMaterialError naming the material uuid and its config.type, and the device enters maintenance mode, reusing the unavailable-device mechanism HostLink already has for backend-unsupported devices: the device and its sub-devices do not start, the Host and the other devices start normally, and the record (with maintenance, material_uuid, material_type and a reason naming the device) reaches the capability snapshot, GET /api/v1/devices (unavailable) and /api/v1/health. ROS 2's HostNode records the same entry. The built instances are reused when the driver is attached, so nothing is deserialized twice. The silent split (split_plr_material_tree) and the legacy detach that moved such materials out of the device in the authority (tracker.legacy_material_uuids, DeviceNode._detach_legacy_materials) only served old databases, which are now rebuilt, and are removed. --- docs/developer_guide/api_v1_migration.md | 5 +- docs/developer_guide/networking_overview.md | 9 +- .../test_device_material_maintenance.py | 141 ++++++++++++++++++ .../test_attach_legacy_non_plr_children.py | 137 ----------------- .../runtime/test_legacy_material_detach.py | 98 ------------ .../client/host/hostlink/local_runtime.py | 3 +- .../client/host/hostlink/main_hostlink_run.py | 45 ++++-- .../client/host/ros2/presets/host_node.py | 16 +- .../client/host/runtime/driver_creator.py | 89 ++++++----- unilabos/client/host/runtime/exception.py | 37 +++++ unilabos/client/host/runtime/node.py | 27 ---- unilabos/resources/resource_tracker.py | 52 ------- unilabos/server/services/runtime/devices.py | 2 +- 13 files changed, 286 insertions(+), 375 deletions(-) create mode 100644 tests/client/host/hostlink/test_device_material_maintenance.py delete mode 100644 tests/client/host/runtime/test_attach_legacy_non_plr_children.py delete mode 100644 tests/client/host/runtime/test_legacy_material_detach.py diff --git a/docs/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index 4db785faa..d6401daf6 100644 --- a/docs/developer_guide/api_v1_migration.md +++ b/docs/developer_guide/api_v1_migration.md @@ -55,8 +55,9 @@ `starting` / `failed`)、`capabilities`、`phase`、`workflowRuntime`、可选 `observability`;dev 的探针摘要 `scheduler`(`local` / `remote`)、`execution`、`reasons` 作为扩展字段保留,dev 原来的 `not_ready` 状态改为 V1 的 `starting`。health 的 `scheduler` 按 V1 为 `ready` / `disabled`,dev 的本机 / 远端归属改名 `scheduler_mode`, - `execution` 保留;dev 扩展 `unavailable_devices` 列出设备图里有、但当前 backend 跑不了而没有启动的设备 - (`device_id` / `registry_name` / `backend` / `reason` / `supported_backends`),分进程时经控制面读 Host。 + `execution` 保留;dev 扩展 `unavailable_devices` 列出设备图里有、但没有启动的设备:当前 backend 跑不了的 + (`device_id` / `registry_name` / `backend` / `reason` / `supported_backends`),以及持有的物料建不成 PLR 实例而 + 进入维护模式的(另有 `maintenance: true` / `material_uuid` / `material_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 f5987f1c1..d74a20510 100644 --- a/docs/developer_guide/networking_overview.md +++ b/docs/developer_guide/networking_overview.md @@ -198,7 +198,14 @@ ActionClient、规划场景、RViz、依赖 ROS graph/TF 的功能,以及 ROS2 (`edge_status: "unavailable"`,`unavailable` 字段写明原因与支持的 backend;设备目录与在线列表 都不把它算作在线)、运行预检、`/api/v1/hostlink/peers` 与 `/api/v1/health` 的 `unavailable_devices` 中。注册表缺失、模板名非法等配置错误仍让启动失败。Slave 上跳过的设备 -目前只写 Slave 自己的日志。工作站和 +目前只写 Slave 自己的日志。 + +设备持有的物料建不成 PLR 实例(缺 / 写错 `config.type`、类不存在、反序列化失败)时,这台设备进入 +**维护模式**:同一套不可用记录,只是不启动的原因不同。构造驱动之前先把它持有的每棵物料子树建一遍 +(`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 下使用 相同的设备初始化路径。 diff --git a/tests/client/host/hostlink/test_device_material_maintenance.py b/tests/client/host/hostlink/test_device_material_maintenance.py new file mode 100644 index 000000000..00d100fc9 --- /dev/null +++ b/tests/client/host/hostlink/test_device_material_maintenance.py @@ -0,0 +1,141 @@ +"""设备持有的物料建不成 PLR 实例时,这台设备进入维护模式:不启动,Host 与其余设备照常运行。 + +权威只核对 ``config.type`` 的格式;类是否存在、能否反序列化只有 Host 知道。建不成(缺 / 写错 +``config.type``、类不存在、反序列化失败)不再跳过那棵物料让设备照常起来,而是这台设备不启动,原因 +(设备、物料 uuid、``config.type``)登记为不可用设备,随能力快照到 ``GET /api/v1/devices``, +并出现在 ``/api/v1/health`` 里。 +""" + +from __future__ import annotations + +from types import SimpleNamespace +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.client.host.runtime.driver_creator import build_device_materials +from unilabos.client.host.runtime.exception import DeviceMaterialError +from unilabos.registry.registry import lab_registry +from unilabos.resources.resource_tracker import ResourceTreeSet +from unilabos.server.services.materials.graph import graph_resource_tree +from tests.plr_fixtures import plate + +MODULE = __name__ + + +class PlainDriver: + def __init__(self, device_id: str = "", **_kwargs) -> None: + self.device_id = device_id + + +@pytest.fixture +def registry(monkeypatch): + monkeypatch.setitem(lab_registry.device_type_registry, "test_holder", { + "class": {"module": f"{MODULE}:PlainDriver", "type": "python"}}) + # 不接物料权威:设备的子树就是图里给的 + monkeypatch.setattr(definition_module, "apply_device_authority_state", lambda *args, **kwargs: None) + + +def _device(device_id: str, parent: str | None = None) -> dict: + return {"id": device_id, "uuid": str(uuid4()), "type": "device", "class": "test_holder", + "template_name": "test_holder", "parent": parent, "config": {}} + + +def _plate_nodes(name: str, device: dict, *, break_with=None) -> list[dict]: + nodes = ResourceTreeSet.from_plr_resources([plate(name)], known_random_uuid=True).dump()[0] + nodes[0]["parent_uuid"] = device["uuid"] + if break_with is not None: + break_with(nodes) + return nodes + + +def _unknown_class(nodes: list[dict]) -> None: + nodes[0]["config"]["type"] = "NotAPlrClass" + + +def _missing_type_on_a_well(nodes: list[dict]) -> None: + nodes[5]["config"].pop("type") + + +def _well_without_location(nodes: list[dict]) -> None: + nodes[5]["pose"]["position"] = None + + +def _graph(*groups: list[dict]): + return graph_resource_tree([node for group in groups for node in group]) + + +@pytest.mark.parametrize( + "break_with, named_node, shown_type", + [(_unknown_class, 0, "NotAPlrClass"), (_missing_type_on_a_well, 5, None), (_well_without_location, 0, "Plate")], +) +def test_only_the_device_with_a_bad_material_stays_down(registry, break_with, named_node, shown_type) -> None: + bad, good = _device("heater_bad"), _device("heater_ok") + child = _device("heater_bad_probe", parent="heater_bad") + bad_nodes = _plate_nodes("bad_plate", bad, break_with=break_with) + devices = _graph([bad, child, good], bad_nodes, _plate_nodes("good_plate", good)) + + runtime = populate_runtime(HostLinkLocalRuntime(), devices) + runtime.start() + try: + assert set(runtime.devices) == {"heater_ok"} + assert [res.name for res in runtime.devices["heater_ok"].resource_tracker.resources] == ["good_plate"] + record = runtime.unavailable_devices["heater_bad"] + assert record["maintenance"] is True + assert record["material_uuid"] == bad_nodes[named_node]["uuid"] + assert record["material_type"] == shown_type + assert "heater_bad" in record["reason"] and bad_nodes[named_node]["uuid"] in record["reason"] + # 子设备没有宿主,一并不启动 + assert runtime.unavailable_devices["heater_bad_probe"]["parent_device_id"] == "heater_bad" + finally: + runtime.stop() + + +def test_build_names_the_material_and_its_type() -> None: + device = _device("holder") + tree = _graph([device], _plate_nodes("p", device, break_with=_unknown_class)).trees[0] + + with pytest.raises(DeviceMaterialError) as caught: + build_device_materials(tree.root_node.children) + + assert caught.value.material_type == "NotAPlrClass" + assert "NotAPlrClass" in str(caught.value) + + +def test_the_maintenance_record_reaches_the_device_catalog_route() -> None: + from unilabos.client.host.capabilities import build_endpoint_capabilities + + error = DeviceMaterialError(material_uuid="m-1", material_type="Typo", reason="类不存在", device_id="heater") + adapter = SimpleNamespace( + devices_names={}, _action_value_mappings={}, + unavailable_devices={"heater": {"device_id": "heater", "registry_name": "test_holder", **error.unavailable_record()}}, + ) + + routes, _capabilities = build_endpoint_capabilities(adapter, observed_at_ms=1) + + route = next(route for route in routes if route.device_uuid == "heater") + assert route.enabled is False + assert route.config["unavailable"]["maintenance"] is True + assert route.config["unavailable"]["material_uuid"] == "m-1" + assert "Typo" in route.config["unavailable"]["reason"] + + +def test_health_lists_the_device_in_maintenance(registry, monkeypatch) -> None: + 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 + + bad = _device("heater_bad") + runtime = populate_runtime(HostLinkLocalRuntime(), _graph([bad], _plate_nodes("p", bad, break_with=_unknown_class))) + 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"] == "heater_bad" and record["maintenance"] is True + assert record["material_type"] == "NotAPlrClass" diff --git a/tests/client/host/runtime/test_attach_legacy_non_plr_children.py b/tests/client/host/runtime/test_attach_legacy_non_plr_children.py deleted file mode 100644 index 53c801bd4..000000000 --- a/tests/client/host/runtime/test_attach_legacy_non_plr_children.py +++ /dev/null @@ -1,137 +0,0 @@ -"""设备初始化拿到的子树先拆一遍:旧数据里的非 PLR 物料拆下来点名报错,其余照常初始化。 - -权威已在落位时拒绝新的非 PLR 物料进入设备子树;这里只处理升级前留下的旧数据(如旧版虚拟加热 -平台经网关手写、没有 ``config.type`` 的样品)——以前它让设备在重启时直接起不来。拆的粒度是节点: -台面上放着一个旧物料时,台面(连同其它 PLR 物料)仍和设备一起初始化,比如液体工作站构造时 -要带上的 deck。 -""" - -from __future__ import annotations - -import logging -from typing import Any -from uuid import uuid4 - -from pylabrobot.resources import Resource - -from unilabos.client.host.runtime.driver_creator import DeviceClassCreator, PyLabRobotCreator -from unilabos.resources.resource_tracker import ( - DeviceNodeResourceTracker, - ResourceDict, - ResourceDictInstance, - ResourceTreeInstance, - ResourceTreeSet, - split_plr_material_tree, -) -from tests.plr_fixtures import SiteDeck, site_deck - - -class _Driver: - def __init__(self, **_kwargs) -> None: - pass - - -class _Handler: - """构造时要带上 deck 的驱动(液体工作站的形状)。""" - - def __init__(self, deck: Any = None, **_kwargs) -> None: - self.deck = deck - - -def _legacy_node(device_uuid: str, *, parent_uuid: str | None = None, uuid: str | None = None) -> dict: - return { - "id": "legacy_bottle", - "uuid": uuid or str(uuid4()), - "name": "legacy_bottle", - "type": "container", - "class": "Resource", - "template_name": "legacy_bottle", - "parent_uuid": parent_uuid or device_uuid, - "config": {}, - "data": {"volume_ml": 5}, - "extra": {}, - } - - -def _deck_with_legacy_occupant(device_uuid: str) -> tuple[ResourceDictInstance, str, str]: - """T1 上一个 PLR 盒子、T2 上一个旧版非 PLR 物料的台面(挂在设备下)。""" - - deck_uuid = str(uuid4()) - deck = site_deck(deck_uuid, "bench_deck", ("T1", "T2")) - box = Resource("keep_box", size_x=20, size_y=20, size_z=20) - box.unilabos_uuid = str(uuid4()) - deck.assign_child_resource(box, spot=0) - dumped = ResourceTreeSet.from_plr_resources([deck], known_random_uuid=True).dump()[0] - dumped[0]["parent_uuid"] = device_uuid - legacy_uuid = str(uuid4()) - dumped.append(_legacy_node(device_uuid, parent_uuid=deck_uuid, uuid=legacy_uuid)) - for site in dumped[0]["sites"]: - if site["label"] == "T2": - site["occupied_material_uuid"] = legacy_uuid - tree = ResourceTreeSet.load([dumped]).trees[0] - return tree.root_node, box.unilabos_uuid, legacy_uuid - - -def test_split_keeps_the_plr_part_and_frees_the_legacy_site() -> None: - device_uuid = str(uuid4()) - root, box_uuid, legacy_uuid = _deck_with_legacy_occupant(device_uuid) - - kept, pruned = split_plr_material_tree(root) - - assert [content.uuid for content in pruned] == [legacy_uuid] - assert kept is not None - assert [node.res_content.uuid for node in kept.children] == [box_uuid] - sites = {site.label: site.occupied_material_uuid for site in kept.res_content.sites} - assert sites == {"T1": box_uuid, "T2": None} - # 输入不改:拆的是副本 - assert len(root.children) == 2 - # 剩下的部分能按 PLR 反序列化 - (deck,) = ResourceTreeSet([ResourceTreeInstance(kept)]).to_plr_resources() - assert [child.name for child in deck.children] == ["keep_box"] - - -def test_split_returns_plr_trees_unchanged() -> None: - root, _box, _legacy = _deck_with_legacy_occupant(str(uuid4())) - kept, _pruned = split_plr_material_tree(root) - - again, pruned = split_plr_material_tree(kept) - - assert again is kept and pruned == [] - - -def test_attach_skips_only_the_legacy_nodes(caplog) -> None: - device_uuid = str(uuid4()) - deck, box_uuid, legacy_uuid = _deck_with_legacy_occupant(device_uuid) - loose = ResourceDictInstance(ResourceDict.model_validate(_legacy_node(device_uuid))) - tracker = DeviceNodeResourceTracker() - creator = DeviceClassCreator(_Driver, [deck, loose], tracker) - - with caplog.at_level(logging.ERROR): - creator.create_instance({}) - - assert deck.res_content.uuid in tracker.uuid_to_resources - assert box_uuid in tracker.uuid_to_resources - assert legacy_uuid not in tracker.uuid_to_resources - assert loose.res_content.uuid not in tracker.uuid_to_resources - messages = [record.getMessage() for record in caplog.records] - assert sum("legacy_bottle" in message for message in messages) == 2 - - -def test_device_built_with_its_deck_still_initializes_when_a_legacy_material_sits_on_it(caplog) -> None: - """液体工作站的形状:deck 是构造参数,台面上的旧物料拆下来,设备与台面照常初始化。""" - - device_uuid = str(uuid4()) - deck, box_uuid, legacy_uuid = _deck_with_legacy_occupant(device_uuid) - tracker = DeviceNodeResourceTracker() - creator = PyLabRobotCreator(_Handler, [deck], tracker) - - with caplog.at_level(logging.ERROR): - handler = creator.create_instance( - {"deck": {"_resource_child_name": "bench_deck", "_resource_type": "tests.plr_fixtures:SiteDeck"}} - ) - - assert handler is not None and isinstance(handler.deck, SiteDeck) - assert [child.name for child in handler.deck.children] == ["keep_box"] - assert handler.deck.unilabos_uuid == deck.res_content.uuid - assert box_uuid in tracker.uuid_to_resources and legacy_uuid not in tracker.uuid_to_resources - assert any("legacy_bottle" in record.getMessage() for record in caplog.records) diff --git a/tests/client/host/runtime/test_legacy_material_detach.py b/tests/client/host/runtime/test_legacy_material_detach.py deleted file mode 100644 index 34d363e9b..000000000 --- a/tests/client/host/runtime/test_legacy_material_detach.py +++ /dev/null @@ -1,98 +0,0 @@ -"""初始化时拆下的非 PLR 物料在权威里移出设备子树,这棵树之后的严格快照照常对得上。 - -升级前的旧数据里,PLR 物料下面可能挂着没有 ``config.type`` 的物料。设备初始化把它从本地树拆掉; -权威那棵树里若还挂着它,本地树与权威永远对不上,严格快照(观察者的整树提交)全被拒,这棵树上的 -状态变化都会丢。节点拿到物料服务时把拆下的各枝移成独立根物料,两边重新一致。 -""" - -from __future__ import annotations - -from uuid import uuid4 - -from pylabrobot.resources import Coordinate, Resource - -from unilabos.client.host.hostlink.local_runtime import HostLinkDriverSpec, HostLinkLocalRuntime -from unilabos.client.host.runtime.resource import AuthorityResourceService -from unilabos.client.materials import LocalMaterialsClient -from unilabos.resources import materials -from unilabos.resources.adapters.device_site import apply_device_authority_state -from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance -from unilabos.server.services.materials import MaterialsService -from tests.plr_fixtures import plate - -DEVICE_TEMPLATE = "legacy_detach_test_device" - - -class _Device: - def __init__(self, **_kwargs) -> None: - pass - - -def _device_config(device_uuid: str, gateway) -> ResourceDictInstance: - config = ResourceDictInstance( - ResourceDict.model_validate( - { - "id": "placer", "uuid": device_uuid, "name": "placer", "type": "device", - "class": DEVICE_TEMPLATE, "template_name": DEVICE_TEMPLATE, - "config": {}, "data": {}, "extra": {}, "sites": None, "sites_initialized": False, - } - ) - ) - apply_device_authority_state( - config, {"available_sites": [{"index": 1, "label": "slot_a"}]}, DEVICE_TEMPLATE, gateway=gateway - ) - return config - - -def _start(device_uuid: str, gateway) -> tuple[HostLinkLocalRuntime, object]: - runtime = HostLinkLocalRuntime() - node = runtime.add_driver( - HostLinkDriverSpec( - "placer", _Device, {}, resource_uuid=device_uuid, device_config=_device_config(device_uuid, gateway) - ) - ) - runtime.set_resource_service(AuthorityResourceService(gateway)) - runtime.start() - return runtime, node - - -def test_a_legacy_child_is_moved_out_so_its_tree_snapshots_strictly_again(tmp_path) -> None: - service = MaterialsService(tmp_path / "materials.db") - gateway = LocalMaterialsClient(service) - device_uuid = str(uuid4()) - try: - runtime, node = _start(device_uuid, gateway) - holder = Resource("holder", size_x=300, size_y=100, size_z=10, category="container") - holder.assign_child_resource(plate("keep"), location=Coordinate(0, 0, 0)) - holder.assign_child_resource( - Resource("legacy", size_x=10, size_y=10, size_z=10, category="container"), - location=Coordinate(200, 0, 0), - ) - created = materials.create(holder, node=node, site="slot_a", gateway=gateway) - holder_uuid = created.unilabos_uuid - legacy_uuid = next(child.unilabos_uuid for child in created.children if child.name == "legacy") - runtime.stop() - # 升级前留下的行:没有 config.type - with service.write(): - service.connection.execute( - "UPDATE material SET config_json=json_remove(config_json,'$.type') WHERE material_uuid=?", - (legacy_uuid,), - ) - - runtime, node = _start(device_uuid, gateway) - try: - local_holder = node.resource_tracker.uuid_to_resources[holder_uuid] - assert legacy_uuid not in node.resource_tracker.uuid_to_resources - assert node.resource_tracker.legacy_material_uuids == [] - # 权威里它已是独立根物料,holder 那棵树与本地一致 - assert service.get_material(legacy_uuid).material.parent_material_uuid is None - assert legacy_uuid not in { - item.material.material_uuid for item in service.get_tree(holder_uuid).nodes - } - AuthorityResourceService(gateway)._update_sync( - "placer", device_uuid, local_holder, allow_partial=False, conflict_retries=1 - ) - finally: - runtime.stop() - finally: - service.close() diff --git a/unilabos/client/host/hostlink/local_runtime.py b/unilabos/client/host/hostlink/local_runtime.py index e2a7a17f3..60a9665b1 100644 --- a/unilabos/client/host/hostlink/local_runtime.py +++ b/unilabos/client/host/hostlink/local_runtime.py @@ -1260,7 +1260,8 @@ def __init__(self) -> None: #: 图中声明的 host_node 身份(device_id -> 资源 uuid),供内置 host #: 服务设备注册时复用,保证图导出与权威身份一致。 self.graph_host_resource_uuids: dict[str, str] = {} - #: 设备图中因 backend 不支持而跳过的设备(device_id -> 原因记录), + #: 设备图中没有启动的设备(device_id -> 原因记录):backend 不支持而跳过的,以及持有的物料 + #: 建不成 PLR 实例而进入维护模式的(记录带 ``maintenance`` / ``material_uuid`` / ``material_type``); #: 由能力快照、``/api/v1/hostlink/peers`` 与 ``/api/v1/health`` 上报。 self.unavailable_devices: dict[str, dict[str, Any]] = {} self.topic_bus = LocalTopicBus() diff --git a/unilabos/client/host/hostlink/main_hostlink_run.py b/unilabos/client/host/hostlink/main_hostlink_run.py index ff9e5a585..74f680271 100644 --- a/unilabos/client/host/hostlink/main_hostlink_run.py +++ b/unilabos/client/host/hostlink/main_hostlink_run.py @@ -10,7 +10,7 @@ iter_device_config_entries, resolve_device_definition, ) -from unilabos.client.host.runtime.exception import DeviceBackendUnsupported +from unilabos.client.host.runtime.exception import DeviceBackendUnsupported, DeviceMaterialError from unilabos.client.host.hostlink.backend import HostLinkBackend from unilabos.client.host.hostlink.local_runtime import ( HostLinkDriverSpec, @@ -99,22 +99,35 @@ def populate_runtime( parent_device_id=entry.parent_device_id, ) continue - runtime.add_driver( - HostLinkDriverSpec( - device_id=device_id, - driver_class=definition.driver_class, - config=definition.runtime_config, + try: + runtime.add_driver( + HostLinkDriverSpec( + device_id=device_id, + driver_class=definition.driver_class, + config=definition.runtime_config, + registry_name=definition.registry_name, + display_name=definition.display_name, + resource_uuid=definition.resource_uuid, + action_names=tuple(definition.action_value_mappings), + action_value_mappings=definition.action_value_mappings, + status_names=tuple(definition.status_types), + device_config=node, + parent_device_id=entry.parent_device_id, + hardware_interface=definition.hardware_interface, + ) + ) + except DeviceMaterialError as exc: + # 维护模式:持有的物料建不成 PLR 实例,这台设备不启动(子设备随之跳过),其余照常 + exc.device_id = device_id + record = exc.unavailable_record() + _mark_unavailable( + runtime, + device_id, registry_name=definition.registry_name, - display_name=definition.display_name, - resource_uuid=definition.resource_uuid, - action_names=tuple(definition.action_value_mappings), - action_value_mappings=definition.action_value_mappings, - status_names=tuple(definition.status_types), - device_config=node, + reason=record.pop("reason"), parent_device_id=entry.parent_device_id, - hardware_interface=definition.hardware_interface, + extra=record, ) - ) return runtime @@ -126,12 +139,14 @@ def _mark_unavailable( reason: str, supported_backends: Optional[list[str]] = None, 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) @@ -147,7 +162,7 @@ def _mark_unavailable( def unavailable_devices() -> list[dict[str, Any]]: - """本进程 HostLink runtime 因 backend 不支持而跳过的设备(供诊断 / 健康接口)。""" + """本进程 HostLink runtime 没有启动的设备(backend 不支持、物料建不成时的维护模式;供诊断 / 健康接口)。""" runtime = _runtime local = getattr(runtime, "local", None) diff --git a/unilabos/client/host/ros2/presets/host_node.py b/unilabos/client/host/ros2/presets/host_node.py index f2df41b88..60e0566f7 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 +from unilabos.client.host.runtime.exception import DeviceClassInvalid, DeviceMaterialError from unilabos.client.host.runtime.host_adapter import ( HostAdapterBase, execution_result_bridges, @@ -508,7 +508,10 @@ def unavailable_devices(self) -> Dict[str, Dict[str, Any]]: from unilabos.server.services.device_processes import managed_device_unavailability - return managed_device_unavailability() + records = managed_device_unavailability() + # 持有的物料建不成 PLR 实例、进入维护模式的本机设备 + records.update(self.__dict__.get("_maintenance_devices") or {}) + return records def _hostlink_liveness_callback(self) -> None: """按 HostLink 连接状态更新 Slave 设备的在线状态。 @@ -684,6 +687,15 @@ def initialize_device(self, device_id: str, device_config: ResourceDictInstance) 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 if d is None: diff --git a/unilabos/client/host/runtime/driver_creator.py b/unilabos/client/host/runtime/driver_creator.py index 6d34b0eef..e3c40b8c7 100644 --- a/unilabos/client/host/runtime/driver_creator.py +++ b/unilabos/client/host/runtime/driver_creator.py @@ -15,12 +15,13 @@ from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar from unilabos.client.host.runtime.async_utils import schedule_async_func +from unilabos.client.host.runtime.exception import DeviceMaterialError from unilabos.resources.resource_tracker import ( DeviceNodeResourceTracker, ResourceDictInstance, ResourceTreeInstance, ResourceTreeSet, - split_plr_material_tree, + require_plr_config_type, ) from unilabos.utils import logger from unilabos.utils.cls_creator import create_instance_from_config @@ -35,43 +36,41 @@ def create_instance(self, *args: Any, **kwargs: Any) -> T: raise NotImplementedError -def _plr_children( - device_cls: Type[Any], - children: List[ResourceDictInstance], - resource_tracker: Optional[DeviceNodeResourceTracker] = None, -) -> List[ResourceDictInstance]: - """设备初始化拿到的子树先拆一遍:每棵物料子树只留能按 PLR 反序列化的部分。 - - 挂载用的物料、构造设备要一起带上的物料(液体工作站的台面、工作站的 deck)都从这里取, - 同一套拆法。拆下来的非 PLR 物料(升级前遗留,没有 ``config.type``)连同挂在它下面的物料 - 不挂到设备本地,逐个点名报错;整台设备照常初始化。子设备由它自己的构造器处理,不在这里拆。 +def build_device_materials(children: List[ResourceDictInstance]) -> Dict[str, Any]: + """把设备持有的每棵物料子树建成 PLR 实例,返回 ``{子树根 uuid: 实例}``;建不成就抛错。 - 拆下的各枝记在 ``resource_tracker.legacy_material_uuids``:节点拿到物料服务时把它们在权威里 - 移出设备子树(成为独立根物料)。否则权威的树里还挂着它们,与本地树永远对不上,这棵树的 - 严格快照全被拒,设备运行中的状态变化(体积、枪头……)都会丢。 + 设备持有的物料只收 PLR 物料(权威核对 ``config.type`` 的格式);类是否存在、能否反序列化只有 + Host 知道。任何一棵建不成(缺 / 写错 ``config.type``、类不存在、反序列化失败)都抛 + :class:`DeviceMaterialError`:这台设备进入维护模式、不启动,Host 与其余设备照常运行。没有 + 「跳过建不成的物料、设备照常启动」的退路。``config.type`` 的问题指名到那个物料;反序列化失败 + 指名到那棵子树的根,附 PLR 的报错。子设备由它自己的构造器处理。 """ - device_name = getattr(device_cls, "__name__", str(device_cls)) - result: List[ResourceDictInstance] = [] + built: Dict[str, Any] = {} for child in children: if child.res_content.type == "device": - result.append(child) continue - tree, pruned = split_plr_material_tree(child) - for content in pruned: - logger.error( - "设备 %s 下的物料 %s(%s)不是 PLR 物料(没有 config.type),连同挂在它下面的物料" - "没有挂到设备本地,并会在权威里移出设备子树(成为独立根物料);请按注册表资源类经 " - "materials.create 重新创建它,再删除这条旧物料", - device_name, - content.id, - content.uuid, - ) - if resource_tracker is not None and content.uuid: - resource_tracker.legacy_material_uuids.append(str(content.uuid)) - if tree is not None: - result.append(tree) - return result + for node in ResourceTreeInstance(child).get_all_nodes(): + content = node.res_content + if content.type == "device": + continue + config = content.config if isinstance(content.config, dict) else {} + try: + require_plr_config_type(config, uuid=content.uuid, template_name=content.template_name) + except ValueError as exc: + raise DeviceMaterialError( + material_uuid=content.uuid, material_type=config.get("type"), reason=str(exc) + ) from exc + root = child.res_content + try: + built[str(root.uuid or "")] = ResourceTreeSet([ResourceTreeInstance(child)]).to_plr_resources()[0] + except Exception as exc: # noqa: BLE001 - 任何反序列化错误都让设备进入维护模式 + raise DeviceMaterialError( + material_uuid=root.uuid, + material_type=(root.config or {}).get("type"), + reason=f"{type(exc).__name__}: {exc}", + ) from exc + return built class DeviceClassCreator(Generic[T]): @@ -82,11 +81,24 @@ def __init__( cls: Type[T], children: List[ResourceDictInstance], resource_tracker: DeviceNodeResourceTracker, + *, + built: Optional[Dict[str, Any]] = None, ) -> None: self.device_cls = cls self.device_instance: Optional[T] = None self.resource_tracker = resource_tracker - self.children = _plr_children(cls, children, resource_tracker) + self.children = list(children) + # 构造驱动之前先把持有的物料整棵建一遍:建不成时设备不启动(维护模式)。建好的实例 + # 挂载时直接用,不再建第二份;``built`` 是外层构造器(工作站建 deck)已经建好的那一份。 + self._built = built if built is not None else build_device_materials(self.children) + + def _plr_instance(self, child: ResourceDictInstance) -> Any: + """子树根的 PLR 实例:构造时建好的那一份(只用一次),用过之后再要就现建。""" + + instance = self._built.pop(str(child.res_content.uuid or ""), None) + if instance is None: + instance = ResourceTreeSet([ResourceTreeInstance(child)]).to_plr_resources()[0] + return instance def attach_resource(self) -> None: if self.device_instance is None: @@ -98,8 +110,7 @@ def attach_resource(self) -> None: # 再实例化一份会让同一权威物料有两个实例,uuid 索引指向驱动手里没有的副本。 if str(child.res_content.uuid or "") in self.resource_tracker.uuid_to_resources: continue - resource = ResourceTreeSet([ResourceTreeInstance(child)]).to_plr_resources()[0] - self.resource_tracker.add_resource(resource) + self.resource_tracker.add_resource(self._plr_instance(child)) def create_instance(self, data: Dict[str, Any]) -> T: self.device_instance = create_instance_from_config( @@ -129,8 +140,9 @@ def __init__( resource_tracker: DeviceNodeResourceTracker, *, task_scheduler: Optional[TaskScheduler] = None, + built: Optional[Dict[str, Any]] = None, ) -> None: - super().__init__(cls, children, resource_tracker) + super().__init__(cls, children, resource_tracker, built=built) self.task_scheduler = task_scheduler self.has_deserialize = hasattr(cls, "deserialize") and callable( getattr(cls, "deserialize") @@ -181,9 +193,7 @@ def _process_resource_references( ) return resource try: - resource_instance: Resource = ResourceTreeSet( - [ResourceTreeInstance(resource)] - ).to_plr_resources()[0] + resource_instance: Resource = self._plr_instance(resource) states[prefix_path] = resource_instance.serialize_all_state() if to_dict: return resource_instance.serialize() @@ -390,6 +400,7 @@ def create_instance(self, data: Dict[str, Any]) -> T: self.children, self.resource_tracker, task_scheduler=self.task_scheduler, + built=self._built, ).create_instance(deck_data) else: params["deck"] = None diff --git a/unilabos/client/host/runtime/exception.py b/unilabos/client/host/runtime/exception.py index e258fc03a..d74b93cf9 100644 --- a/unilabos/client/host/runtime/exception.py +++ b/unilabos/client/host/runtime/exception.py @@ -32,6 +32,43 @@ def __init__( ) +class DeviceMaterialError(DeviceClassInvalid): + """设备持有的物料建不成 PLR 实例(缺 / 写错 ``config.type``、类不存在、反序列化失败)。 + + 设备进入维护模式:这台设备不启动,Host 照常运行、其余设备照常启动;原因(设备、物料 uuid、 + ``config.type``)登记为不可用设备,经能力快照到达 ``GET /api/v1/devices``。构造器不知道设备 id, + 由启动设备的一方补上 ``device_id``。 + """ + + def __init__(self, *, material_uuid: Any, material_type: Any, reason: str, device_id: str = "") -> None: + self.material_uuid = str(material_uuid or "") + self.material_type = material_type + self.reason = str(reason) + self.device_id = str(device_id or "") + super().__init__(self.reason) + + def __str__(self) -> str: + device = f"设备 {self.device_id} " if self.device_id else "设备" + return ( + f"{device}持有的物料 {self.material_uuid}(config.type={self.material_type!r})" + f"建不成 PLR 实例,设备进入维护模式:{self.reason}" + ) + + def unavailable_record(self) -> Dict[str, Any]: + """不可用设备记录里的维护模式字段(与 backend 不支持等原因同一份记录)。""" + + return { + "maintenance": True, + "reason": str(self), + "material_uuid": self.material_uuid, + "material_type": ( + self.material_type + if self.material_type is None or isinstance(self.material_type, str) + else repr(self.material_type) + ), + } + + class ActionTimeoutBase(RuntimeError): """``@action`` 超时闸门触发时由执行面构造的异常基类。 diff --git a/unilabos/client/host/runtime/node.py b/unilabos/client/host/runtime/node.py index 290d7b217..bb64ab15e 100644 --- a/unilabos/client/host/runtime/node.py +++ b/unilabos/client/host/runtime/node.py @@ -162,33 +162,6 @@ def set_resource_service(self, service: "ResourceService") -> None: observer.set_service(service) self.__dict__["_material_snapshot_observer"] = observer observer.observe_all(list(tracker.resources)) - self._detach_legacy_materials(service, tracker) - - def _detach_legacy_materials(self, service: Any, tracker: Any) -> None: - """初始化时拆下的非 PLR 物料在权威里移出设备子树(移成独立根物料,释放占着的库位)。 - - 本地树已经没有它们;权威那棵树里若还挂着,两边永远对不上,这棵树的严格快照全被拒。 - 移成功的从待办里去掉;失败的留着报错,下次拿到物料服务时再试。设备构造期就可能走到这里 - (ROS 2 节点在 ``Node.__init__`` 之前设物料服务),所以用模块 logger。 - """ - - from unilabos.utils import logger - - pending = getattr(tracker, "legacy_material_uuids", None) - move = getattr(service, "move_resource_sync", None) - if not pending or not callable(move): - return - for material_uuid in list(pending): - try: - move(str(self.device_id), str(self.resource_uuid or ""), material_uuid, parent_material_uuid=None) - except Exception as exc: # noqa: BLE001 - 失败只影响这棵树的快照,设备照常运行 - logger.error( - f"设备 {self.device_id} 的非 PLR 物料 {material_uuid} 没能移出设备子树({exc});" - "在它被移走或删除之前,它所在那棵树的快照会被权威拒绝" - ) - continue - pending.remove(material_uuid) - logger.warning(f"设备 {self.device_id} 的非 PLR 物料 {material_uuid} 已在权威里移出设备子树,成为独立根物料") def _invalidate_material_baselines(self) -> None: """权威侧结构已变(下行投影 / 挂载):本地缓存的根树基线作废,下次 flush 重拉一次。""" diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index 7201a4aaf..639ad375b 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -1779,55 +1779,6 @@ def load(cls, data: List[List[Dict[str, Any]]]) -> "ResourceTreeSet": return cls(trees) -def split_plr_material_tree( - root: ResourceDictInstance, -) -> Tuple[Optional[ResourceDictInstance], List[ResourceDict]]: - """把一棵物料树拆成能按 PLR 反序列化的部分与拆下来的非 PLR 物料,不改输入。 - - 设备子树只收 PLR 物料(权威在每次落位时拒绝新的),升级前的旧数据里仍可能挂着没有 - ``config.type`` 的物料:它连同挂在它下面的物料整枝拆下,其余照常反序列化——比如液体工作站 - 的台面上放着一个旧物料时,台面仍和设备一起初始化。父物料库位上指向被拆物料的占用在副本里 - 清空(权威不动)。设备节点不拆。 - - 返回 ``(剩下的树, 拆下的各枝的根)``:没有要拆的时原样返回输入;根本身不是 PLR 物料时剩下的树 - 为 None。 - """ - - def is_plr(node: ResourceDictInstance) -> bool: - content = node.res_content - return content.type == "device" or bool( - str((content.config or {}).get("type") or "").strip() - ) - - pruned: List[ResourceDict] = [] - dropped: set[str] = set() - - def visit(node: ResourceDictInstance, inside_pruned: bool) -> None: - if not inside_pruned and not is_plr(node): - pruned.append(node.res_content) - inside_pruned = True - if inside_pruned: - dropped.add(str(node.res_content.uuid)) - for child in node.children: - visit(child, inside_pruned) - - visit(root, False) - if not pruned: - return root, [] - if str(root.res_content.uuid) in dropped: - return None, pruned - kept = [] - for node in ResourceTreeInstance(root).get_all_nodes(): - if str(node.res_content.uuid) in dropped: - continue - dumped = node.res_content.model_dump(by_alias=True) - for site in dumped.get("sites") or []: - if site.get("occupied_material_uuid") in dropped: - site["occupied_material_uuid"] = None - kept.append(dumped) - return ResourceTreeSet.load([kept]).trees[0].root_node, pruned - - def prepare_resource_creation_payloads( resources: List[Dict[str, Any]], ) -> Tuple[ResourceTreeSet, List[Dict[str, Any]]]: @@ -2056,9 +2007,6 @@ def __init__(self): self.uuid_to_resources: Dict[str, Any] = {} self._names: Dict[str, List[Any]] = {} self._parents: Dict[int, Any] = {} - #: 设备初始化时从子树拆下、还没在权威里移出设备子树的非 PLR 物料(各枝的根 uuid); - #: 节点拿到物料服务时逐个移出(见 ``DeviceNode.set_resource_service``) - self.legacy_material_uuids: List[str] = [] # ── 索引维护 ────────────────────────────────────────────── diff --git a/unilabos/server/services/runtime/devices.py b/unilabos/server/services/runtime/devices.py index 4349d185f..9cc814b8e 100644 --- a/unilabos/server/services/runtime/devices.py +++ b/unilabos/server/services/runtime/devices.py @@ -104,7 +104,7 @@ def endpoint_of(self, material: Mapping[str, Any]) -> Optional[Dict[str, Any]]: return None def unavailable(self, material: Mapping[str, Any]) -> Optional[Dict[str, Any]]: - """Host 因 backend 不支持而跳过的设备:停用 route 上的原因记录;正常设备为 None。""" + """Host 没有启动的设备(backend 不支持、物料建不成时的维护模式):停用 route 上的原因记录;正常设备为 None。""" identities = self._identities(material) for endpoint in self.endpoints: From 659096d9e29567e0a960490e81e314d8707ea9fd Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:34:14 +0800 Subject: [PATCH 31/59] fix(devices): heater barcodes cannot collide across devices, and a taken identity moves to the next number Barcodes were OPENLAB-HEAT--[-]: heater's second sample on site 1 and heater-1's sample on site 2 were both OPENLAB-HEAT-heater-1-2. The authority's unique barcode index rejected the create, nothing retried, and heat_site(1) kept failing with "site 1 has no heating sample". The barcode is now OPENLAB-HEAT-, and the resource_id -sample-[-] already reads back unambiguously: only the site and the number follow the last "-sample-". When the authority still rejects the identity as a conflict, the heater tries the next number (bounded). --- .../devices/test_virtual_heating_platform.py | 64 ++++++++++++++- unilabos/devices/virtual/heating_platform.py | 78 +++++++++++-------- 2 files changed, 109 insertions(+), 33 deletions(-) diff --git a/tests/devices/test_virtual_heating_platform.py b/tests/devices/test_virtual_heating_platform.py index 9db55e51e..451492c30 100644 --- a/tests/devices/test_virtual_heating_platform.py +++ b/tests/devices/test_virtual_heating_platform.py @@ -155,7 +155,7 @@ def test_heater_creates_plr_samples_on_its_own_sites_and_heats_them(heater) -> N assert sample.material.template_name == SAMPLE_TEMPLATE assert sample.material.resource_id == f"heater-demo-sample-{index}" assert sample.material.display_name == f"加热样品 {index}" - assert sample.material.barcode == f"OPENLAB-HEAT-heater-demo-{index}" + assert sample.material.barcode == f"OPENLAB-HEAT-heater-demo-sample-{index}" assert sample.material.meta_data["display_color"] == SAMPLE_DISPLAY_COLORS[index - 1] # uuid → 实例唯一:驱动拿着的就是设备 tracker 登记的那一份 instance = tracker.uuid_to_resources[sample.material.material_uuid] @@ -267,7 +267,7 @@ def test_an_emptied_site_gets_a_new_sample_without_touching_the_one_that_left(he fresh = heater.sites()["site_1"].occupied_material_uuid assert fresh and fresh != moved and result["material_uuid"] == fresh sample = heater.service.get_material(fresh).material - assert (sample.resource_id, sample.barcode) == ("heater-demo-sample-1-2", "OPENLAB-HEAT-heater-demo-1-2") + assert (sample.resource_id, sample.barcode) == ("heater-demo-sample-1-2", "OPENLAB-HEAT-heater-demo-sample-1-2") assert heater.service.get_material(fresh).data.data["temperature_c"] == 50.0 # 移走的那个原样留着 left = heater.service.get_material(moved).material @@ -294,6 +294,66 @@ def test_two_heaters_in_one_lab_each_get_their_samples(tmp_path, monkeypatch) -> service.close() +def _move_off(service: MaterialsService, material_uuid: str) -> None: + from unilabos.protocol.materials import InventoryMutation, MaterialMove + + command = str(uuid4()) + service.move_material( + InventoryMutation(command_uuid=command, effect_key=f"move_material:{command}", operation="move_material", + actor_type="human", actor_uuid="test"), + MaterialMove(material_uuid=material_uuid, parent_material_uuid=None), + ) + + +def test_heaters_whose_ids_extend_each_other_never_share_a_barcode(tmp_path, monkeypatch) -> None: + """``heater`` 工位 1 补的第 2 个样品与 ``heater-1`` 工位 2 的样品,旧格式下条码都是 ``…-heater-1-2``。""" + + service = MaterialsService(tmp_path / "materials.db") + monkeypatch.setattr(BasicConfig, "is_host_mode", True) + set_materials_gateway(LocalMaterialsClient(service)) + plain, suffixed = _Heater(service, "heater"), _Heater(service, "heater-1") + try: + platform = plain.start() + suffixed.start() + _move_off(service, plain.sites()["site_1"].occupied_material_uuid) + + result = platform.heat_site( + site_id=1, target_temperature_c=50.0, duration_seconds=0.1, action_context=ActionContext(action_id="refill") + ) + + refill = service.get_material(result["material_uuid"]).material + assert refill.resource_id == "heater-sample-1-2" + barcodes = [item.material.barcode for item in service.list_materials() if item.material.barcode] + assert len(barcodes) == len(set(barcodes)) == 7 + finally: + suffixed.stop() + plain.stop() + set_materials_gateway(None) + service.close() + + +def test_a_taken_barcode_moves_the_new_sample_to_the_next_number(heater) -> None: + """权威拒绝新样品的身份(条码已被别的物料用了)时换下一个序号,而不是工位一直空着。""" + + from pylabrobot.resources.barcode import Barcode + + from unilabos.resources import materials + from tests.plr_fixtures import plate + + platform = heater.start() + _move_off(heater.service, heater.sites()["site_1"].occupied_material_uuid) + squatter = plate("squatter") + squatter.barcode = Barcode(data="OPENLAB-HEAT-heater-demo-sample-1-2", symbology="CODE128", position_on_resource="front") + materials.create(squatter, gateway=heater.gateway) + + result = platform.heat_site( + site_id=1, target_temperature_c=40.0, duration_seconds=0.1, action_context=ActionContext(action_id="next") + ) + + sample = heater.service.get_material(result["material_uuid"]).material + assert (sample.resource_id, sample.barcode) == ("heater-demo-sample-1-3", "OPENLAB-HEAT-heater-demo-sample-1-3") + + def test_heater_needs_its_device_node() -> None: with pytest.raises(RuntimeError, match="post_init"): VirtualHeatingPlatform("orphan-heater").initialize() diff --git a/unilabos/devices/virtual/heating_platform.py b/unilabos/devices/virtual/heating_platform.py index 480e82a6a..64d5b4c84 100644 --- a/unilabos/devices/virtual/heating_platform.py +++ b/unilabos/devices/virtual/heating_platform.py @@ -95,6 +95,10 @@ def _site_label(site_id: int) -> str: return f"site_{site_id}" +#: 新样品身份被占用时最多换几次序号 +_IDENTITY_ATTEMPTS = 10 + + @resource( # 注册表 AST 扫描只认字面量:与 SAMPLE_TEMPLATE 保持一致 id="virtual_heating_sample", @@ -393,30 +397,32 @@ def _refresh_sites(self) -> None: ) @not_action - def _sample_identity(self, site_id: int) -> tuple[str, str]: - """新样品的 resource_id 与条码,两者在未删除的物料里都要唯一。 - - 按设备与工位区分(同一实验室的第二台加热平台不和第一台撞条码)。工位原来的样品被移走 - 但还在(或升级时被移出设备子树的旧样品)时,``<设备>-sample-<工位>`` 已被占用:加序号 - ``-2``、``-3``……建一个新样品,不去动那一个。 + def _sample_identity(self, site_id: int, *, after: int = 0) -> tuple[str, str, int]: + """新样品的 resource_id、条码与序号;两者在未删除的物料里都要唯一。 + + resource_id 是 ``<设备>-sample-<工位>``,第 2 个起加序号 ``-2``、``-3``……;条码是 + ``OPENLAB-HEAT-``。``-sample-`` 之后只有工位号与序号两段数字,从最后一个 + ``-sample-`` 切开就能还原设备 id,所以不同设备拼不出同一个条码(``heater`` 工位 1 的第 2 个是 + ``OPENLAB-HEAT-heater-sample-1-2``,``heater-1`` 工位 2 是 ``OPENLAB-HEAT-heater-1-sample-2``)。 + 工位原来的样品被移走但还在时它的 resource_id 已被占用:从 ``after`` 之后取第一个空着的序号, + 建一个新样品,不去动那一个。 """ - resource_id = f"{self.device_id}-sample-{site_id}" - barcode = f"OPENLAB-HEAT-{self.device_id}-{site_id}" + base = f"{self.device_id}-sample-{site_id}" gateway = self._gateway() - for attempt in range(1, 100): - suffix = "" if attempt == 1 else f"-{attempt}" + for number in range(after + 1, after + 100): + resource_id = base if number == 1 else f"{base}-{number}" try: - gateway.get_material_by_resource_id(resource_id + suffix) + gateway.get_material_by_resource_id(resource_id) except Exception: # noqa: BLE001 - 查不到即可用;权威读不到时交给建树报错 - return resource_id + suffix, barcode + suffix + return resource_id, f"OPENLAB-HEAT-{resource_id}", number raise RuntimeError(f"{self.device_id} 工位 {site_id} 找不到可用的样品 resource_id") @not_action - def _new_sample(self, site_id: int) -> VirtualHeatingSample: + def _new_sample(self, site_id: int, *, after: int = 0) -> tuple[VirtualHeatingSample, int]: from unilabos.resources.resource_tracker import set_plr_template_name - resource_id, barcode = self._sample_identity(site_id) + resource_id, barcode, number = self._sample_identity(site_id, after=after) sample = VirtualHeatingSample( resource_id, barcode=Barcode( @@ -435,12 +441,16 @@ def _new_sample(self, site_id: int) -> VirtualHeatingSample: }, } sample.temperature_source = self._temperature_source(site_id) - return sample + return sample, number @not_action def _provision_materials(self) -> None: - """空工位放上演示样品:建树与占用工位在权威的同一事务里完成(失败整体回滚)。""" + """空工位放上演示样品:建树与占用工位在权威的同一事务里完成(失败整体回滚)。 + 权威拒绝样品身份(条码 / resource_id / PLR 键已被别的物料用了)时换下一个序号再建。 + """ + + from unilabos.client.host.runtime.resource import _is_conflict_error from unilabos.resources import materials with self._provision_lock: @@ -451,21 +461,27 @@ def _provision_materials(self) -> None: continue site = self._device_sites.get(index) or _site_label(index) display_name = f"加热样品 {index}" - try: - created = materials.create( - self._new_sample(index), - node=node, - site=site, - display_name=display_name, - ) - except LinkError: - raise - except Exception as exc: # noqa: BLE001 - 一个工位放不上不影响其它工位与设备启动 - logger.warning( - "[HeatingDemo] %s 工位 %s 放置演示样品失败:%s", self.device_id, index, exc - ) - continue - self._adopt(index, created, display_name=display_name) + created, after = None, 0 + for _attempt in range(_IDENTITY_ATTEMPTS): + sample, after = self._new_sample(index, after=after) + try: + created = materials.create(sample, node=node, site=site, display_name=display_name) + break + except LinkError: + raise + except Exception as exc: # noqa: BLE001 - 一个工位放不上不影响其它工位与设备启动 + if _is_conflict_error(exc): + logger.info( + "[HeatingDemo] %s 工位 %s 的样品身份 %s 已被占用,换下一个序号:%s", + self.device_id, index, sample.name, exc, + ) + continue + logger.warning( + "[HeatingDemo] %s 工位 %s 放置演示样品失败:%s", self.device_id, index, exc + ) + break + if created is not None: + self._adopt(index, created, display_name=display_name) # ------------------------------------------------------------------ # 加热 From 40a81d9db3a494036597ba15b215aae8fe928565 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:34:14 +0800 Subject: [PATCH 32/59] fix(materials): empty_containers_only lists containers without contents in any form The filter only looked at material_content registrations, so a bottle filled through material.content.set, a device snapshot or put_data (which write substance rows) was listed as empty, and devices, decks and carriers were listed as empty containers. Empty now means no registration and no substance with a quantity above 0, and only containers qualify: device, deck, carrier, *_carrier and warehouse materials are left out. --- tests/server/test_v1_resource_contract.py | 57 +++++++++++++++++++ unilabos/server/api/materials/resources.py | 2 +- .../services/materials/resource_contract.py | 12 +++- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/tests/server/test_v1_resource_contract.py b/tests/server/test_v1_resource_contract.py index 9c1aceb2c..b30a0ebaf 100644 --- a/tests/server/test_v1_resource_contract.py +++ b/tests/server/test_v1_resource_contract.py @@ -251,6 +251,63 @@ def uuids(**params) -> set[str]: error_of(client.get("/api/v1/materials", params={"category": "bogus"}), 1000) +def test_empty_containers_are_containers_without_contents_in_any_form(tmp_path) -> None: + """内容物行(content.set / put_data / 设备快照写的)也算内容;设备、台面、载架不是容器。""" + + from uuid import uuid4 + + from unilabos.protocol.materials import ( + InventoryMutation, + MaterialDataWrite, + MaterialIdentityWrite, + MaterialNodeCreate, + MaterialSubstance, + MaterialTreeCreate, + ) + + service = MaterialsService(tmp_path / "materials.db") + app = FastAPI() + install_materials_api(app, service) + + def mutation(operation: str) -> InventoryMutation: + command = str(uuid4()) + return InventoryMutation(command_uuid=command, effect_key=f"{operation}:{command}", operation=operation, + actor_type="test", actor_uuid="empty-containers") + + def create(resource_type: str) -> str: + return service.create_tree(mutation("create_material_tree"), MaterialTreeCreate(nodes=[MaterialNodeCreate( + client_ref="root", identity=MaterialIdentityWrite( + resource_id=f"{resource_type}-{uuid4().hex[:6]}", template_name=f"{resource_type}_tpl", + resource_type=resource_type, config={"type": "Resource"}), + )])).data.root_material_uuid + + try: + with TestClient(app) as client: + identities = _templates(client) + + def bottle(name: str) -> str: + return ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": name}), status=201)["uuid"] + + empty, set_by_command, put_by_data, drained = bottle("空瓶"), bottle("命令装液"), bottle("数据装液"), bottle("用空") + ok_data(client.post("/api/v1/inventory/commands", json={ + "command_id": "fill-1", "type": "material.content.set", + "payload": {"edge_uuid": set_by_command, "state": {"substances": [ + {"name": "水", "quantity": 10, "quantity_unit": "ml"}]}}})) + for material_uuid, quantity in ((put_by_data, 5.0), (drained, 0.0)): + service.put_data(mutation("put_data"), material_uuid, MaterialDataWrite(substances=[ + MaterialSubstance(name="水", quantity=quantity, quantity_unit="ml")])) + not_containers = {create("device"), create("deck"), create("plate_carrier"), create("warehouse")} + + listed = {item["uuid"] for item in ok_data(client.get( + "/api/v1/materials", params={"empty_containers_only": "true", "page_size": 100}))["items"]} + + assert listed == {empty, drained} + assert not listed & not_containers + finally: + service.close() + + def test_material_graph_rereads_only_the_named_materials_and_their_site_owners(client) -> None: identities = _templates(client) rack = ok_data(client.post("/api/v1/materials", json={ diff --git a/unilabos/server/api/materials/resources.py b/unilabos/server/api/materials/resources.py index 98d2373ca..93bf4401a 100644 --- a/unilabos/server/api/materials/resources.py +++ b/unilabos/server/api/materials/resources.py @@ -233,7 +233,7 @@ def list_materials( resource_template_uuid: Optional[str] = Query(default=None), category: Optional[str] = Query(default=None, description="material = 非设备物料;device = 设备"), inventory_scope: str = Query(default="current", description="current | history(离站物料,本后端恒为空)"), - empty_containers_only: bool = Query(default=False, description="只要没有任何内容登记的物料"), + empty_containers_only: bool = Query(default=False, description="只要空容器:不含设备、台面与载架,且没有内容登记、也没有数量大于 0 的内容物"), ) -> Any: return contract.list_materials(page=page, page_size=page_size, name=name, barcode=barcode, resource_template_uuid=resource_template_uuid or None, diff --git a/unilabos/server/services/materials/resource_contract.py b/unilabos/server/services/materials/resource_contract.py index 7ab47ce51..6410c9b02 100644 --- a/unilabos/server/services/materials/resource_contract.py +++ b/unilabos/server/services/materials/resource_contract.py @@ -502,10 +502,20 @@ def list_materials( elif category: raise MaterialValidationError("category must be material or device") if empty_containers_only: - # 没有任何内容登记(试剂 / 样品 / 当前内容物);数量为 0 的有效登记仍算非空 + # 空容器:只看容器(设备、台面、载架与仓库不是容器),且没有任何内容记录——没有内容登记 + # (试剂 / 样品 / 当前内容物,数量为 0 的有效登记仍算非空),也没有数量大于 0 的内容物 + # (material.content.set、设备快照、put_data 写的是内容物行,不一定有登记) + where.append( + "resource_type NOT IN ('device', 'deck', 'carrier', 'warehouse') " + "AND resource_type NOT LIKE '%\\_carrier' ESCAPE '\\'" + ) where.append( "NOT EXISTS (SELECT 1 FROM material_content c WHERE c.material_uuid = material.material_uuid)" ) + where.append( + "NOT EXISTS (SELECT 1 FROM material_substance s " + "WHERE s.material_uuid = material.material_uuid AND s.quantity > 0)" + ) if name: # V1 的 name 筛选按人读标签匹配 where.append("display_name LIKE ?") From 7129a92722b1b44aaca41e6ab52b48f2de96af4f Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:05:44 +0800 Subject: [PATCH 33/59] fix(materials): a placed create gets a location and never leaves the authority and the device diverged materials.create(plate, node=node, parent=holder) without a site committed the material with no location, and the local load assigned it with location=None: the next start failed to deserialize the device subtree ("Child resource ... has no location"). A local load that failed after the commit (parent not held by the node, a carrier spot mismatch, a timeout, a call from the node's executor) left the authority holding a material the device did not have, or the tracker holding an orphan. Location: one helper (DeviceNode._mount_on_parent) mounts a material on a local parent for create, transfer loads and Host-sent mounts. A parent that places its own spots does it (carrier assign_resource_to_site, spot assign_child_resource, ResourceHolder's default child location); otherwise the material goes to the Site's location, or to (0, 0, 0) without a Site. The location is never None after mounting. The create request stores the same rule's position in the authority (the Site's position or the origin), and the load reports the final pose, so a restart deserializes cleanly. Atomicity: before committing, a placed create checks that it is not on the node's own executor and that a material parent is held by the node. If the local load still fails after the commit, the created tree is deleted in the authority under the same command_uuid (effect undo_create_material_tree) and any local instance is unloaded, then the original error is raised. A load now mounts before it registers the material, so a failed mount leaves no orphan in the tracker. PLR key clashes are already rejected by the authority before anything is committed. --- .../test_materials_create_and_place.py | 102 ++++++++++++++ unilabos/client/host/runtime/node.py | 130 ++++++++++++------ unilabos/resources/adapters/plr_materials.py | 7 +- unilabos/resources/materials.py | 94 ++++++++++++- 4 files changed, 292 insertions(+), 41 deletions(-) diff --git a/tests/resources/test_materials_create_and_place.py b/tests/resources/test_materials_create_and_place.py index 4f14df644..9a80bbbf5 100644 --- a/tests/resources/test_materials_create_and_place.py +++ b/tests/resources/test_materials_create_and_place.py @@ -282,3 +282,105 @@ def test_assign_rejects_another_devices_site_uuid(device) -> None: assert loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources assert service.get_material(loose.unilabos_uuid).material.parent_material_uuid is None assert _site(service, other_uuid, "o1").occupied_material_uuid is None + + +# ── 没给库位的落位:位置是原点,权威里也是,重启照样反序列化 ───────────────── + + +def _holder_on(device, name: str = "holder"): + from pylabrobot.resources import Resource + + holder = Resource(name, size_x=200, size_y=200, size_z=10, category="container") + return materials.create(holder, node=device["node"], site="slot_a", gateway=device["gateway"]) + + +def _restart(device, root_uuid: str): + """设备重启时持有的物料按权威整棵反序列化。""" + + return materials.get(root_uuid, gateway=device["gateway"]).to_plr_resources()[0] + + +def test_create_under_a_parent_without_a_site_gets_the_origin_and_restarts(device) -> None: + from pylabrobot.resources import Coordinate + + holder = _holder_on(device) + + other = materials.create(plate("other"), node=device["node"], parent=holder, gateway=device["gateway"]) + + assert other.location == Coordinate(0, 0, 0) + stored = device["service"].get_material(other.unilabos_uuid).position + assert (stored.position_x, stored.position_y, stored.position_z) == (0, 0, 0) + restored = _restart(device, holder.unilabos_uuid) + assert [child.name for child in restored.children] == ["other"] + + +# ── 本地加载失败时不留分叉:先查前提,提交后失败就在同一条命令下撤销 ───────── + + +def test_a_plr_key_the_tree_already_uses_is_rejected_before_anything_changes(device) -> None: + """PLR 键在这棵树里已经有了(resource_id 不同):权威拒绝,本地加载根本不会开始。""" + + from pylabrobot.resources import Coordinate, Resource + + service, node = device["service"], device["node"] + holder = Resource("holder", size_x=200, size_y=200, size_z=10, category="container") + holder.assign_child_resource(plate("other"), location=Coordinate(0, 0, 0)) + holder = materials.create(holder, node=node, site="slot_a", gateway=device["gateway"]) + before = len(service.list_materials()) + + with pytest.raises(Exception, match="other"): + materials.create(plate("other"), node=node, parent=holder, gateway=device["gateway"]) + + assert len(service.list_materials()) == before + local = node.resource_tracker.uuid_to_resources[holder.unilabos_uuid] + assert [child.name for child in local.children] == ["other"] + assert len(node.resource_tracker.uuid_to_resources) == 1 + len(local.get_all_children()) + materials.update(node, local) + + +def test_a_local_load_failure_after_the_commit_is_undone(device, monkeypatch) -> None: + """权威已建好并落位、本地挂载失败(库位对不上):撤销权威里的新树,tracker 里不留孤儿。""" + + from unilabos.client.host.runtime.node import DeviceNode + + service, node = device["service"], device["node"] + holder = _holder_on(device) + before = {item.material.material_uuid for item in service.list_materials()} + indexed = set(node.resource_tracker.uuid_to_resources) + + def mismatch(*_args, **_kwargs): + raise ValueError("本地库位对不上") + + monkeypatch.setattr(DeviceNode, "_carrier_placement", classmethod(mismatch)) + with pytest.raises(ValueError, match="本地库位对不上"): + materials.create(plate("stray"), node=node, parent=holder, gateway=device["gateway"]) + + assert {item.material.material_uuid for item in service.list_materials()} == before + assert set(node.resource_tracker.uuid_to_resources) == indexed + assert node.resource_tracker.uuid_to_resources[holder.unilabos_uuid].children == [] + + +def test_a_parent_the_device_does_not_hold_is_refused_before_the_commit(device) -> None: + service = device["service"] + elsewhere = materials.create(plate("elsewhere"), gateway=device["gateway"]) + before = len(service.list_materials()) + + with pytest.raises(ValueError, match="不在设备"): + materials.create(plate("orphan_child"), node=device["node"], parent=elsewhere, gateway=device["gateway"]) + + assert len(service.list_materials()) == before + + +def test_a_placed_create_from_the_node_executor_is_refused_before_the_commit(device) -> None: + from unilabos.client.host.runtime.async_utils import run_node_coroutine + + service, node = device["service"], device["node"] + before = len(service.list_materials()) + + async def from_the_executor(): + materials.create(plate("blocked"), node=node, site="slot_b", gateway=device["gateway"], timeout=1.0) + + with pytest.raises(RuntimeError, match="执行器线程"): + run_node_coroutine(node, from_the_executor(), 5.0) + + assert len(service.list_materials()) == before diff --git a/unilabos/client/host/runtime/node.py b/unilabos/client/host/runtime/node.py index bb64ab15e..e56b0f8e1 100644 --- a/unilabos/client/host/runtime/node.py +++ b/unilabos/client/host/runtime/node.py @@ -455,11 +455,77 @@ def _carrier_placement( ) return carrier, holder_spot + @staticmethod + def _site_position(sites: Any, selector: Any | None) -> Any | None: + """库位列表(``ResourceSite`` 或其 dict)里按 uuid / label / index 命中的那个库位的位置;没给库位返回 None。""" + + from pylabrobot.resources import Coordinate + + if selector is None or str(selector).strip() == "": + return None + normalized = str(selector).strip() + for site in sites or []: + dumped = site if isinstance(site, dict) else site.model_dump() + if normalized in {str(dumped.get("uuid") or ""), str(dumped.get("label") or ""), str(dumped.get("index", ""))}: + position = (dumped.get("pose") or {}).get("position") or {} + return Coordinate(*(float(position.get(axis) or 0.0) for axis in ("x", "y", "z"))) + raise ValueError(f"找不到库位 {selector!r}") + + def _device_site_location(self, selector: Any | None) -> Any | None: + """本设备自身库位的位置(库位来自设备节点的图配置);没给库位返回 None。""" + + config = getattr(self, "device_config", None) + sites = getattr(getattr(config, "res_content", None), "sites", None) + return self._site_position(sites, selector) if sites else None + + @classmethod + def _mount_on_parent( + cls, parent: Any, resource: Any, selector: Any | None, *, default_location: Any | None = None + ) -> Any: + """把 ``resource`` 挂到本地 PLR 父物料 ``parent`` 下;create / assign / transfer 落到本设备都经这里。 + + 父物料自己会排布库位时交给它算位置:PLR 载架(或载架某个库位的 holder)经 + ``assign_resource_to_site`` 放到库位上,``assign_child_resource`` 接受 ``spot`` 的按库位挂, + ``ResourceHolder`` 用它的默认子位置。其余父物料不会自己算:给了库位用那个库位的位置,没给就是 + ``default_location``(Host 下发挂载时给的挂载坐标),缺省 ``(0, 0, 0)``。挂上之后位置一定不是 None——设备重启时整棵树按 PLR 反序列化,没有位置的孩子会让 + 它失败。返回实际承载它的父物料(经载架放时是载架)。 + """ + + from pylabrobot.resources import Coordinate, ResourceHolder + + from unilabos.resources.objects.resource import EXTRA_SITES + + placement = cls._carrier_placement(parent, selector) + if placement is not None: + carrier, spot = placement + carrier.assign_resource_to_site(resource, spot) + return carrier + assign_site = getattr(parent, "assign_resource_to_site", None) + takes_spot = "spot" in inspect.signature(parent.assign_child_resource).parameters + spot = cls._site_spot(parent, selector) if callable(assign_site) or takes_spot else None + if callable(assign_site) and spot is not None: + assign_site(resource, spot) + elif takes_spot: + parent.assign_child_resource(resource, location=None, spot=spot) + elif isinstance(parent, ResourceHolder): + parent.assign_child_resource(resource, location=None) + else: + extra = getattr(parent, "unilabos_extra", None) + sidecar = extra.get(EXTRA_SITES) if isinstance(extra, dict) else None + sites = list(sidecar.values()) if isinstance(sidecar, dict) else [] + location = cls._site_position(sites, selector) if selector is not None else None + parent.assign_child_resource(resource, location=location or default_location or Coordinate(0, 0, 0)) + if resource.location is None: + resource.location = default_location or Coordinate(0, 0, 0) + return parent + async def _attach_local_materials( self, material_uuids: list[str], sites: list[Any | None], ) -> list[Any]: + from pylabrobot.resources import Coordinate + tracker = getattr(self, "resource_tracker", None) if tracker is None: raise BackendCapabilityError( @@ -483,16 +549,17 @@ async def _attach_local_materials( existing = tracker.uuid_to_resources.get(material_uuid) if existing is not None: await self._remove_local_materials([material_uuid]) - tracker.add_resource(resource) parent_uuid = str(tree.root_node.res_content.uuid_parent or "") parent = None if parent_uuid and parent_uuid != self.resource_uuid: parent = tracker.uuid_to_resources.get(parent_uuid) if parent is None: - tracker.remove_resource(resource) raise ValueError( f"目标设备 {self.device_id!r} 找不到挂载物料 {parent_uuid}" ) + # 先挂上再登记:挂不上(库位对不上等)时 tracker 里不留孤儿 + parent = self._mount_on_parent(parent, resource, site) + tracker.add_resource(resource) tracker.resources = [ item for item in tracker.resources if item is not resource ] @@ -501,27 +568,11 @@ async def _attach_local_materials( ) if observer is not None: observer.unobserve(resource) - placement = self._carrier_placement(parent, site) - spot = ( - placement[1] - if placement is not None - else self._site_spot(parent, site) - ) - assign_site = getattr( - placement[0] if placement is not None else parent, - "assign_resource_to_site", - None, - ) - if callable(assign_site) and spot is not None: - # 载架 Site:经载架放到 holder 上(权威父节点可能是载架或其 holder) - assign_site(resource, spot) - else: - assign = parent.assign_child_resource - parameters = inspect.signature(assign).parameters - kwargs: dict[str, Any] = {} - if "spot" in parameters: - kwargs["spot"] = spot - assign(resource, location=None, **kwargs) + else: + # 设备自身持有的根物料:没有位置时按库位的位置,没给库位是原点 + if resource.location is None: + resource.location = self._device_site_location(site) or Coordinate(0, 0, 0) + tracker.add_resource(resource) if parent is not None: await self._invoke_resource_hook( "resource_tree_transfer", @@ -707,7 +758,12 @@ def _release_resource_tree_uuid_locks(self, locks: List[DeviceAsyncMutex]) -> No lock.release(self) def transfer_to_new_resource( - self, plr_resource: Any, tree: Any, additional_add_params: Dict[str, Any] + self, + plr_resource: Any, + tree: Any, + additional_add_params: Dict[str, Any], + *, + location: Any | None = None, ) -> Optional[Any]: """把(已实例化的)物料挂载到 tree 指定的父物料下,返回父物料。 @@ -736,7 +792,6 @@ def transfer_to_new_resource( return None try: # 将 Uni-Lab-OS 的 site/slot 元数据转换为 PLR 挂载参数。 - additional_params: Dict[str, Any] = {} extra = getattr(plr_resource, "unilabos_extra", {}) if len(extra): self.lab_logger().info(f"发现物料{plr_resource}额外参数: " + str(extra)) @@ -745,20 +800,19 @@ def transfer_to_new_resource( additional_add_params["slot"] = extra["update_resource_site"] # site 只承载权威 Site uuid;slot 承载 label / 0-based 索引 selector = additional_add_params.get("site") or additional_add_params.get("slot") - # PLR 载架(仓库等)只能经 Site 放物料;目标也可能是载架 Site 的 holder + # 卸下原父物料之前先核对库位能解析(PLR 载架只能经 Site 放物料,目标也可能是载架 + # Site 的 holder;按 spot 排布的父物料解析 uuid、label 或索引):选择器无效时什么都不改 placement = self._carrier_placement(parent_resource, selector) spec = inspect.signature(parent_resource.assign_child_resource) if placement is None and "spot" in spec.parameters: - # _site_spot 解析 uuid、label 或索引;未指定时由父级选择默认位置, - # 无法解析的显式选择器直接报错。 - additional_params["spot"] = self._site_spot(parent_resource, selector) + self._site_spot(parent_resource, selector) old_parent = plr_resource.parent if old_parent is not None: # PLR 资源在重新挂载前必须先从当前父资源解除。 self.lab_logger().info(f"物料{plr_resource}从{old_parent}卸载") old_parent.unassign_child_resource(plr_resource) self.lab_logger().info( - f"物料{plr_resource}挂载到{parent_resource},额外参数:{additional_params}" + f"物料{plr_resource}挂载到{parent_resource},库位:{selector}" ) # 挂载后资源属于 parent_resource;先从顶级列表移除可避免 @@ -777,14 +831,10 @@ def transfer_to_new_resource( if observer is not None: observer.unobserve(plr_resource) - if placement is not None: - carrier, spot = placement - self.lab_logger().info(f"物料{plr_resource}经载架{carrier}放到 Site[{spot}]") - carrier.assign_resource_to_site(plr_resource, spot) - # 上报从载架起:它的 Site 占用随同一棵树回报 - parent_resource = carrier - else: - parent_resource.assign_child_resource(plr_resource, location=None, **additional_params) + # 与 create / transfer 落到本设备同一条挂载规则;经载架放时上报从载架起(Site 占用随同一棵树回报) + parent_resource = self._mount_on_parent( + parent_resource, plr_resource, selector, default_location=location + ) func = getattr(self._resource_driver(), "resource_tree_transfer", None) if callable(func): @@ -1019,7 +1069,9 @@ async def append_resource( if all(id(old_root) != id(existing) for existing in report_roots): report_roots.append(old_root) plr_instances.append(plr_instance) - parent = self.transfer_to_new_resource(plr_instance, tree, dict(additional_params)) + parent = self.transfer_to_new_resource( + plr_instance, tree, dict(additional_params), location=bind_location + ) if parent is None and parent_uuid != self.resource_uuid: raise ValueError(f"物料 {plr_instance.name} 挂载到 {bind_parent_id} 失败(详见设备日志)") if plr_instance.location is None: diff --git a/unilabos/resources/adapters/plr_materials.py b/unilabos/resources/adapters/plr_materials.py index ce1e0ef74..9d5f434b2 100644 --- a/unilabos/resources/adapters/plr_materials.py +++ b/unilabos/resources/adapters/plr_materials.py @@ -634,6 +634,7 @@ def create_plr_materials( root_extra: dict[str, Any] | None = None, placement: MaterialPlacement | None = None, display_name: str = "", + root_position: tuple[float, float, float] | None = None, ) -> CreatedPLRMaterials: """把 PLR 草稿发给权威创建;``root_extra`` 合并进根节点 identity.extra。 @@ -641,7 +642,8 @@ def create_plr_materials( 在 create 请求上合并可保证入库即带元数据,且不修改调用方的输入实例。 ``placement`` 让权威在建树的同一事务里把根物料落到父物料 / 库位上(原子)。 ``display_name`` 是根物料的人读标签(省略时取 PLR 名);PLR 运行时不承载展示名, - 之后的快照也不会改写它。 + 之后的快照也不会改写它。``root_position`` 是落位时根物料没有位置时入库的位置(库位的位置或原点), + 权威里不留没有位置的孩子。 """ request = plr_resources_to_create(resources) @@ -652,6 +654,9 @@ def create_plr_materials( node.identity.extra = {**node.identity.extra, **root_extra} if display_name.strip(): node.identity.display_name = display_name.strip() + if root_position is not None and node.position.position_x is None: + x, y, z = root_position + node.position = node.position.model_copy(update={"position_x": x, "position_y": y, "position_z": z}) if placement is not None: request.placement = placement result = gateway.create_tree(mutation, request) diff --git a/unilabos/resources/materials.py b/unilabos/resources/materials.py index 7973c4310..652072313 100644 --- a/unilabos/resources/materials.py +++ b/unilabos/resources/materials.py @@ -729,6 +729,81 @@ def _site_uuid(site: Any, parent_uuid: str, gateway: MaterialGateway) -> str: return str(matches[0].site_uuid) +def _require_off_node_executor(node: Any, what: str) -> None: + """阻塞等待本地挂载的调用不能跑在设备节点自己的事件循环上:挂载要排到那个循环里,会等到自己。""" + + loop = getattr(node, "_loop", None) + try: + running = asyncio.get_running_loop() + except RuntimeError: + return + if loop is not None and running is loop: + raise RuntimeError( + f"{what} 不能在设备 {getattr(node, 'device_id', node)} 的执行器线程里调用(会等到自己):" + "请在驱动的普通线程里调用" + ) + + +def _site_position( + gateway: MaterialGateway, parent_uuid: str, site_uuid: str | None +) -> tuple[float, float, float]: + """落位时根物料没有位置要入库的位置:给了库位是那个库位的位置,没给是原点。""" + + if site_uuid is None: + return (0.0, 0.0, 0.0) + for item in gateway.get_material(parent_uuid).sites: + if str(item.site_uuid) == site_uuid: + position = (item.pose or {}).get("position") or {} + return tuple(float(position.get(axis) or 0.0) for axis in ("x", "y", "z")) # type: ignore[return-value] + return (0.0, 0.0, 0.0) + + +def _undo_placed_create( + node: Any, + gateway: MaterialGateway, + mutation: InventoryMutation, + created: CreatedPLRMaterials, + timeout: float, +) -> None: + """权威已建好并落位、本地挂载却失败(超时、库位对不上……):两边都回到 create 之前。 + + 本地若已挂上就按 transfer 的 unload 卸掉(tracker 不留孤儿),权威在同一条命令下删掉刚建的树、 + 释放库位。撤销本身失败只写日志,原来的错误照常抛给调用方。 + """ + + from unilabos.client.host.runtime.async_utils import run_node_coroutine + from unilabos.protocol.materials import MaterialDelete + from unilabos.utils.log import logger + + root_uuid = str(created.tree.trees[0].root_node.res_content.uuid) + try: + run_node_coroutine( + node, + node.material_sync({ + "transfer_uuid": f"undo-create:{mutation.command_uuid}", + "device_id": str(node.device_id), + "action": "unload", + "material_uuids": [root_uuid], + }), + timeout, + ) + except Exception as exc: # noqa: BLE001 - 本地卸不掉只能记下,权威照样撤销 + logger.error(f"[materials.create] 本地挂载失败后卸下物料 {root_uuid} 也失败:{exc}") + try: + gateway.delete_material( + InventoryMutation( + command_uuid=mutation.command_uuid, + effect_key="undo_create_material_tree", + operation="delete_material", + actor_type=mutation.actor_type, + actor_uuid=mutation.actor_uuid, + ), + MaterialDelete(material_uuid=root_uuid, recursive=True), + ) + except Exception as exc: # noqa: BLE001 - 原错误更重要 + logger.error(f"[materials.create] 本地挂载失败后撤销权威里的物料 {root_uuid} 也失败:{exc}") + + def _attach_placed( node: Any, created: CreatedPLRMaterials, @@ -853,12 +928,24 @@ def create( resolved_gateway = gateway or resolve_materials_gateway() placement: MaterialPlacement | None = None site_uuid: str | None = None + root_position: tuple[float, float, float] | None = None if parent is not None or site is not None: if node is None: raise ValueError("带落位的 create 需要 node:落位后要在设备本地挂上同一份实例") parent_uuid = _parent_material_uuid(node, parent) + # 提交之前先核对本地挂载的前提,不满足时什么都不写 + _require_off_node_executor(node, "带落位的 materials.create") + if parent_uuid != str(getattr(node, "resource_uuid", "") or "") and ( + parent_uuid not in node.resource_tracker.uuid_to_resources + ): + raise ValueError( + f"父物料 {parent_uuid} 不在设备 {node.device_id} 本地:只能落到本设备持有的物料上" + ) if site is not None: site_uuid = _site_uuid(site, parent_uuid, resolved_gateway) + # 权威里的位置与本地挂载同一条规则:给了库位是库位的位置,没给是原点;父物料自己排布库位时 + # 本地挂上后按它算出的位置补报 + root_position = _site_position(resolved_gateway, parent_uuid, site_uuid) placement = MaterialPlacement(parent_material_uuid=parent_uuid, site=site_uuid) created = create_plr_materials( resolved_gateway, @@ -871,13 +958,18 @@ def create( ), placement=placement, display_name=display_name, + root_position=root_position, ) if node is not None: if placement is None: for resource in created.resources: node.resource_tracker.add_resource(resource) else: - created = _attach_placed(node, created, site_uuid, request.command_uuid, timeout) + try: + created = _attach_placed(node, created, site_uuid, request.command_uuid, timeout) + except BaseException: + _undo_placed_create(node, resolved_gateway, request, created, timeout) + raise if not unwrap_single: return created if len(created.resources) != 1: From 30ec1f2b2232f81f70e7426fb2af5452588aef47 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:06:03 +0800 Subject: [PATCH 34/59] fix(materials): assign is a material move through the materials service materials.assign(node_B, uuid, slot=...) on a material device A still held re-parented it in the authority while A kept its local instance: both trackers mapped the uuid and A's strict snapshots failed. Assign with a material parent also mounted locally before the authority move, so a rejected move left the local mount behind. assign now runs the same flow as materials.transfer (MaterialsService.transfer_material): the authority validates and commits the move, the device that held the material (its owner in the authority, or none) unloads it, and the target device loads and rebuilds the subtree. Same device and cross device take this one path, and a rejected move changes nothing locally. A material already at the destination and held by the node is a no-op. The result lists the rebuilt instances ("resources"); the parent can still be a PLR key the node holds, and site / slot are resolved by the authority (uuid, label or the Site's own index). Assign goes through the node's own materials gateway and refuses to run on the node's executor. HostLinkLocalRuntime.dispatch_material_sync runs a load / unload on a local device; HostLinkBackend uses it for its local devices. Host-sent RESOURCE_APPEND (deduct-and-mount) still uses append_resource. --- .../examples/materials_operations_guide.md | 60 ++++---- .../interfaces/python-cli-mcp.md | 11 +- .../test_material_creation_flows_e2e.py | 78 +++++++---- .../hostlink/test_material_io_deck_sync.py | 4 +- .../hostlink/test_warehouse_site_placement.py | 13 +- .../runtime/test_append_resource_commit.py | 23 +++- tests/plr_fixtures.py | 19 +++ .../test_materials_create_and_place.py | 101 +++++++++++++- unilabos/client/host/hostlink/backend.py | 5 +- .../client/host/hostlink/local_runtime.py | 11 ++ unilabos/client/host/runtime/resource.py | 5 + unilabos/resources/materials.py | 130 +++++++++++------- 12 files changed, 326 insertions(+), 134 deletions(-) diff --git a/docs/developer_guide/examples/materials_operations_guide.md b/docs/developer_guide/examples/materials_operations_guide.md index 2c4b726a0..50e6b1571 100644 --- a/docs/developer_guide/examples/materials_operations_guide.md +++ b/docs/developer_guide/examples/materials_operations_guide.md @@ -169,21 +169,22 @@ tree_set = await node.get_resource_by_id("PRCXI_Deck/plate_1") ### 2.4 挂载到台面(materials.assign) -把权威已创建的物料 assign 到本设备的目标父物料下,一个调用完成 -"拉取/复用实例 → 物理 assign → 权威 move 落父子与 Site 占用 → 快照回写": +把权威已创建的物料放到本设备的目标父物料 / 库位上。`assign` 就是一次物料移动,与 +`materials.transfer` 同一条路(`MaterialsService.transfer_material`):"权威校验并提交 move(父子与 +Site 占用)→ 原来持有它的设备 unload → 本设备 load(按权威重建这棵子树挂上,并把位姿补报给权威)"。 +同设备换位与跨设备一样;权威拒绝(库位被占、类别不符、设备只收 PLR 物料、PLR 键重名……)时本地什么都不改: ```python -# 物料实例 + 目标父物料名 + slot -materials.assign(node, plate, parent="PRCXI_Deck", slot="T2") +# 物料实例 + 目标父物料(本设备持有的 PLR 键 / uuid / 实例)+ 库位;返回本设备重建后的实例 +[plate] = materials.assign(node, plate, parent="PRCXI_Deck", slot="T2")["resources"] -# 裸 uuid 在本地未命中时会从权威加载并实例化 +# 裸 uuid:不属于任何设备的物料没有要卸下的地方,直接按权威加载 materials.assign(node, plate_uuid, parent="PRCXI_Deck", slot="T2") -# site= 传权威 ResourceSite 的 uuid(机器路径,与 slot 二选一) +# site= 传库位实例或权威 ResourceSite 的 uuid(也接受 label / index,与 slot 同一套匹配) materials.assign(node, plate, parent="PRCXI_Deck", site=site_uuid) -# parent=None:挂到设备自身(台面 Deck、驻留在设备上的顶级物料)——本地登记 tracker, -# 权威里该物料的 parent 落为设备物料,前端设备卡片下即可看到它和它的 sites +# parent=None:放到设备自身(台面 Deck、驻留在设备上的顶级物料);权威里该物料的 parent 落为设备物料 materials.assign(node, deck) # 仓库 / 载架(PLR Carrier、ItemizedCarrier、WareHouse)同样按库位挂载,必须给 slot 或 site @@ -211,30 +212,26 @@ def _ensure_bench(self): return node.resource_tracker.uuid_to_resources[self.deck_uuid] ``` -`assign` 的 `timeout`(默认 30 s,Host 下发 `RESOURCE_APPEND` 同此)只约束提交点之前:等挂载锁、 -从权威拉取物料。超时就取消,本地与权威都不变,抛 `TimeoutError`。本地 PLR 挂上之后(提交点), -权威 move 与快照回报一定走完再返回:快照按物料所在的整棵根树做,上千个物料的台面要几十秒, -期间每过一个 `timeout` 记一条 WARNING,不会在提交之后取消。每次取消都在设备日志里记 ERROR, -写明取消发生在哪一阶段。跨机(Slave 上的设备)时 Host 的 HostLink 请求仍以 30 s 为限: -Slave 照样把挂载做完,但 Host 侧调用方会先收到超时。 +Host 下发的 `RESOURCE_APPEND`(出库并挂载)仍由设备节点的 `append_resource` 执行;它的 `timeout` +(默认 30 s)只约束提交点之前:等挂载锁、从权威拉取物料。超时就取消,本地与权威都不变,抛 `TimeoutError`。 +本地 PLR 挂上之后(提交点),权威 move 与快照回报一定走完再返回:快照按物料所在的整棵根树做,上千个物料的 +台面要几十秒,期间每过一个 `timeout` 记一条 WARNING,不会在提交之后取消。 -创建多件耗材再逐件 `assign` 时,先校验目标位点空闲;挂载失败要 `materials.remove` 掉本轮已经 -发号的物料,否则权威里会留下不挂在任何台面上的孤儿。 +目标位参数(`site` 与 `slot` 都给时必须指向同一个库位),由权威按父物料的库位解析: -目标位参数(二选一): +| 参数 | 承载 | 示例 | +| ------ | ------------------------------------ | -------------------------- | +| `site` | 库位实例、权威 `ResourceSite.uuid`、label 或 index | `site_instance` / `"26da5442-…"` | +| `slot` | label 或库位自己的 index | `"A1"` / `"T2"` | -| 参数 | 承载 | 示例 | 适用 | -| ------ | ---------------------- | ----------------------- | ------------------------- | -| `site` | 权威 `ResourceSite.uuid` | `"26da5442-…"` | 机器路径(前端/微后端下发),move 直传免反查 | -| `slot` | label 或 0-based 数字字符串 | `"A1"` / `"T2"` / `"0"` | 人类/脚本路径;label 优先于数字解释 | +行为细节: -行为细节(自动完成,无需干预): - -- 本地已持有该 uuid 时**复用现有实例**(换位场景),不重复触发 - `resource_tree_add` 回调; -- Host 对远端设备下发挂载走 `RESOURCE_APPEND`(跨机 RPC),与本函数完全同语义; -- 本函数为阻塞式(驱动线程/脚本直接调);已在节点执行器内的异步代码 - 用 `await node.append_resource(payload)`。 +- 同设备换位也是 unload + load:tracker 里换成按权威重建的实例,旧实例作废,回调是 + `resource_tree_remove`(旧)+ `resource_tree_add`(新);用返回值里的 `resources` 继续操作; +- 已经在目标位置、本设备也持有它时幂等(什么都不做); +- 不给库位时位置是原点,父物料自己排布库位(载架、按 `spot` 挂的台面、`ResourceHolder`)时按它算, + 权威里存的位姿与本地一致,重启照样反序列化; +- 阻塞式(驱动线程 / 脚本直接调),不能在本设备的执行器线程里调用(load 要排到那个执行器上,会等到自己)。 ### 2.5 内容物与状态同步 @@ -366,8 +363,8 @@ created.get_well("A2").tracker.commit() # 观察者自动快照到权威 ```python # 按类名创建(或传草稿实例),node= 自动登记 tips = materials.create("PRCXI_300ul_Tips", name="local_tips", node=node) -# 挂上台面:复用本实例 -> assign -> 权威 move -> 快照 -materials.assign(node, tips, parent="PRCXI_Deck", slot="T2") +# 挂上台面:权威 move -> 本设备 unload 旧实例、load 重建 +[tips] = materials.assign(node, tips, parent="PRCXI_Deck", slot="T2")["resources"] ``` ### 来源 C:微后端仓储扣减(`apply_deduct_resource` 语义) @@ -468,8 +465,7 @@ transfer_resource`,与机械臂 pick/place 流使用同一转移语义。 | `adopt` 时只给根 uuid、后代缺失 | 全树每个节点都带 uuid | | tracker 操作后不 `commit()` | `add_liquid`/`empty` 等之后 `commit()`(观察者靠它触发) | | 绕过 tracker 改状态后不同步 | `await node.update_resource(物料)` 或 `materials.update` | -| 用 1-based slot 数字 | `slot` 是 label 或 0-based 数字字符串(`"A1"` / `"0"`) | -| `site` 参数传 label | `site` 只承载权威 `ResourceSite.uuid`,label 走 `slot` | +| assign 之后继续用传入的旧实例 | 用返回值里 `resources` 的重建实例 | ## 6. 模块速查 diff --git a/docs/developer_guide/interfaces/python-cli-mcp.md b/docs/developer_guide/interfaces/python-cli-mcp.md index b391bdcb2..3040bb996 100644 --- a/docs/developer_guide/interfaces/python-cli-mcp.md +++ b/docs/developer_guide/interfaces/python-cli-mcp.md @@ -152,14 +152,13 @@ ErrorPolicy 的 options 按异常类名映射到选项列表,`"*"` 是默认 from unilabos.resources import materials def create_and_mount(node, draft, parent_uuid: str, site_uuid: str): - # 必须使用返回的新实例,输入 draft 不会被就地改为权威实例。 - authoritative = materials.create(draft, node=node) - materials.assign(node, authoritative, parent=parent_uuid, site=site_uuid) - return authoritative + # 建树与落位在权威的同一事务里;返回本设备 tracker 里的那一份实例,输入 draft 不会被就地改为权威实例。 + return materials.create(draft, node=node, parent=parent_uuid, site=site_uuid) ``` -这是同步驱动/外部线程用法;assign 内部等待 node executor,不能在同一个 executor 的异步动作里同步等待自己。 -异步动作使用 `await node.append_resource(payload)`,具体 payload 见 HostLink 下行章节。 +这是同步驱动/外部线程用法;create(带落位)与 assign 都要等本设备执行器上的 load,不能在同一个执行器的 +异步动作里同步调用(会直接报错,不会等到自己)。已有物料换位用 `materials.assign`(经 transfer 的物料移动, +返回重建后的实例)。 create 一次只接收一个根(可带 children),`node=` 会自动登记该节点 tracker 和来源设备。 跨设备用 `await materials.transfer(...)`,由权威移位、来源 unload、目标 load; diff --git a/tests/client/host/hostlink/test_material_creation_flows_e2e.py b/tests/client/host/hostlink/test_material_creation_flows_e2e.py index 78f3ed5a7..97773baf4 100644 --- a/tests/client/host/hostlink/test_material_creation_flows_e2e.py +++ b/tests/client/host/hostlink/test_material_creation_flows_e2e.py @@ -18,9 +18,8 @@ materials.create("类名", name=..., node=node, gateway=...) -> registry 实例化草稿 -> 权威发 uuid -> node= 自动登记 tracker materials.assign(node, tips, parent="Bench_Deck", slot="T2") - -> node.append_resource:uuid 已在 tracker -> 复用本地实例 - (不重复触发 resource_tree_add)-> transfer_to_new_resource assign - -> 权威 move(parent_material_uuid + Site 占用)-> update_resource 快照 + -> 与 transfer 同一条路:权威先提交 move(parent + Site 占用) + -> 原持有设备 unload(resource_tree_remove)-> 本设备 load 按权威重建(resource_tree_add) [3] 微后端仓储系统扣减创建(host_node.apply_deduct_resource 同语义) 分支 A 库存已在权威:materials.ensure(带 uuid 实体) -> gw.get_material @@ -28,8 +27,8 @@ 挂载走 Host 下发 RESOURCE_APPEND(跨机 RPC 与 assign 同语义) 分支 B 扣减产物权威缺失:materials.ensure -> resource_tree_to_create( adopt_uuid=True) -> create_tree(显式 uuid,带条件创建=adopt) - 挂载走 materials.assign(node, uuid 字符串, ...):本地未命中 - 实例 -> get_resource 按 uuid 从权威加载 -> resource_tree_add + 挂载走 materials.assign(node, uuid 字符串, ...):不属于任何设备, + 没有要卸下的地方 -> 本设备 load 按 uuid 从权威加载 -> resource_tree_add [4] materials.transfer 换位(同设备 source==target,跨设备编排一致) materials.transfer(uuid, DEVICE_ID, deck_uuid, "T4", source_device_id=...) @@ -108,6 +107,33 @@ def _append_via_hostlink( ) +def _register_device(service: MaterialsService, device_uuid: str, device_id: str) -> None: + """开机图对齐会落的设备物料行:物料放到设备自身时权威要有这台设备。""" + + from unilabos.protocol.materials import ( + InventoryMutation, + MaterialDataWrite, + MaterialIdentityWrite, + MaterialNodeCreate, + MaterialTreeCreate, + ResourceTemplateWrite, + ) + + def mutation(operation: str) -> InventoryMutation: + return InventoryMutation(command_uuid=str(uuid4()), effect_key=operation, operation=operation, + actor_type="graph", actor_uuid="test") + + service.put_template(mutation("put_template"), ResourceTemplateWrite( + name="bench_demo", display_name="bench", resource_type="device", class_name="bench_demo", + )) + service.create_tree(mutation("create_material_tree"), MaterialTreeCreate(nodes=[MaterialNodeCreate( + client_ref="dev", material_uuid=device_uuid, + identity=MaterialIdentityWrite(resource_id=device_id, resource_type="device", + class_name="bench_demo", template_name="bench_demo"), + data=MaterialDataWrite(data={}, sites_initialized=True, state_status="ready"), + )])) + + def _site_by_label(service: MaterialsService, root_uuid: str, label: str): for node in service.get_tree(root_uuid).nodes: for site in node.sites: @@ -246,12 +272,14 @@ def test_material_creation_flows_host_plus_slave(tmp_path, monkeypatch) -> None: tips_uuid = local_tips.unilabos_uuid assert node.resource_tracker.uuid_to_resources[tips_uuid] is local_tips - # 挂载门面:与 Host 下发 RESOURCE_APPEND 同语义(node.append_resource) - materials.assign(node, local_tips, parent="Bench_Deck", slot="T2") - # 本地已持有 -> append_resource 复用同一实例,不重复 resource_tree_add - assert node.resource_tracker.uuid_to_resources[tips_uuid] is local_tips - assert local_tips.parent is deck_inst - assert len(node.driver.added_batches) == 1 + # assign 就是一次物料移动:权威提交 -> 原持有设备(就是本设备)unload -> load 重建 + [placed_tips] = materials.assign(node, local_tips, parent="Bench_Deck", slot="T2")["resources"] + assert placed_tips is not local_tips + assert node.resource_tracker.uuid_to_resources[tips_uuid] is placed_tips + assert placed_tips.parent is deck_inst + assert node.driver.removed_batches[-1] == [local_tips] + assert node.driver.added_batches[-1] == [placed_tips] + assert len(node.driver.added_batches) == 2 # 权威:move 落父子 + Site 占用 assert ( service.get_material(tips_uuid).material.parent_material_uuid == deck_uuid @@ -265,7 +293,7 @@ def test_material_creation_flows_host_plus_slave(tmp_path, monkeypatch) -> None: # node.update_resource 即本调用的 async 包装)。挂载后的物料按其 # 所在根树(deck)投影提交并返回;快照幂等,与 observer 并发冲突 # 时自动重拉基线重试,重复提交无害。 - updated = materials.update(node, local_tips) + updated = materials.update(node, placed_tips) assert { tree.root_node.res_content.uuid for tree in updated.trees } == {deck_uuid} @@ -295,7 +323,7 @@ def test_material_creation_flows_host_plus_slave(tmp_path, monkeypatch) -> None: _append_via_hostlink(host, stock_uuid, bind_parent_id=deck_uuid, slot="T3") stock_inst = node.resource_tracker.uuid_to_resources[stock_uuid] assert stock_inst.parent is deck_inst - assert len(node.driver.added_batches) == 2 # 新实例 -> resource_tree_add + assert len(node.driver.added_batches) == 3 # 新实例 -> resource_tree_add # 库存液体随权威 round-trip 恢复到台面实例 assert _normalize_liquids(stock_inst.get_well("A1").tracker.liquids) == [ ("Water", 80.0, "ul") @@ -325,7 +353,7 @@ def test_material_creation_flows_host_plus_slave(tmp_path, monkeypatch) -> None: ) deducted_inst = node.resource_tracker.uuid_to_resources[deducted_uuid] assert deducted_inst.parent is deck_inst - assert len(node.driver.added_batches) == 3 + assert len(node.driver.added_batches) == 4 assert ( service.get_material(deducted_uuid).material.parent_material_uuid == deck_uuid @@ -360,9 +388,9 @@ def test_material_creation_flows_host_plus_slave(tmp_path, monkeypatch) -> None: ) # 设备投影:unload 卸载旧实例(resource_tree_remove),load 权威拉取重建 moved_tips = node.resource_tracker.uuid_to_resources[tips_uuid] - assert moved_tips is not local_tips + assert moved_tips is not placed_tips assert moved_tips.parent is deck_inst - assert node.driver.removed_batches[-1] == [local_tips] + assert node.driver.removed_batches[-1] == [placed_tips] assert node.driver.added_batches[-1] == [moved_tips] # ---- 终局:三种来源的物料在权威/台面上共存且互不串扰 ---- @@ -451,7 +479,7 @@ def _mutation(operation: str) -> InventoryMutation: lab_registry.resource_type_registry, "test_tip_rack_300ul", registry_entry(TIP_RACK_MODULE) ) tips = materials.create("test_tip_rack_300ul", name="tips_r1", node=node) - materials.assign(node, tips, parent="Bench_Deck", slot="T1") + [tips] = materials.assign(node, tips, parent="Bench_Deck", slot="T1")["resources"] assert service.get_material(tips.unilabos_uuid).material.parent_material_uuid == deck_uuid assert _site_by_label(service, deck_uuid, "T1").occupied_material_uuid == tips.unilabos_uuid @@ -464,7 +492,7 @@ def _mutation(operation: str) -> InventoryMutation: # 观察者自动快照(孔位加液同款:本地 state 变化 + commit -> 自动上报)在台面挂设备后 # 照常到达权威:hydrate_well 之前卡死就是因为根被解析成设备、快照集合对不上 plate_r1 = materials.create(plate("plate_r1"), node=node) - materials.assign(node, plate_r1, parent="Bench_Deck", slot="T2") + [plate_r1] = materials.assign(node, plate_r1, parent="Bench_Deck", slot="T2")["resources"] well = plate_r1.get_well("A1") well.tracker.add_liquid("Buffer", 25.0) well.tracker.commit() @@ -498,8 +526,10 @@ def test_discarded_tip_is_removed_from_authority(tmp_path, monkeypatch) -> None: monkeypatch.setattr(HostLinkConfig, "bind", "127.0.0.1") monkeypatch.setattr(HostLinkConfig, "port", 0) + device_uuid = str(uuid4()) + _register_device(service, device_uuid, "bench") local = HostLinkLocalRuntime() - node = local.add_driver(HostLinkDriverSpec("bench", _BenchDriver, {}, resource_uuid=str(uuid4()))) + node = local.add_driver(HostLinkDriverSpec("bench", _BenchDriver, {}, resource_uuid=device_uuid)) backend = HostLinkBackend(local, is_slave=False) backend.start() try: @@ -509,7 +539,7 @@ def test_discarded_tip_is_removed_from_authority(tmp_path, monkeypatch) -> None: deck = node.resource_tracker.uuid_to_resources[deck_uuid] tips = materials.create(tip_rack("tips_discard"), node=node) - materials.assign(node, tips, parent="Bench_Deck", slot="T1") + [tips] = materials.assign(node, tips, parent="Bench_Deck", slot="T1")["resources"] spot = tips.get_item("A1") other = tips.get_item("A2") @@ -594,7 +624,7 @@ def test_slave_observer_retires_discarded_tip_over_hostlink(tmp_path, monkeypatc materials.ensure(_build_deck(deck_uuid), gateway=gateway) _append_via_hostlink(host, deck_uuid, bind_parent_id=DEVICE_ID) tips = materials.create(tip_rack("tips_slave"), node=node, gateway=slave_gateway) - materials.assign(node, tips, parent="Bench_Deck", slot="T1") + [tips] = materials.assign(node, tips, parent="Bench_Deck", slot="T1")["resources"] observer = node.resource_tracker._material_snapshot_observer assert observer is not None @@ -633,8 +663,10 @@ def test_retired_tip_does_not_come_back_on_restore(tmp_path, monkeypatch) -> Non monkeypatch.setattr(HostLinkConfig, "port", 0) monkeypatch.setattr(BasicConfig, "is_host_mode", True) + device_uuid = str(uuid4()) + _register_device(service, device_uuid, "bench") local = HostLinkLocalRuntime() - node = local.add_driver(HostLinkDriverSpec("bench", _BenchDriver, {}, resource_uuid=str(uuid4()))) + node = local.add_driver(HostLinkDriverSpec("bench", _BenchDriver, {}, resource_uuid=device_uuid)) backend = HostLinkBackend(local, is_slave=False) backend.start() try: @@ -643,7 +675,7 @@ def test_retired_tip_does_not_come_back_on_restore(tmp_path, monkeypatch) -> Non materials.assign(node, deck_uuid) deck = node.resource_tracker.uuid_to_resources[deck_uuid] tips = materials.create(tip_rack("tips_restore"), node=node) - materials.assign(node, tips, parent="Bench_Deck", slot="T1") + [tips] = materials.assign(node, tips, parent="Bench_Deck", slot="T1")["resources"] spot = tips.get_item("A1") discarded = spot.tip diff --git a/tests/client/host/hostlink/test_material_io_deck_sync.py b/tests/client/host/hostlink/test_material_io_deck_sync.py index 059f07e1f..c2b2c5dc4 100644 --- a/tests/client/host/hostlink/test_material_io_deck_sync.py +++ b/tests/client/host/hostlink/test_material_io_deck_sync.py @@ -15,7 +15,7 @@ import pytest from tests.client.host.hostlink.test_warehouse_site_placement import DEVICE_ID, _bottle, stocker # noqa: F401 - fixture -from tests.plr_fixtures import site_deck +from tests.plr_fixtures import site_deck, device_material from tests.server.test_material_io_inventory import TIP_RACK, registry_template from unilabos.client.host.hostlink import downlink, main_hostlink_run from unilabos.client.host.hostlink.backend import HostLinkBackend @@ -59,7 +59,7 @@ def handler(tmp_path, monkeypatch): monkeypatch.setattr(HostLinkConfig, "bind", "127.0.0.1") monkeypatch.setattr(HostLinkConfig, "port", 0) local = HostLinkLocalRuntime() - node = local.add_driver(HostLinkDriverSpec(HANDLER_ID, _HandlerDriver, {}, resource_uuid=str(uuid4()))) + node = local.add_driver(HostLinkDriverSpec(HANDLER_ID, _HandlerDriver, {}, resource_uuid=device_material(gateway, HANDLER_ID))) backend = HostLinkBackend(local, is_slave=False) backend.start() monkeypatch.setattr(BasicConfig, "backend", "hostlink") diff --git a/tests/client/host/hostlink/test_warehouse_site_placement.py b/tests/client/host/hostlink/test_warehouse_site_placement.py index 13432da35..af2698292 100644 --- a/tests/client/host/hostlink/test_warehouse_site_placement.py +++ b/tests/client/host/hostlink/test_warehouse_site_placement.py @@ -1,7 +1,7 @@ """设备侧把物料放到仓库(PLR ``ItemizedCarrier`` / ``WareHouse``)库位上(FRAMEWORK_GAPS #29 / #30)。 仓库只接受 ``assign_resource_to_site``:物料挂在库位 holder 下,仓库的 canonical Site -同时记占用。``materials.assign``(RESOURCE_APPEND)、权威 transfer 的 load、资源树下行 +同时记占用。``materials.assign``(与 transfer 同一条路)、权威 transfer 的 load、资源树下行 (RESOURCE_TREE_SYNC)都要走这条路径;之后整棵仓库树从权威反序列化(下次启动)不出错, 观察者的快照也不报错。 """ @@ -24,6 +24,7 @@ from unilabos.resources.presets.warehouse import warehouse_factory from unilabos.server.execution_composition import set_materials_gateway from unilabos.server.services.materials import MaterialsService +from tests.plr_fixtures import device_material DEVICE_ID = "stocker" @@ -54,14 +55,14 @@ def stocker(tmp_path, monkeypatch): monkeypatch.setattr(HostLinkConfig, "bind", "127.0.0.1") monkeypatch.setattr(HostLinkConfig, "port", 0) local = HostLinkLocalRuntime() - node = local.add_driver(HostLinkDriverSpec(DEVICE_ID, _StockerDriver, {}, resource_uuid=str(uuid4()))) + node = local.add_driver(HostLinkDriverSpec(DEVICE_ID, _StockerDriver, {}, resource_uuid=device_material(gateway, DEVICE_ID))) backend = HostLinkBackend(local, is_slave=False) backend.start() try: warehouse = materials.create( warehouse_factory("stock", num_items_x=3, num_items_y=1, num_items_z=1), node=node ) - materials.assign(node, warehouse) + [warehouse] = materials.assign(node, warehouse)["resources"] yield service, gateway, node, warehouse finally: backend.stop() @@ -101,12 +102,12 @@ def _observer_errors(node) -> tuple: def test_assign_onto_a_warehouse_site(stocker) -> None: - """#29:materials.assign / RESOURCE_APPEND 按库位放上仓库。""" + """#29:materials.assign 按库位放上仓库(权威提交后本设备 load 重建)。""" service, gateway, node, warehouse = stocker bottle = materials.create(_bottle("assigned"), node=node) - materials.assign(node, bottle, parent=warehouse, slot="A02") + [bottle] = materials.assign(node, bottle, parent=warehouse, slot="A02")["resources"] assert warehouse["A02"].resource is bottle assert _authority_placement(service, warehouse) == {"A02": ("assigned", warehouse["A02"].name)} @@ -115,7 +116,7 @@ def test_assign_onto_a_warehouse_site(stocker) -> None: # 不指定库位:仓库只能按库位放物料,明确报错,权威不变 loose = materials.create(_bottle("loose"), node=node) - with pytest.raises(Exception, match="挂载"): + with pytest.raises(Exception, match="only holds materials on its Sites"): materials.assign(node, loose, parent=warehouse) assert _authority_placement(service, warehouse) == {"A02": ("assigned", warehouse["A02"].name)} diff --git a/tests/client/host/runtime/test_append_resource_commit.py b/tests/client/host/runtime/test_append_resource_commit.py index fa4d89fea..36127d1d6 100644 --- a/tests/client/host/runtime/test_append_resource_commit.py +++ b/tests/client/host/runtime/test_append_resource_commit.py @@ -1,7 +1,7 @@ """FRAMEWORK_GAPS #26:大物料树挂载不能在提交之后被等待方超时取消,每次取消都要留日志。 -``materials.assign`` / Host 下发 ``RESOURCE_APPEND`` 都经 ``run_node_coroutine`` 阻塞等待 -``node.append_resource``。挂载以一次根树快照收尾,树大时(1873 个物料的扣电台面)要几十秒。 +Host 下发 ``RESOURCE_APPEND`` 经 ``run_node_coroutine`` 阻塞等待 ``node.append_resource`` +(``append_resource_blocking``)。挂载以一次根树快照收尾,树大时(1873 个物料的扣电台面)要几十秒。 等待方的超时只能约束提交点之前的阶段(等锁、从权威拉取物料);本地 PLR 挂上、权威 move 落库之后再取消,本地与权威就各执一词,调用方还拿到一个"失败"。 """ @@ -21,7 +21,7 @@ from unilabos.client.materials import LocalMaterialsClient from unilabos.resources import materials from unilabos.server.services.materials import MaterialsService -from tests.plr_fixtures import site_deck, tip_rack +from tests.plr_fixtures import device_material, site_deck, tip_rack class _Bench: @@ -67,8 +67,9 @@ def bench(tmp_path): gateway = LocalMaterialsClient(service) authority = _SlowAuthority(gateway) runtime = HostLinkLocalRuntime() - node = runtime.add_driver(HostLinkDriverSpec("bench", _Bench, {}, resource_uuid="bench-uuid")) + node = runtime.add_driver(HostLinkDriverSpec("bench", _Bench, {}, resource_uuid=device_material(gateway, "bench"))) runtime.set_resource_service(authority) + service.set_resource_sync_dispatcher(runtime.dispatch_material_sync) runtime.start() deck_uuid = str(uuid4()) materials.ensure(site_deck(deck_uuid, "Bench_Deck", ("T1", "T2")), gateway=gateway) @@ -91,6 +92,16 @@ def bench(tmp_path): service.close() +def _append(node, tips, *, timeout: float) -> dict: + """Host 下发的 RESOURCE_APPEND:挂到台面 T2。""" + + return node.append_resource_blocking( + {"resource_uuid": [tips.unilabos_uuid], "bind_parent_id": "Bench_Deck", + "other_calling_param": {"slot": "T2"}}, + timeout, + ) + + def test_mount_is_not_cancelled_after_the_move_is_committed(bench) -> None: """快照回报比等待方的超时还慢:挂载照常走完,调用方拿到成功结果,不留半截状态。""" @@ -98,7 +109,7 @@ def test_mount_is_not_cancelled_after_the_move_is_committed(bench) -> None: tips = bench["tips"] started = time.monotonic() - result = materials.assign(bench["node"], tips, parent="Bench_Deck", slot="T2", timeout=3.0) + result = _append(bench["node"], tips, timeout=3.0) assert time.monotonic() - started >= 6.0 # 越过超时一直等到快照回报完成 @@ -119,7 +130,7 @@ def test_mount_cancelled_before_commit_is_logged_and_leaves_nothing_behind(bench deck_uuid = bench["deck_uuid"] with pytest.raises(TimeoutError): - materials.assign(bench["node"], tips, parent="Bench_Deck", slot="T2", timeout=0.3) + _append(bench["node"], tips, timeout=0.3) time.sleep(1.8) # 让被取消的协程有机会(错误地)继续执行 assert tips.parent is None diff --git a/tests/plr_fixtures.py b/tests/plr_fixtures.py index f05acf6f0..259f7d450 100644 --- a/tests/plr_fixtures.py +++ b/tests/plr_fixtures.py @@ -168,3 +168,22 @@ def _site(index: int, label: str) -> ResourceSite: ) deck.unilabos_uuid = deck_uuid return deck + + +def device_material(gateway: Any, device_id: str, *, sites: Sequence[Dict[str, Any]] = ()) -> str: + """在权威里登记一台设备的物料行(开机图对齐的结果),返回设备 uuid。 + + 物料放到设备自身(``materials.assign(node, x)``)就是挂到这一行下面:设备在权威里得有它。 + """ + + from unilabos.resources.adapters.device_site import apply_device_authority_state + from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance + + device_uuid = str(uuid4()) + config = ResourceDictInstance(ResourceDict.model_validate({ + "id": device_id, "uuid": device_uuid, "name": device_id, "type": "device", + "class": "test_device", "template_name": "test_device", "config": {}, "data": {}, "extra": {}, + "sites": None, "sites_initialized": False, + })) + apply_device_authority_state(config, {"available_sites": list(sites)}, "test_device", gateway=gateway) + return device_uuid diff --git a/tests/resources/test_materials_create_and_place.py b/tests/resources/test_materials_create_and_place.py index 9a80bbbf5..7b1254f44 100644 --- a/tests/resources/test_materials_create_and_place.py +++ b/tests/resources/test_materials_create_and_place.py @@ -18,6 +18,7 @@ from unilabos.resources.adapters.device_site import apply_device_authority_state from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance from unilabos.server.services.materials import MaterialsService +from unilabos.server.services.materials.core import MaterialValidationError from tests.plr_fixtures import plate DEVICE_TEMPLATE = "create_and_place_test_device" @@ -66,6 +67,8 @@ def device(tmp_path): HostLinkDriverSpec("placer", _Device, {}, resource_uuid=device_uuid) ) runtime.set_resource_service(AuthorityResourceService(gateway)) + # assign 与 transfer 同一条路:权威提交后经物料服务下发 unload / load + service.set_resource_sync_dispatcher(runtime.dispatch_material_sync) runtime.start() try: yield { @@ -181,14 +184,17 @@ def test_assign_moves_between_device_sites(device) -> None: service, node = device["service"], device["node"] created = materials.create(plate("mover"), node=node, site="slot_a", gateway=device["gateway"]) - materials.assign(node, created, slot="slot_b") + result = materials.assign(node, created, slot="slot_b") assert _site(service, device["device_uuid"], "slot_a").occupied_material_uuid is None assert ( _site(service, device["device_uuid"], "slot_b").occupied_material_uuid == created.unilabos_uuid ) - assert node.resource_tracker.uuid_to_resources[created.unilabos_uuid] is created + # 同设备换位也是一次 unload + load:本地按权威重建,tracker 里只有新的那一份 + [moved] = result["resources"] + assert node.resource_tracker.uuid_to_resources[created.unilabos_uuid] is moved + assert [res.name for res in node.resource_tracker.resources] == ["mover"] def test_assign_to_the_device_without_a_site_only_sets_the_parent(device) -> None: @@ -208,7 +214,7 @@ def test_assign_rejects_an_unknown_device_site_without_mounting(device) -> None: service, node = device["service"], device["node"] loose = materials.create(plate("stray"), gateway=device["gateway"]) - with pytest.raises(ValueError, match="slot_z"): + with pytest.raises(MaterialValidationError, match="slot_z"): materials.assign(node, loose, slot="slot_z") assert loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources @@ -251,16 +257,16 @@ def test_assign_moves_a_nested_material_off_its_plr_parent_onto_a_device_site(de created = materials.create(holder, node=node, site="slot_a", gateway=gateway) inner = next(child for child in created.children if child.name == "inner") - materials.assign(node, inner, slot="slot_b") + [moved] = materials.assign(node, inner, slot="slot_b")["resources"] assert service.get_material(inner.unilabos_uuid).material.parent_material_uuid == device["device_uuid"] assert _site(service, device["device_uuid"], "slot_b").occupied_material_uuid == inner.unilabos_uuid assert inner.parent is None and created.children == [] assert {res.name for res in node.resource_tracker.resources} == {"holder", "inner"} - assert node.resource_tracker.parent_resource(inner) is None + assert node.resource_tracker.parent_resource(moved) is None # 原父树与权威一致:严格快照不再因为「本地多一个孩子」被拒 materials.update(node, created) - materials.update(node, inner) + materials.update(node, moved) def test_assign_rejects_another_devices_site_uuid(device) -> None: @@ -276,7 +282,7 @@ def test_assign_rejects_another_devices_site_uuid(device) -> None: foreign = _site(service, other_uuid, "o1") loose = materials.create(plate("wanderer"), gateway=gateway) - with pytest.raises(ValueError, match="不存在"): + with pytest.raises(MaterialValidationError, match="has no Site"): materials.assign(node, loose, site=foreign.site_uuid) assert loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources @@ -314,6 +320,19 @@ def test_create_under_a_parent_without_a_site_gets_the_origin_and_restarts(devic assert [child.name for child in restored.children] == ["other"] +def test_assign_under_a_parent_without_a_site_gets_the_origin_and_restarts(device) -> None: + from pylabrobot.resources import Coordinate + + holder = _holder_on(device) + loose = materials.create(plate("loose_child"), gateway=device["gateway"]) + + [mounted] = materials.assign(device["node"], loose, parent=holder)["resources"] + + assert mounted.parent is device["node"].resource_tracker.uuid_to_resources[holder.unilabos_uuid] + assert mounted.location == Coordinate(0, 0, 0) + assert [child.name for child in _restart(device, holder.unilabos_uuid).children] == ["loose_child"] + + # ── 本地加载失败时不留分叉:先查前提,提交后失败就在同一条命令下撤销 ───────── @@ -384,3 +403,71 @@ async def from_the_executor(): run_node_coroutine(node, from_the_executor(), 5.0) assert len(service.list_materials()) == before + + +# ── assign 到库位就是一次物料移动:权威提交 → 原设备卸下 → 新设备重建 ───────── + + +@pytest.fixture +def second_device(device): + service, gateway = device["service"], device["gateway"] + device_uuid = str(uuid4()) + config = ResourceDictInstance(ResourceDict.model_validate({ + **_device_config(device_uuid).res_content.model_dump(by_alias=True), "id": "receiver", "name": "receiver", + })) + apply_device_authority_state(config, {"available_sites": DEVICE_SITES}, DEVICE_TEMPLATE, gateway=gateway) + runtime = HostLinkLocalRuntime() + node = runtime.add_driver(HostLinkDriverSpec("receiver", _Device, {}, resource_uuid=device_uuid)) + runtime.set_resource_service(AuthorityResourceService(gateway)) + first_dispatch = device["node"].__dict__["_hostlink_runtime"].dispatch_material_sync + + def dispatch(command): + target = runtime if command.device_id == "receiver" else None + return target.dispatch_material_sync(command) if target is not None else first_dispatch(command) + + service.set_resource_sync_dispatcher(dispatch) + runtime.start() + try: + yield {"node": node, "device_uuid": device_uuid} + finally: + runtime.stop() + + +def test_assign_onto_another_devices_site_unloads_it_from_the_holder(device, second_device) -> None: + service, source = device["service"], device["node"] + sample = materials.create(plate("traveller"), node=source, site="slot_a", gateway=device["gateway"]) + + [arrived] = materials.assign(second_device["node"], sample.unilabos_uuid, slot="slot_b")["resources"] + + assert sample.unilabos_uuid not in source.resource_tracker.uuid_to_resources + assert source.resource_tracker.resources == [] + assert second_device["node"].resource_tracker.uuid_to_resources[sample.unilabos_uuid] is arrived + assert service.get_material(sample.unilabos_uuid).material.parent_material_uuid == second_device["device_uuid"] + assert _site(service, device["device_uuid"], "slot_a").occupied_material_uuid is None + # 两边本地树都与权威一致:严格快照照常提交 + materials.update(second_device["node"], arrived) + + +def test_a_rejected_assign_onto_a_material_changes_nothing_locally(device) -> None: + """权威拒绝(库位只收别的模板)时本地不先挂:父物料下不会多出一个权威里没有的孩子。""" + + from tests.plr_fixtures import site_deck + + service, node, gateway = device["service"], device["node"], device["gateway"] + deck_uuid = str(uuid4()) + materials.ensure(site_deck(deck_uuid, "Bench_Deck", ("T1", "T2")), gateway=gateway) + materials.assign(node, deck_uuid) + t1 = next(site for site in service.get_material(deck_uuid).sites if site.label == "T1") + with service.write() as connection: + connection.execute( + "UPDATE site SET extra_json=? WHERE site_uuid=?", + ('{"allowed_resource_template_uuids": ["only_tip_racks"]}', t1.site_uuid), + ) + loose = materials.create(plate("refused"), gateway=gateway) + + with pytest.raises(Exception, match="只接受资源模板"): + materials.assign(node, loose, parent=deck_uuid, slot="T1") + + deck = node.resource_tracker.uuid_to_resources[deck_uuid] + assert deck.children == [] and loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources + assert service.get_material(loose.unilabos_uuid).material.parent_material_uuid is None diff --git a/unilabos/client/host/hostlink/backend.py b/unilabos/client/host/hostlink/backend.py index a48a7b2e4..4a49dba08 100644 --- a/unilabos/client/host/hostlink/backend.py +++ b/unilabos/client/host/hostlink/backend.py @@ -470,9 +470,8 @@ def dispatch_material_sync(self, command: Any) -> dict[str, Any]: data = command.model_dump(mode="json", exclude_none=False) device_id = str(data["device_id"]) - node = self.local.get_device(device_id) - if node is not None: - result = run_node_coroutine(node, node.material_sync(dict(data))) + if self.local.get_device(device_id) is not None: + result = self.local.dispatch_material_sync(data) elif self.server is not None and self.server.has_device(device_id): result = self.server.request_device( device_id, ActionType.MATERIAL_SYNC, data, timeout=30.0 diff --git a/unilabos/client/host/hostlink/local_runtime.py b/unilabos/client/host/hostlink/local_runtime.py index 60a9665b1..acd6d8a2d 100644 --- a/unilabos/client/host/hostlink/local_runtime.py +++ b/unilabos/client/host/hostlink/local_runtime.py @@ -1516,6 +1516,17 @@ def get_device(self, device_id: str) -> Optional["HostLinkDeviceNode"]: """按 device_id 取本进程设备节点(容忍 ``/devices/`` 前缀)。""" return self.devices.get(self._normalize_device_id(device_id)) + def dispatch_material_sync(self, command: Any) -> dict[str, Any]: + """物料服务 transfer 的本机投影(unload / load):在目标设备自己的执行器上执行并等结果。""" + + from unilabos.client.host.runtime.async_utils import run_node_coroutine + + data = command.model_dump(mode="json", exclude_none=False) if hasattr(command, "model_dump") else dict(command) + node = self.get_device(str(data["device_id"])) + if node is None: + raise RuntimeError(f"设备 {data['device_id']!r} 不在本进程,无法同步物料") + return run_node_coroutine(node, node.material_sync(dict(data))) + @staticmethod def _normalize_device_id(device_id: str) -> str: normalized = str(device_id or "").strip() diff --git a/unilabos/client/host/runtime/resource.py b/unilabos/client/host/runtime/resource.py index fe9add40c..5351ee9f7 100644 --- a/unilabos/client/host/runtime/resource.py +++ b/unilabos/client/host/runtime/resource.py @@ -638,6 +638,11 @@ def _gateway(self) -> MaterialGateway: raise RuntimeError("微后端 Materials Authority 尚未配置") return gateway + def gateway(self) -> MaterialGateway: + """设备节点接入的物料权威网关(快照、load / unload 用的同一个)。""" + + return self._gateway() + # ── 权威基线缓存与版本表 ───────────────────────────────────── def remember_baseline(self, tree: Any) -> None: diff --git a/unilabos/resources/materials.py b/unilabos/resources/materials.py index 652072313..32ca53359 100644 --- a/unilabos/resources/materials.py +++ b/unilabos/resources/materials.py @@ -8,7 +8,7 @@ - ``get``:按 uuid 或 resource id 取物料树(未命中抛错); - ``search``:按人读标签 ``display_name`` 精确搜索物料树(未命中返回 []); - ``resolve``:把单个 ResourceSlot 原始入参解析成带 uuid 的 PLR 实例; -- ``assign``:把权威已创建的物料挂载到设备的目标父物料下(append 门面); +- ``assign``:把权威已创建的物料放到本设备的父物料 / 库位上(经 transfer 的物料移动); - ``update``:把带权威 uuid 的(部分)物料树 diff/apply 回 authority; - ``remove``:按 uuid 或 resource id 删除权威物料树; - ``snapshot``:把整棵已登记 PLR 根树原子 diff/apply 到 authority; @@ -729,6 +729,14 @@ def _site_uuid(site: Any, parent_uuid: str, gateway: MaterialGateway) -> str: return str(matches[0].site_uuid) +def _node_gateway(node: Any) -> MaterialGateway: + """设备节点接入的物料权威(与它的快照、load / unload 同一个);节点没接入时按进程角色解析。""" + + service = node.__dict__.get("_device_resource_service") + gateway = getattr(service, "gateway", None) + return gateway() if callable(gateway) else resolve_materials_gateway() + + def _require_off_node_executor(node: Any, what: str) -> None: """阻塞等待本地挂载的调用不能跑在设备节点自己的事件循环上:挂载要排到那个循环里,会等到自己。""" @@ -987,68 +995,92 @@ def assign( parent: Any | None = None, slot: Any | None = None, site: Any | None = None, - location: Optional[Dict[str, float]] = None, - timeout: float = 30.0, + gateway: MaterialGateway | None = None, ) -> Dict[str, Any]: - """把权威已创建的物料挂载到本设备的目标父物料下(append 门面)。 + """把权威已创建的物料放到本设备的目标父物料 / 库位上:一次经物料服务的物料移动(transfer)。 - 与 Host 下发 RESOURCE_APPEND 完全同语义:内部即 - ``node.append_resource``(按 uuid 拉取/复用实例 -> 物理 assign -> - 权威 move 落父子与 Site 占用 -> 快照回写),在节点自己的执行器上 - 执行并阻塞等待完成。 + 与 :func:`transfer` 同一条路(``MaterialsService.transfer_material``):权威校验并提交移动 → + 原来持有它的设备 unload → 本设备 load(按权威重建这棵子树挂上)。同设备换位与跨设备一样走这条路; + 权威拒绝(库位被占、类别不符、设备只收 PLR 物料、PLR 键重名……)时本地什么都不改。 - ``resources``:PLR 实例(带权威 uuid)或 uuid 字符串,单个或列表; - - ``parent``:目标父物料(实例、uuid 或 PLR 键);省略或传设备节点本身表示挂到设备自身 - (本地是 tracker 根物料,不做 PLR assign;权威 parent 落设备物料); - - ``site``:库位实例(``post_init`` 给的 ``ResourceSite``)或权威 Site uuid; - label / 数字索引按 ``slot`` 处理; - - ``slot``:label 或 0-based 数字字符串(如 ``"A1"`` / ``"0"``); - - 设备自身的库位同样适用:``assign(node, sample, site=sites["site_1"])`` 或 - ``slot="site_1"``,权威 move 占用设备库位;不给库位时只落父子关系; - - 一个库位只放一个物料:给了 ``site`` / ``slot`` 时一次只能挂一个物料; - - ``timeout``:只约束提交点之前(等锁、从权威拉取物料),超时取消挂载、什么都不改; - 本地挂上之后,权威 move 与快照回报一定走完再返回(大台面的整树快照要几十秒), - 不会在提交之后被取消(见 ``DeviceNode.append_resource_blocking``)。 - - 本函数为阻塞式,供驱动线程 / 脚本调用;已在节点执行器内的异步代码 - 请直接 ``await node.append_resource(payload)``。 + - ``parent``:目标父物料(实例、uuid 或本设备持有的 PLR 键);省略或传设备节点本身表示设备自身; + - ``site``:库位实例(``post_init`` 给的 ``ResourceSite``)、Site uuid、label 或库位自己的 index; + - ``slot``:同 ``site``(label 或 index),两者都给时必须指向同一个库位; + - 一个库位只放一个物料:给了库位时一次只能放一个物料;不给库位时只落父子关系,位置是原点 + (父物料自己排布库位时按它算)。 + + 原持有设备按权威的归属推断(最近的设备祖先,或根物料登记的所属设备);不属于任何设备的物料 + 没有要卸下的地方。返回 ``resources``:本设备 tracker 里重建后的实例(与传入的不是同一个对象)。 + 阻塞式,不能在本设备的执行器线程里调用(load 要排到那个执行器上)。 """ items = resources if isinstance(resources, (list, tuple)) else [resources] resource_uuids = [material_uuid(item) for item in items] + gw = gateway or _node_gateway(node) + _require_off_node_executor(node, "materials.assign") if parent is None or parent is node: - bind_parent_id = str(node.device_id) + target_uuid = _parent_material_uuid(node, None) + elif isinstance(parent, str) and not _looks_like_uuid(parent.strip()): + target_uuid = material_uuid(node.resource_tracker.figure_resource({"name": parent.strip()}), "父") else: - bind_parent_id = str( - getattr(parent, "unilabos_uuid", None) or getattr(parent, "name", parent) - ) - other: Dict[str, Any] = {} - if slot is not None and str(slot).strip() != "": - other["slot"] = str(slot).strip() - if site is not None: - site_uuid = _site_instance_uuid(site) - selector = str(site).strip() - if site_uuid is None and _looks_like_uuid(selector): - site_uuid = selector - if site_uuid is not None: - other["site"] = site_uuid - elif selector: - if other.get("slot", selector) != selector: - raise ValueError(f"site={site!r} 与 slot={slot!r} 指向不同库位") - other["slot"] = selector - if ("site" in other or "slot" in other) and len(resource_uuids) != 1: + target_uuid = material_uuid(parent, "父") + selectors = { + str(_site_instance_uuid(value) or value).strip() + for value in (site, slot) + if value is not None and str(value).strip() != "" + } + if len(selectors) > 1: + raise ValueError(f"site={site!r} 与 slot={slot!r} 指向不同库位") + selector = next(iter(selectors), None) + if selector is not None and len(resource_uuids) != 1: raise ValueError( f"一个库位只能放一个物料:指定库位时一次只能挂一个物料,实际 {len(resource_uuids)} 个" ) - payload: Dict[str, Any] = { - "device_id": str(node.device_id), - "resource_uuid": resource_uuids, - "bind_parent_id": bind_parent_id, - "bind_location": dict(location or {"x": 0.0, "y": 0.0, "z": 0.0}), + target_device = str(node.device_id).split("/")[-1] + by_source: Dict[str, List[str]] = {} + for item_uuid in resource_uuids: + source = find_owner_device(item_uuid, gateway=gw) or target_device + by_source.setdefault(source, []).append(item_uuid) + from unilabos.client.host.runtime.resource import _is_no_change_error + + tracker = node.resource_tracker + moves: List[Dict[str, Any]] = [] + for source, group in by_source.items(): + command_uuid = str(uuid4()) + try: + result = gw.transfer_material( + InventoryMutation( + command_uuid=command_uuid, + effect_key=f"transfer_material:{command_uuid}", + operation="transfer_material", + actor_type=ACTOR_DEVICE, + actor_uuid=str(getattr(node, "resource_uuid", "") or "") or target_device, + ), + MaterialTransfer( + source_device_id=source, + target_device_id=target_device, + items=[ + MaterialTransferItem( + material_uuid=item_uuid, target_material_uuid=target_uuid, target_site=selector + ) + for item_uuid in group + ], + ), + ) + except Exception as exc: + # 已经在目标位置、本设备也持有它:幂等,什么都不做 + if _is_no_change_error(exc) and all(item in tracker.uuid_to_resources for item in group): + continue + raise + moves.extend(value.model_dump(mode="json", exclude_none=False) for value in result.data.materials) + return { + "success": True, + "material_uuids": resource_uuids, + "target_material_uuid": target_uuid, + "resources": [tracker.uuid_to_resources[item_uuid] for item_uuid in resource_uuids], + "moves": moves, } - if other: - payload["other_calling_param"] = other - return node.append_resource_blocking(payload, timeout) async def snapshot( From ca83626c5c7ff300e146eb003b4b2c7980c058aa Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:20:38 +0800 Subject: [PATCH 35/59] fix(materials): V1 POST /materials initializes a PLR instance and goes through the instantiate path V1 POST /materials wrote an identity-only node from the template, without a PLR instance, so placing it on a device Site was always rejected ("only PLR materials") and nothing it created could be deserialized on a device. The request now initializes a PLR instance first and converts it with the same plr_resources_to_create path as instantiate_material: - config.type given: the template definition's config plus the request's config / data, deserialized through ResourceTreeSet; - otherwise a registry PLR resource template is instantiated from the registry (with its default children); - otherwise the template's implementation (module_name's class, or class_name) when it is a known PLR class, deserialized as above. The root then gets the uuid, the resource_id as its PLR key, the display name, barcode, description, meta_data and V1 position, and the tree is created, placed and filled in the existing single transaction. A template that cannot be instantiated is rejected with 1000 naming the template and asking for config.type; nothing is created. Tests that create materials from class-less V1 templates now declare a PLR class on the template. --- .../server/test_content_quantity_workflow.py | 2 +- tests/server/test_inventory_seam_v1.py | 4 +- .../test_scheduler_inventory_authority.py | 4 +- tests/server/test_task_inventory_bindings.py | 4 +- tests/server/test_v1_inventory_api.py | 6 +- tests/server/test_v1_lab_workspace.py | 6 +- tests/server/test_v1_resource_contract.py | 55 +++++++++++ .../services/materials/resource_contract.py | 97 ++++++++++++++----- 8 files changed, 146 insertions(+), 32 deletions(-) diff --git a/tests/server/test_content_quantity_workflow.py b/tests/server/test_content_quantity_workflow.py index 2f80ce49d..8bf155568 100644 --- a/tests/server/test_content_quantity_workflow.py +++ b/tests/server/test_content_quantity_workflow.py @@ -30,7 +30,7 @@ def lab(tmp_path): materials = MaterialsService(tmp_path / "materials.db") contents = ContentContract(materials, compound_source=None) contract = ResourceContract(materials) - template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource"}])["templates"][0] + template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource", "class": {"module": "pylabrobot.resources:Container", "type": "pylabrobot"}}])["templates"][0] bottle = contract.create_material({"resource_template_uuid": template["uuid"], "name": "缓冲液瓶"}) info = contents.create_reagent_info({"name": "PBS", "physical_state": "liquid"}) reagent = contents.create_reagent({"material_uuid": bottle["uuid"], "reagent_info_uuid": info["uuid"], diff --git a/tests/server/test_inventory_seam_v1.py b/tests/server/test_inventory_seam_v1.py index a4290a5af..1a80c8c7c 100644 --- a/tests/server/test_inventory_seam_v1.py +++ b/tests/server/test_inventory_seam_v1.py @@ -207,7 +207,7 @@ def test_content_reservation_reconcile_and_reagent_lineage(seam) -> None: stack, materials = seam contents = ContentContract(materials, compound_source=None) contract = ResourceContract(materials) - template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource"}])["templates"][0] + template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource", "class": {"module": "pylabrobot.resources:Container", "type": "pylabrobot"}}])["templates"][0] bottle = contract.create_material({"resource_template_uuid": template["uuid"], "name": "试剂瓶"}) info = contents.create_reagent_info({"name": "乙醇", "cas": "64-17-5", "physical_state": "liquid"}) reagent = contents.create_reagent({"material_uuid": bottle["uuid"], "reagent_info_uuid": info["uuid"], @@ -320,7 +320,7 @@ def test_settled_aliquot_is_a_consumption_of_the_source_contents(tmp_path) -> No try: contents = ContentContract(materials, compound_source=None) contract = ResourceContract(materials) - template = contract.sync_resource_templates([{"id": "tube", "registry_type": "resource"}])["templates"][0] + template = contract.sync_resource_templates([{"id": "tube", "registry_type": "resource", "class": {"module": "pylabrobot.resources:Container", "type": "pylabrobot"}}])["templates"][0] source, target = (contract.create_material({"resource_template_uuid": template["uuid"], "name": name}) for name in ("母液", "子管")) info = contents.create_reagent_info({"name": "乙醇", "cas": "64-17-5", "physical_state": "liquid"}) diff --git a/tests/server/test_scheduler_inventory_authority.py b/tests/server/test_scheduler_inventory_authority.py index 00b3cc31f..1b288c4f6 100644 --- a/tests/server/test_scheduler_inventory_authority.py +++ b/tests/server/test_scheduler_inventory_authority.py @@ -750,7 +750,9 @@ def test_backend_scheduler_reserves_container_content_for_the_task(tmp_path) -> try: contents = ContentContract(service, compound_source=None) contract = ResourceContract(service) - template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource"}])["templates"][0] + template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource", + "class": {"module": "pylabrobot.resources:Container", + "type": "pylabrobot"}}])["templates"][0] bottle = contract.create_material({"resource_template_uuid": template["uuid"], "name": "缓冲液瓶"}) info = contents.create_reagent_info({"name": "PBS", "physical_state": "liquid"}) reagent = contents.create_reagent({"material_uuid": bottle["uuid"], "reagent_info_uuid": info["uuid"], diff --git a/tests/server/test_task_inventory_bindings.py b/tests/server/test_task_inventory_bindings.py index fa12599e7..f0d94d5b8 100644 --- a/tests/server/test_task_inventory_bindings.py +++ b/tests/server/test_task_inventory_bindings.py @@ -27,7 +27,9 @@ def __init__(self, tmp_path, *, quantity_a: float = 100, quantity_b: float = 100 self.stack = Stack(tmp_path) self.contents = ContentContract(self.stack.materials, compound_source=None) contract = ResourceContract(self.stack.materials) - template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource"}])["templates"][0] + template = contract.sync_resource_templates([{"id": "bottle", "registry_type": "resource", + "class": {"module": "pylabrobot.resources:Container", + "type": "pylabrobot"}}])["templates"][0] info = self.contents.create_reagent_info({"name": "PBS", "physical_state": "liquid"}) self.bottles, self.reagents = [], [] for name, quantity in (("瓶 A", quantity_a), ("瓶 B", quantity_b)): diff --git a/tests/server/test_v1_inventory_api.py b/tests/server/test_v1_inventory_api.py index 9e2117c3f..30e77517b 100644 --- a/tests/server/test_v1_inventory_api.py +++ b/tests/server/test_v1_inventory_api.py @@ -187,7 +187,7 @@ def test_typed_lot_commands_inbound_correct_reconcile_and_reads(stack) -> None: def test_reagent_dispense_command_matches_v1_console_contract(stack) -> None: _service, client = stack identities = {item["name"]: item["uuid"] for item in ok_data(client.post("/api/v1/resource-templates", json={ - "resources": [{"id": "bottle", "registry_type": "resource", "category": ["container"]}]}))["templates"]} + "resources": [{"id": "bottle", "registry_type": "resource", "category": ["container"], "class": {"module": "pylabrobot.resources:Container", "type": "pylabrobot"}}]}))["templates"]} source, *targets = ( ok_data(client.post("/api/v1/materials", json={"resource_template_uuid": identities["bottle"], "name": name}), status=201) for name in ("源瓶", "分装-1", "分装-2") @@ -218,7 +218,7 @@ def test_reagent_dispense_command_matches_v1_console_contract(stack) -> None: def test_content_reservations_prevent_overdrawing_a_bottle(stack) -> None: _service, client = stack identities = {item["name"]: item["uuid"] for item in ok_data(client.post("/api/v1/resource-templates", json={ - "resources": [{"id": "bottle", "registry_type": "resource"}]}))["templates"]} + "resources": [{"id": "bottle", "registry_type": "resource", "class": {"module": "pylabrobot.resources:Container", "type": "pylabrobot"}}]}))["templates"]} bottle = ok_data(client.post("/api/v1/materials", json={"resource_template_uuid": identities["bottle"], "name": "瓶"}), status=201) info = ok_data(client.post("/api/v1/reagent-infos", json={"name": "水", "cas": "7732-18-5"}), status=201) reagent = ok_data(client.post("/api/v1/reagents", json={ @@ -249,7 +249,7 @@ def reserve(command_id, task, quantity, unit="ml"): def test_material_source_bindings_share_or_exclude_and_block_delete(stack) -> None: _service, client = stack identities = {item["name"]: item["uuid"] for item in ok_data(client.post("/api/v1/resource-templates", json={ - "resources": [{"id": "bottle", "registry_type": "resource"}]}))["templates"]} + "resources": [{"id": "bottle", "registry_type": "resource", "class": {"module": "pylabrobot.resources:Container", "type": "pylabrobot"}}]}))["templates"]} bottle = ok_data(client.post("/api/v1/materials", json={"resource_template_uuid": identities["bottle"], "name": "瓶"}), status=201) def bind(command_id, task, policy): diff --git a/tests/server/test_v1_lab_workspace.py b/tests/server/test_v1_lab_workspace.py index e5d3d3fbb..8525720af 100644 --- a/tests/server/test_v1_lab_workspace.py +++ b/tests/server/test_v1_lab_workspace.py @@ -39,8 +39,10 @@ def test_profile_layout_zones_and_placements_are_gone(lab) -> None: def test_warehouse_assembly_and_demo_seed(lab) -> None: _service, client = lab identities = {item["name"]: item["uuid"] for item in ok_data(client.post("/api/v1/resource-templates", json={ - "resources": [{"id": "deck", "registry_type": "resource", "available_sites": [{"id": "A1", "label": "A1"}]}, - {"id": "tube", "registry_type": "resource"}]}))["templates"]} + "resources": [{"id": "deck", "registry_type": "resource", "available_sites": [{"id": "A1", "label": "A1"}], + "class": {"module": "pylabrobot.resources:Resource", "type": "pylabrobot"}}, + {"id": "tube", "registry_type": "resource", + "class": {"module": "pylabrobot.resources:Container", "type": "pylabrobot"}}]}))["templates"]} deck = ok_data(client.post("/api/v1/materials", json={"resource_template_uuid": identities["deck"], "name": "台面-1"}), status=201) ok_data(client.post("/api/v1/materials", json={ "resource_template_uuid": identities["tube"], "name": "管-1", diff --git a/tests/server/test_v1_resource_contract.py b/tests/server/test_v1_resource_contract.py index b30a0ebaf..f843d8257 100644 --- a/tests/server/test_v1_resource_contract.py +++ b/tests/server/test_v1_resource_contract.py @@ -201,6 +201,61 @@ def total() -> int: assert ok_data(client.get(f"/api/v1/sites/{site_uuid}"))["occupied_material_uuid"] == placed["uuid"] +def test_v1_create_initializes_a_plr_material_that_a_device_site_accepts(tmp_path) -> None: + """V1 POST /materials 先初始化出 PLR 实例(config.type 或模板的 PLR 类),能放上设备库位、能反序列化。""" + + from uuid import uuid4 + + from unilabos.client.materials import LocalMaterialsClient + from unilabos.resources import materials + from unilabos.resources.adapters.device_site import apply_device_authority_state + from unilabos.resources.resource_tracker import ResourceDict, ResourceDictInstance + + service = MaterialsService(tmp_path / "materials.db") + device_uuid = str(uuid4()) + device = ResourceDictInstance(ResourceDict.model_validate({ + "id": "v1-device", "uuid": device_uuid, "name": "v1-device", "type": "device", "class": "v1_device", + "template_name": "v1_device", "config": {}, "data": {}, "extra": {}, "sites": None, "sites_initialized": False, + })) + apply_device_authority_state(device, {"available_sites": [{"index": 1, "label": "s1"}, {"index": 2, "label": "s2"}]}, + "v1_device", gateway=LocalMaterialsClient(service)) + sites = {site.label: site.site_uuid for site in service.get_material(device_uuid).sites} + app = FastAPI() + install_materials_api(app, service) + try: + with TestClient(app) as client: + identities = _templates(client) + placed = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "设备上的瓶", + "config": {"max_volume": 500}, + "site_placement": {"action": "place", "site_uuid": sites["s1"]}, + }), status=201) + assert placed["parent_uuid"] == device_uuid and placed["current_site"]["uuid"] == sites["s1"] + assert placed["config"]["type"] == "Container" and placed["config"]["max_volume"] == 500 + restored = materials.get(placed["uuid"], gateway=LocalMaterialsClient(service)).to_plr_resources()[0] + assert type(restored).__name__ == "Container" and restored.max_volume == 500 + + # 显式 config.type 优先于模板的实现类 + typed = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["tube_rack_2"], "name": "显式类型", + "config": {"type": "Container"}, + "site_placement": {"action": "place", "site_uuid": sites["s2"]}, + }), status=201) + assert typed["config"]["type"] == "Container" + + # 实例化不出来:说明原因(1000),不建任何东西 + odd = ok_data(client.post("/api/v1/resource-templates", json={"resources": [{ + "id": "odd_thing", "registry_type": "resource", "class": {"module": "lab.custom:Thing", "type": "python"}, + "category": ["thing"], + }]}))["templates"][0]["uuid"] + before = ok_data(client.get("/api/v1/materials", params={"page_size": 100}))["total"] + failed = client.post("/api/v1/materials", json={"resource_template_uuid": odd, "name": "怪东西"}).json() + assert failed["code"] == 1000 and "config.type" in str(failed) + assert ok_data(client.get("/api/v1/materials", params={"page_size": 100}))["total"] == before + finally: + service.close() + + def test_v1_material_records_carry_inventory_facts(client) -> None: """V1 物料 DTO 带 inventory_status / inventory_presence / disposition,由生命周期派生。""" diff --git a/unilabos/server/services/materials/resource_contract.py b/unilabos/server/services/materials/resource_contract.py index 6410c9b02..671bb6704 100644 --- a/unilabos/server/services/materials/resource_contract.py +++ b/unilabos/server/services/materials/resource_contract.py @@ -18,9 +18,7 @@ InventoryMutation, MaterialDataWrite, MaterialDelete, - MaterialIdentityWrite, MaterialMove, - MaterialNodeCreate, MaterialPatch, MaterialPlacement, MaterialPosition, @@ -35,6 +33,7 @@ MaterialNoChangeError, MaterialNotFoundError, MaterialsService, + MaterialsServiceError, MaterialValidationError, ) @@ -623,9 +622,6 @@ def create_material(self, values: Mapping[str, Any]) -> dict[str, Any]: "Material barcode or sibling name conflicts with an existing material", conflict="identity" ) relative = values.get("relative_position") - position = MaterialPosition() - if isinstance(relative, Mapping): - position = self._position_from_v1(relative) material_uuid = str(uuid4()) # 放入库位 = 挂到库位的所属物料并占用它;只给父物料 = 只落父子关系。与建树同一事务(MaterialPlacement) tree_placement: Optional[MaterialPlacement] = None @@ -633,23 +629,20 @@ def create_material(self, values: Mapping[str, Any]) -> dict[str, Any]: tree_placement = MaterialPlacement(parent_material_uuid=site.owner_material_uuid, site=site_uuid) elif parent_uuid: tree_placement = MaterialPlacement(parent_material_uuid=parent_uuid) - tree = MaterialTreeCreate(placement=tree_placement, nodes=[MaterialNodeCreate( - client_ref="material", - material_uuid=material_uuid, - identity=MaterialIdentityWrite( - # 物料 name 由权威写成 uuid;PLR 键取全局唯一的 resource_id - resource_id=self._resource_id(name), - display_name=display_name, - description=str(values.get("description") or ""), - resource_type=template.resource_type, - class_name=template.class_name or template.name, - barcode=barcode, - template_name=template.name, - config=_mapping(values.get("config")), - meta_data=_mapping(values.get("meta_data")), - ), - position=position, - )]) + tree = self._instantiated_tree(template, values, resource_id=self._resource_id(name)) + tree.placement = tree_placement + root = next(node for node in tree.nodes if node.parent_client_ref is None) + root.material_uuid = material_uuid + identity = root.identity + identity.display_name = display_name + identity.description = str(values.get("description") or "") + identity.resource_type = template.resource_type + identity.class_name = template.class_name or template.name + identity.template_name = template.name + identity.barcode = barcode + identity.meta_data = _mapping(values.get("meta_data")) + if isinstance(relative, Mapping): + root.position = self._position_from_v1(relative) reagent = values.get("reagent") content: Optional[dict[str, Any]] = None try: @@ -681,6 +674,66 @@ def create_material(self, values: Mapping[str, Any]) -> dict[str, Any]: result["reagent"] = content return result + @staticmethod + def _instantiated_tree( + template: ResourceTemplateRead, values: Mapping[str, Any], *, resource_id: str + ) -> MaterialTreeCreate: + """V1 新建物料先初始化出 PLR 实例,再按 instantiate 同一条转换(``plr_resources_to_create``)变成建树请求。 + + 这样的物料带完整的 ``config.type`` 与 PLR 字段,能放上设备库位,设备重启时也反序列化得了。实例来源: + + - 请求的 config 给了 ``type``(PLR 类名):用模板定义里的 config、请求的 config / data 按 + ``ResourceTreeSet`` 反序列化出来; + - 否则模板是注册表里的 PLR 资源类:按注册表实例化(带默认孩子,与 ``instantiate_material`` 相同); + - 否则模板的实现(``module_name`` 的类名,或 ``class_name``)是已知的 PLR 类:同第一条。 + + 都不满足、或反序列化失败时报 1000,说明哪里不能实例化。PLR 名(PLR 键)是 ``resource_id``。 + """ + + from unilabos.resources.adapters.plr_materials import plr_resources_to_create + from unilabos.resources.material_class import registry_resource_entry + from unilabos.resources.materials import instantiate_registry_resource + from unilabos.resources.resource_tracker import ( + ResourceTreeSet, + find_plr_resource_class, + set_resource_uuid, + walk_resources, + ) + + definition_config = _mapping((template.definition or {}).get("config")) + config = {**definition_config, **_mapping(values.get("config"))} + plr_type = str(_mapping(values.get("config")).get("type") or "").strip() + entry = registry_resource_entry(template.name) + registry_class = isinstance(entry, Mapping) and _mapping(entry.get("class")).get("type") == "pylabrobot" + try: + if not plr_type and registry_class: + draft = instantiate_registry_resource(template.name, resource_id) + else: + if not plr_type: + implementation = str(template.module_name or "").partition(":")[2] or str(template.class_name or "") + known = str(config.get("type") or "").strip() or implementation + plr_type = known if known and find_plr_resource_class(known) is not None else "" + if not plr_type: + raise ValueError( + f"模板 {template.name} 不是注册表里的 PLR 资源类,实现 {template.module_name or template.class_name!r} " + "也不是已知的 PLR 类;请在 config.type 里给出 PLR 类名" + ) + node = { + "id": resource_id, "uuid": str(uuid4()), "name": resource_id, "type": template.resource_type, + "class": template.class_name or template.name, "template_name": template.name, + "config": {**config, "type": plr_type}, "data": dict(_mapping(values.get("data"))), + "parent_uuid": None, + } + draft = ResourceTreeSet.from_raw_dict_list([node]).to_plr_resources()[0] + # 只是建树用的草稿:去掉临时 uuid,由权威发号 + for item in walk_resources(draft): + set_resource_uuid(item, "") + return plr_resources_to_create([draft]) + except MaterialsServiceError: + raise + except Exception as exc: # noqa: BLE001 - 实例化失败一律是请求不合法 + raise MaterialValidationError(f"无法按模板 {template.name} 初始化 PLR 物料:{exc}") from None + def find_by_barcode(self, barcode: str) -> Optional[str]: row = self.materials.connection.execute( "SELECT material_uuid FROM material WHERE barcode=? AND deleted_at_ms IS NULL", (barcode,) From b7d6ac2d7ff8bc99c382de8fb760481b2d24b9c5 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:20:47 +0800 Subject: [PATCH 36/59] test: the atomicity, reserve and liquid-handler deck tests exercise the paths they name - V1 create-place-fill atomicity: the failing request used to be rejected by the FastAPI request model and never reached the service. It now passes the model and fails inside create_reagent, after the tree and its placement were written in the same transaction (a spy checks that), and the test asserts material and ledger counts are unchanged. - inventory.reserve malformed payload: node_requirements was a list, so the command failed at dict(list) instead of the bad quantity. It is now a node -> requirements mapping and the rejection names the bad value. - A real PLR LiquidHandler built through PyLabRobotCreator goes through LiquidHandler.deserialize (to_dict=True) with its deck referenced from children[0]: the deck and its labware are deserialized and tracked once; a deck holding an unknown class puts the device into maintenance mode. --- .../test_device_material_maintenance.py | 54 ++++++++++++++ tests/server/test_v1_inventory_api.py | 5 +- tests/server/test_v1_resource_contract.py | 73 ++++++++++++------- 3 files changed, 106 insertions(+), 26 deletions(-) diff --git a/tests/client/host/hostlink/test_device_material_maintenance.py b/tests/client/host/hostlink/test_device_material_maintenance.py index 00d100fc9..2a2eb58d5 100644 --- a/tests/client/host/hostlink/test_device_material_maintenance.py +++ b/tests/client/host/hostlink/test_device_material_maintenance.py @@ -139,3 +139,57 @@ def test_health_lists_the_device_in_maintenance(registry, monkeypatch) -> None: [record] = client.get("/api/v1/health").json()["data"]["unavailable_devices"] assert record["device_id"] == "heater_bad" and record["maintenance"] is True assert record["material_type"] == "NotAPlrClass" + + +def _liquid_handler(deck_children=(), *, break_with=None): + """真的 PLR LiquidHandler:构造器走 ``LiquidHandler.deserialize``(to_dict=True),台面按 PLR 键引用。""" + + from pylabrobot.legacy.liquid_handling import LiquidHandler + from pylabrobot.legacy.liquid_handling.backends.chatterbox import LiquidHandlerChatterboxBackend + from pylabrobot.resources import Coordinate, Deck + + deck = Deck(name="deck", size_x=500, size_y=300, size_z=10) + for index, child in enumerate(deck_children): + deck.assign_child_resource(child, location=Coordinate(10 + 150 * index, 10, 0)) + nodes = ResourceTreeSet.from_plr_resources([deck], known_random_uuid=True).dump()[0] + if break_with is not None: + break_with(nodes) + deck_node = ResourceTreeSet.load([nodes]).trees[0].root_node + template = LiquidHandler( + backend=LiquidHandlerChatterboxBackend(), deck=Deck(name="deck", size_x=500, size_y=300, size_z=10) + ).serialize() + # LiquidHandler.deserialize 从 children[0] 取台面 + template["children"] = [{"_resource_child_name": "deck", "_resource_type": "pylabrobot.resources:Deck"}] + return LiquidHandler, deck_node, {"data": template} + + +def test_a_liquid_handler_is_deserialized_with_its_deck_and_labware(): + from unilabos.client.host.runtime.driver_creator import PyLabRobotCreator + from unilabos.resources.resource_tracker import DeviceNodeResourceTracker + + handler_class, deck_node, config = _liquid_handler([plate("p1")]) + plate_uuid = deck_node.children[0].res_content.uuid + tracker = DeviceNodeResourceTracker() + + driver = PyLabRobotCreator(handler_class, [deck_node], tracker).create_instance(config) + + assert type(driver) is handler_class + assert [child.name for child in driver.deck.children] == ["p1"] + assert tracker.uuid_to_resources[deck_node.res_content.uuid] is driver.deck + assert tracker.uuid_to_resources[plate_uuid] is driver.deck.get_resource("p1") + + +def test_a_liquid_handler_whose_deck_holds_a_bad_material_enters_maintenance(): + from unilabos.client.host.runtime.driver_creator import PyLabRobotCreator + from unilabos.resources.resource_tracker import DeviceNodeResourceTracker + + def unknown_plate(nodes: list[dict]) -> None: + nodes[1]["config"]["type"] = "NotAPlrClass" + + _handler_class, deck_node, _config = _liquid_handler([plate("p1")], break_with=unknown_plate) + + with pytest.raises(DeviceMaterialError) as caught: + PyLabRobotCreator(_handler_class, [deck_node], DeviceNodeResourceTracker()) + + assert caught.value.material_uuid == deck_node.children[0].res_content.uuid + assert caught.value.material_type == "NotAPlrClass" diff --git a/tests/server/test_v1_inventory_api.py b/tests/server/test_v1_inventory_api.py index 30e77517b..010edc18e 100644 --- a/tests/server/test_v1_inventory_api.py +++ b/tests/server/test_v1_inventory_api.py @@ -112,7 +112,8 @@ def test_command_entry_runs_materials_v1_mutations_idempotently(stack) -> None: ("command_type", "payload"), [ ("inventory.template.upsert", {"template_id": "probe", "spec": "not-an-object"}), - ("inventory.reserve", {"workflow_id": "wf-1", "node_requirements": [{"quantity": "lots"}]}), + # node_requirements 本身形状正确(节点 -> 需求列表),坏的是数量:失败发生在 float(quantity) + ("inventory.reserve", {"workflow_id": "wf-1", "node_requirements": {"node-1": [{"quantity": "lots"}]}}), ("inventory.reconcile_count", {"lot_id": "lot-x", "measured_count": "many"}), ("material.move", [1, 2]), ], @@ -131,6 +132,8 @@ def test_typed_command_with_malformed_payload_is_a_recorded_rejection(stack, com first = command_body(client.post("/api/v1/inventory/commands", json=body)) assert first["status"] == "rejected" and first["code"] == 1000 and first["replayed"] is False, first assert first["error_code"] == "invalid_material" + if command_type == "inventory.reserve": + assert "lots" in str(first), first replay = command_body(client.post("/api/v1/inventory/commands", json=body)) assert replay["status"] == "rejected" and replay["code"] == 1000 and replay["replayed"] is True processed = ok_data(client.get("/api/v1/inventory/commands/processed"))["commands"] diff --git a/tests/server/test_v1_resource_contract.py b/tests/server/test_v1_resource_contract.py index f843d8257..3e131a890 100644 --- a/tests/server/test_v1_resource_contract.py +++ b/tests/server/test_v1_resource_contract.py @@ -172,33 +172,56 @@ def test_material_create_place_update_ledger_and_delete(client) -> None: error_of(client.get(f"/api/v1/materials/{bottle['uuid']}"), 6000) -def test_v1_create_places_and_fills_in_one_transaction(client) -> None: - """建物料、放入库位与装液是同一个事务:装液失败时物料与落位一起回滚,库位仍空、不留半成品。""" +def test_v1_create_places_and_fills_in_one_transaction(tmp_path, monkeypatch) -> None: + """建物料、放入库位与装液是同一个事务:装液失败时物料与落位一起回滚,库位仍空、不留半成品。 - identities = _templates(client) - rack = ok_data(client.post("/api/v1/materials", json={ - "resource_template_uuid": identities["tube_rack_2"], "name": "架-T"}), status=201) - site_uuid = rack["site_uuids"][0] + 失败必须发生在服务里(建树与落位已经写进事务之后),而不是被请求模型挡在门外。 + """ - def total() -> int: - return ok_data(client.get("/api/v1/materials", params={"page": 1, "page_size": 100}))["total"] - - before = total() - failed = client.post("/api/v1/materials", json={ - "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-坏", - "site_placement": {"action": "place", "site_uuid": site_uuid}, - "reagent": {"quantity": 5}, # 缺 quantity_unit:装液被拒 - }) - assert failed.json()["code"] == 1000, failed.text - assert total() == before - assert ok_data(client.get(f"/api/v1/sites/{site_uuid}"))["occupied_material_uuid"] is None - - placed = ok_data(client.post("/api/v1/materials", json={ - "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-好", - "site_placement": {"action": "place", "site_uuid": site_uuid}, - }), status=201) - assert placed["current_site"]["uuid"] == site_uuid and placed["parent_uuid"] == rack["uuid"] - assert ok_data(client.get(f"/api/v1/sites/{site_uuid}"))["occupied_material_uuid"] == placed["uuid"] + from unilabos.server.services.materials.contents import ContentContract + + service = MaterialsService(tmp_path / "materials.db") + app = FastAPI() + install_materials_api(app, service) + reached: list[str] = [] + create_reagent = ContentContract.create_reagent + + def spy(self, values): + # 走到这里时建树与落位已经在同一个外层事务里写下 + reached.append(str(service.connection.execute("SELECT COUNT(*) FROM material").fetchone()[0])) + return create_reagent(self, values) + + monkeypatch.setattr(ContentContract, "create_reagent", spy) + with TestClient(app) as client: + identities = _templates(client) + rack = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["tube_rack_2"], "name": "架-T"}), status=201) + site_uuid = rack["site_uuids"][0] + + def counts() -> tuple[int, int]: + connection = service.connection + return (connection.execute("SELECT COUNT(*) FROM material").fetchone()[0], + connection.execute("SELECT COUNT(*) FROM inventory_ledger").fetchone()[0]) + + before = counts() + failed = client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-坏", + "site_placement": {"action": "place", "site_uuid": site_uuid}, + # 请求模型合法;没有试剂身份(cas / reagent_info_uuid),装液在服务里被拒 + "reagent": {"quantity": 5, "quantity_unit": "ml"}, + }) + assert failed.json()["code"] == 1000, failed.text + assert reached == [str(before[0] + 1)] # 失败前新物料确实已写进事务 + assert counts() == before + assert ok_data(client.get(f"/api/v1/sites/{site_uuid}"))["occupied_material_uuid"] is None + + placed = ok_data(client.post("/api/v1/materials", json={ + "resource_template_uuid": identities["bottle_500ml"], "name": "瓶-好", + "site_placement": {"action": "place", "site_uuid": site_uuid}, + }), status=201) + assert placed["current_site"]["uuid"] == site_uuid and placed["parent_uuid"] == rack["uuid"] + assert ok_data(client.get(f"/api/v1/sites/{site_uuid}"))["occupied_material_uuid"] == placed["uuid"] + service.close() def test_v1_create_initializes_a_plr_material_that_a_device_site_accepts(tmp_path) -> None: From 98965eae6aa3f61b83fba7335ba58562e6f27d42 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:21:50 +0800 Subject: [PATCH 37/59] fix(events): one shared materials ledger poller serves every SSE connection Every /api/v1/events connection read the materials ledger once a second in the default thread pool, the same pool the runtime.v1 control socket's outbound pump and the edge proxy use; /api/v1/materials/events read it on the event loop itself, also once per connection. With many tabs and a long write, messages to the Host were delayed. LedgerWatch (server/services/materials/ledger_watch.py) is one per materials authority: a dedicated daemon thread reads the ledger tail once a second while anyone subscribes, reads the new rows (500 per batch, the rest on the next round), works out the changed materials once, and hands the batch to every subscriber. A subscriber gives its own starting point: the watch catches it up from there, or sends a reset batch when the cursor is ahead (database reset). Connection baselines and the ledger epoch are read on the same thread, not in the default pool. Read errors are logged and retried on the next round without dropping subscribers; a subscriber whose delivery fails is dropped; with no subscribers and no pending reads the thread exits and forgets its position. /api/v1/events turns batches into material.changed frames as before. /api/v1/materials/events (including the epoch / reset handling of e125c66cb) now streams the watch's rows instead of polling per connection, and sends stream.reset (cursor_ahead) when the ledger shrinks under a live connection instead of going silent. --- .../test_runtime_events_material_notices.py | 87 ++++++- unilabos/server/api/materials/core.py | 78 ++++-- unilabos/server/api/runtime/events.py | 142 ++++------- .../server/services/materials/ledger_watch.py | 239 ++++++++++++++++++ 4 files changed, 432 insertions(+), 114 deletions(-) create mode 100644 unilabos/server/services/materials/ledger_watch.py diff --git a/tests/server/test_runtime_events_material_notices.py b/tests/server/test_runtime_events_material_notices.py index be22c0bfd..690dff7c4 100644 --- a/tests/server/test_runtime_events_material_notices.py +++ b/tests/server/test_runtime_events_material_notices.py @@ -2,6 +2,7 @@ 前端每个工站只维持这一条事件流(HTTP/1.1 连接数有限),物料失效与工作流、日志通知走同一条。 通知列出这段账本里变了的物料,前端只重读这些;列不准时省略,前端整体重读。 +账本由一个物料权威一条的共享轮询线程读,所有连接共用,不占默认线程池。 """ from __future__ import annotations @@ -12,6 +13,7 @@ from unittest.mock import Mock from unilabos.server.api.runtime import events +from unilabos.server.services.materials.ledger_watch import LedgerWatch class _Request: @@ -29,7 +31,11 @@ class _Ledger: def __init__(self, tail: int, rows=(), sites=None): self.tail = tail - self.rows = [SimpleNamespace(sequence=s, aggregate_type=t, aggregate_uuid=u) for s, t, u in rows] + self.rows = [ + SimpleNamespace(sequence=row[0], aggregate_type=row[1], aggregate_uuid=row[2], + delta=row[3] if len(row) > 3 else {}) + for row in rows + ] self.sites = dict(sites or {}) def latest_ledger_sequence(self) -> int: @@ -58,7 +64,7 @@ def _first_frame(materials, cursor: int, workflow=None) -> str: async def scenario(): stream = events.runtime_event_stream( _Request(), workflow or _workflow(), cursor=41, - materials=events.MaterialNotices(materials), material_cursor=cursor, + materials=LedgerWatch(materials), material_cursor=cursor, ) assert "connected" in await anext(stream) frame = await asyncio.wait_for(anext(stream), 2) @@ -101,7 +107,7 @@ def latest_ledger_sequence(self) -> int: async def scenario(): stream = events.runtime_event_stream( _Request(), _workflow(), cursor=41, - materials=events.MaterialNotices(_SlowLedger(3, rows=[(3, "material", "m")])), material_cursor=2, + materials=LedgerWatch(_SlowLedger(3, rows=[(3, "material", "m")])), material_cursor=2, ) assert "connected" in await anext(stream) ticks: list[float] = [] @@ -192,7 +198,7 @@ def mutation(operation: str) -> InventoryMutation: gateway=LocalMaterialsClient(service), ) [site] = service.get_material(device_uuid).sites - notices = events.MaterialNotices(service) + notices = LedgerWatch(service) before = notices.latest() created = service.create_tree( @@ -207,7 +213,7 @@ def mutation(operation: str) -> InventoryMutation: sample_uuid = created.data.root_material_uuid after = notices.latest() assert after > before - assert set(notices.changed_materials(before, after)) == {sample_uuid, device_uuid} + assert set(notices.read(before, after).changed) == {sample_uuid, device_uuid} finally: service.close() @@ -221,3 +227,74 @@ def test_notices_exist_only_where_the_materials_authority_lives(monkeypatch): monkeypatch.setattr(execution_composition, "get_materials_service", lambda: _Ledger(12)) notices = events.material_notices() assert notices is not None and notices.latest() == 12 + + +def test_material_notices_never_use_the_shared_thread_pool(monkeypatch): + """runtime.v1 控制 socket 的出站泵与 edge 代理用默认线程池;SSE 的物料轮询不能和它们抢。""" + + _quiet(monkeypatch) + + def forbidden(*_args, **_kwargs): + raise AssertionError("SSE 物料轮询用了默认线程池") + + monkeypatch.setattr(events.asyncio, "to_thread", forbidden) + ledger = _Ledger(7, rows=[(6, "material", "plate"), (7, "material", "plate")]) + assert _data(_first_frame(ledger, cursor=5)) == {"sequence": 7, "material_uuids": ["plate"]} + + +def test_many_connections_share_one_ledger_read_per_tick(): + """N 个订阅者共用一次读:账本末尾的读取次数与连接数无关。""" + + import threading + import time + + class _Counting(_Ledger): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.reads = 0 + self.lock = threading.Lock() + + def latest_ledger_sequence(self) -> int: + with self.lock: + self.reads += 1 + return self.tail + + ledger = _Counting(3) + watch = LedgerWatch(ledger, interval=0.1) + received: list[list] = [[] for _ in range(20)] + releases = [watch.subscribe(3, received[index].append) for index in range(20)] + time.sleep(0.3) + ledger.rows.append(SimpleNamespace(sequence=4, aggregate_type="material", aggregate_uuid="m", delta={})) + ledger.tail = 4 + deadline = time.monotonic() + 3 + while time.monotonic() < deadline and not all(batches for batches in received): + time.sleep(0.02) + reads_with_twenty = ledger.reads + + assert all([batch.changed for batch in batches] == [["m"]] for batches in received) + # 1 次建立基线 + 每 0.1 秒一轮;20 个连接各读一次的话会远多于这个数 + assert reads_with_twenty < 20 + for release in releases: + release() + deadline = time.monotonic() + 2 + while time.monotonic() < deadline and watch._thread is not None: + time.sleep(0.02) + assert watch._thread is None # 没有订阅者,轮询线程退出 + + +def test_a_late_subscriber_catches_up_from_its_own_cursor(): + import time + + ledger = _Ledger(5, rows=[(4, "material", "a"), (5, "material", "b")]) + watch = LedgerWatch(ledger, interval=0.05) + first: list = [] + release = watch.subscribe(5, first.append) + late: list = [] + release_late = watch.subscribe(3, late.append) + deadline = time.monotonic() + 2 + while time.monotonic() < deadline and not late: + time.sleep(0.02) + release() + release_late() + assert first == [] + assert [(batch.after, batch.upto, batch.changed) for batch in late] == [(3, 5, ["a", "b"])] diff --git a/unilabos/server/api/materials/core.py b/unilabos/server/api/materials/core.py index 6ee47e562..826754028 100644 --- a/unilabos/server/api/materials/core.py +++ b/unilabos/server/api/materials/core.py @@ -15,6 +15,7 @@ from __future__ import annotations +import asyncio import json import re from typing import Literal, Optional @@ -29,6 +30,7 @@ from unilabos.server.lifecycle import shutting_down, sleep_unless_shutting_down from unilabos.protocol.materials import InventoryRequirement, MaterialSnapshot from unilabos.server.services.materials import MaterialsService +from unilabos.server.services.materials.ledger_watch import LedgerBatch, ledger_watch class InventoryPreviewRequest(ServerObject): @@ -242,9 +244,11 @@ async def events( raise HTTPException(status_code=422, detail="invalid Last-Event-ID") # 必须在发出响应头/onopen 之前固定基线与新水位。否则浏览器已校准 HTTP 快照后, - # 首连再追平账本会吞掉这期间的创建/移动;用 MAX 查询也避免全量扫描历史。 - latest = service.latest_ledger_sequence() - epoch = service.ledger_epoch() + # 首连再追平账本会吞掉这期间的创建/移动。基线与纪元在共享账本轮询的线程上读, + # 不占默认线程池;之后的变化也由那条线程统一读出、分给所有连接,不按连接重复读。 + watch = ledger_watch(service) + latest = await asyncio.wrap_future(watch.baseline()) + epoch = await asyncio.wrap_future(watch.call(service.ledger_epoch)) fresh = cursor is None if cursor is None: cursor = latest @@ -268,28 +272,56 @@ def _format_event(row) -> str: ) return f"id: {format_materials_cursor(row.sequence, epoch)}\nevent: {MATERIALS_CHANGED_EVENT}\ndata: {data}\n\n" + def _format_reset(reason: str) -> str: + data = json.dumps({"reason": reason}, separators=(",", ":")) + return f"id: {format_materials_cursor(cursor, epoch)}\nevent: {STREAM_RESET_EVENT}\ndata: {data}\n\n" + async def stream(): nonlocal cursor, epoch - yield "retry: 3000\n: connected\n\n" - if reset_reason is not None: - data = json.dumps({"reason": reset_reason}, separators=(",", ":")) - yield f"id: {format_materials_cursor(cursor, epoch)}\nevent: {STREAM_RESET_EVENT}\ndata: {data}\n\n" - elif fresh: - # 只设置浏览器续传水位,不触发业务失效;空闲连接断线后也能从这里续传或被重置。 - yield f"id: {format_materials_cursor(cursor, epoch)}\n\n" - # 停机开始就主动结束:浏览器按 retry 自动重连,uvicorn 不必超时取消 - while not shutting_down() and not await request.is_disconnected(): - rows = service.changes(after_sequence=cursor, limit=500) - if rows and epoch is None: - # 连接时账本为空:第一条记录写入后纪元才确定 - epoch = service.ledger_epoch() - for row in rows: - cursor = row.sequence - yield _format_event(row) - if not rows: - yield ": keepalive\n\n" - if not await sleep_unless_shutting_down(1): - return + loop = asyncio.get_running_loop() + batches: list[LedgerBatch] = [] + closed = False + + def receive(batch: LedgerBatch) -> None: + # 共享轮询线程上调用:只把这一批交回事件循环 + if not closed: + loop.call_soon_threadsafe(batches.append, batch) + + release = watch.subscribe(cursor, receive) + try: + yield "retry: 3000\n: connected\n\n" + if reset_reason is not None: + yield _format_reset(reset_reason) + elif fresh: + # 只设置浏览器续传水位,不触发业务失效;空闲连接断线后也能从这里续传或被重置。 + yield f"id: {format_materials_cursor(cursor, epoch)}\n\n" + # 停机开始就主动结束:浏览器按 retry 自动重连,uvicorn 不必超时取消 + while not shutting_down() and not await request.is_disconnected(): + pending, batches[:] = list(batches), [] + sent = False + for batch in pending: + if batch.reset: + # 库被重置(账本末尾变小):给出新水位,客户端整体重读 + cursor = batch.upto + epoch = await asyncio.wrap_future(watch.call(service.ledger_epoch)) + yield _format_reset("cursor_ahead") + sent = True + continue + rows = [row for row in batch.rows if row.sequence > cursor] + if rows and epoch is None: + # 连接时账本为空:第一条记录写入后纪元才确定 + epoch = await asyncio.wrap_future(watch.call(service.ledger_epoch)) + for row in rows: + cursor = row.sequence + yield _format_event(row) + sent = True + if not sent: + yield ": keepalive\n\n" + if not await sleep_unless_shutting_down(1): + return + finally: + closed = True + release() return StreamingResponse( stream(), diff --git a/unilabos/server/api/runtime/events.py b/unilabos/server/api/runtime/events.py index bacd774e3..5e1634c46 100644 --- a/unilabos/server/api/runtime/events.py +++ b/unilabos/server/api/runtime/events.py @@ -22,9 +22,16 @@ 物料失效:本进程持有物料权威时,物料账本前进就推一条**不带 id** 的 ``material.changed`` (``data: {"sequence": <账本末尾序号>, "material_uuids": [...]}``),与日志通知一样不动工作流游标。 -``material_uuids`` 是这段账本里变了的物料(Site 的变化归到所属物料);列不准时(条目过多、模板变化、 -库被重置)省略它,表示整体重读。只维持这一条事件流的前端据此重读物料;要按账本 sequence 续传的 -客户端仍用 ``/api/v1/materials/events``(``materials.changed``)。 +``material_uuids`` 的语义: + +- 带这个键:恰好是这段账本里变了的物料(Site 的变化归到所属物料,拓扑边的变化归到两端物料), + 客户端只重读这些;**空列表就是没有物料变化**(这段账本只动了批次 / 预留),什么都不用重读, + ``sequence`` 照常前进; +- 不带这个键:列不准(模板变化、库被重置),整体重读。 + +账本由进程内唯一的共享轮询读(``server/services/materials/ledger_watch.py``),所有连接共用一份结果, +不占默认线程池。只维持这一条事件流的前端据此重读物料;要按账本 sequence 续传的客户端仍用 +``/api/v1/materials/events``(``materials.changed``)。 """ from __future__ import annotations @@ -39,6 +46,7 @@ from fastapi.responses import Response, StreamingResponse from unilabos.protocol.runtime.logs import RuntimeLogNotice +from unilabos.server.services.materials.ledger_watch import LedgerBatch, LedgerWatch, ledger_watch from unilabos.server.api.envelope import WORKFLOW, envelope_router from unilabos.server.lifecycle import shutting_down from unilabos.utils.log_notices import LOG_NOTICE_EVENT, log_notices, merge_notices @@ -74,49 +82,8 @@ def to_v1_event(event: Dict[str, Any]) -> Dict[str, Any]: return {**event, "event": name, "data": data} -#: 一次通知最多列出的账本条目;超过就不列物料,让客户端整体重读 -MATERIAL_NOTICE_WINDOW = 500 - - -class MaterialNotices: - """本进程物料权威的账本视图:末尾序号,以及一段区间里哪些物料变了。""" - - def __init__(self, service: Any): - self._service = service - - def latest(self) -> int: - return int(self._service.latest_ledger_sequence()) - - def changed_materials(self, after: int, upto: int) -> list[str] | None: - """``(after, upto]`` 里变了的物料 uuid(Site 的变化归到它的所属物料)。 - - 返回 None 表示列不准(条目超过窗口、模板变了),客户端应整体重读。 - """ - - rows = self._service.changes(after_sequence=after, limit=MATERIAL_NOTICE_WINDOW + 1) - rows = [row for row in rows if row.sequence <= upto] - if len(rows) > MATERIAL_NOTICE_WINDOW: - return None - changed: set[str] = set() - sites: set[str] = set() - for row in rows: - if row.aggregate_type == "material": - changed.add(row.aggregate_uuid) - elif row.aggregate_type == "site": - sites.add(row.aggregate_uuid) - elif row.aggregate_type == "resource_template": - # 模板变化可能改变很多物料的展示,不逐个列 - return None - # 同一个 Site 在一段账本里常出现多次(占用、释放),每个只查一次所属物料 - for site_uuid in sorted(sites): - site = self._service.get_site(site_uuid, include_deleted=True) - if site is not None: - changed.add(site.owner_material_uuid) - return sorted(changed) - - -def material_notices() -> MaterialNotices | None: - """本进程持有物料权威时返回账本视图;Host 子进程等没有权威的进程返回 None。""" +def material_notices() -> LedgerWatch | None: + """本进程持有物料权威时返回它的共享账本轮询;Host 子进程等没有权威的进程返回 None。""" try: from unilabos.server.execution_composition import get_materials_service @@ -125,40 +92,13 @@ def material_notices() -> MaterialNotices | None: service = get_materials_service() if service is None or not callable(getattr(service, "latest_ledger_sequence", None)): return None - return MaterialNotices(service) - - -def _latest_material_sequence(materials: MaterialNotices, fallback: int) -> int: - try: - return materials.latest() - except Exception: # noqa: BLE001 - 读不到账本只是这一轮不发失效,不能断开工作流事件流 - return fallback - - -def _changed_materials(materials: MaterialNotices, after: int, upto: int) -> list[str] | None: - try: - return materials.changed_materials(after, upto) - except Exception: # noqa: BLE001 - 列不出来就让客户端整体重读 - return None - - -def _poll_materials(materials: MaterialNotices, cursor: int) -> tuple[int, list[str] | None]: - """账本末尾,以及 ``(cursor, 末尾]`` 里变了的物料;末尾变小(库被重置)时不列。 - - 在工作线程里跑(``asyncio.to_thread``):读账本要拿物料库的锁,写事务持锁期间读会等, - 放在事件循环上会卡住这个进程的全部连接。 - """ - - latest = _latest_material_sequence(materials, cursor) - if latest <= cursor: - return latest, None - return latest, _changed_materials(materials, cursor, latest) + return ledger_watch(service) def material_changed_frame(sequence: int, material_uuids: list[str] | None = None) -> str: """不写 SSE id:Last-Event-ID 只表示工作流持久事件的序号。 - ``material_uuids`` 缺省表示"列不准,整体重读";给出时客户端只重读这些物料。 + ``material_uuids`` 为 None 时省略这个键,表示"列不准,整体重读";空列表表示没有物料变化。 """ payload: Dict[str, Any] = {"sequence": sequence} @@ -168,6 +108,19 @@ def material_changed_frame(sequence: int, material_uuids: list[str] | None = Non return f"event: {MATERIAL_CHANGED_EVENT}\ndata: {data}\n\n" +def _merge_material_batches(current: LedgerBatch | None, batch: LedgerBatch) -> LedgerBatch: + """连接来不及发时把多批合成一批:区间取并、物料取并;任一批列不准或重置就整体重读。""" + + if current is None: + return batch + changed = ( + None + if current.reset or batch.reset or current.changed is None or batch.changed is None + else sorted(set(current.changed) | set(batch.changed)) + ) + return LedgerBatch(after=current.after, upto=batch.upto, changed=changed, reset=current.reset or batch.reset) + + async def runtime_event_stream( request: Request, service=None, @@ -175,7 +128,7 @@ async def runtime_event_stream( *, watermark: bool = False, replay: bool = False, - materials: MaterialNotices | None = None, + materials: LedgerWatch | None = None, material_cursor: int = 0, ): from unilabos.server.api.runtime.workflow import format_sse_event @@ -183,6 +136,17 @@ async def runtime_event_stream( loop = asyncio.get_running_loop() pending: asyncio.Queue[RuntimeLogNotice] = asyncio.Queue(maxsize=1) closed = False + material_batch: LedgerBatch | None = None + + def put_material(batch: LedgerBatch) -> None: + nonlocal material_batch + if not closed: + material_batch = _merge_material_batches(material_batch, batch) + + def receive_material(batch: LedgerBatch) -> None: + # 共享轮询线程上调用:只把这一批交回事件循环 + if not closed: + loop.call_soon_threadsafe(put_material, batch) def put(notice: RuntimeLogNotice): if closed: @@ -196,6 +160,8 @@ def receive(notice: RuntimeLogNotice): loop.call_soon_threadsafe(put, notice) release = log_notices.subscribe(receive) + # 从基线之后订阅共享账本轮询:基线到共享进度之间由轮询线程补读,此后每批都分到这里 + release_materials = materials.subscribe(material_cursor, receive_material) if materials is not None else None next_workflow = 0.0 heartbeat = time.monotonic() + 15 try: @@ -205,14 +171,12 @@ def receive(notice: RuntimeLogNotice): yield f"id: {cursor}\n\n" while not shutting_down() and not await request.is_disconnected(): now = time.monotonic() + if material_batch is not None: + # 账本前进了就发一次失效,列出这段区间里变了的物料;库被重置或模板变了不列,整体重读 + batch, material_batch = material_batch, None + yield material_changed_frame(batch.upto, None if batch.reset else batch.changed) if now >= next_workflow: next_workflow = now + 1 - if materials is not None: - # 账本末尾变了就发一次失效,列出这段区间里变了的物料;库被重置(末尾变小)时不列,整体重读。 - latest_material, changed = await asyncio.to_thread(_poll_materials, materials, material_cursor) - if latest_material != material_cursor: - material_cursor = latest_material - yield material_changed_frame(latest_material, changed) if service is not None: oldest, latest, events = service.read_event_window(after_id=cursor, limit=101) reason = None @@ -245,6 +209,8 @@ def receive(notice: RuntimeLogNotice): finally: closed = True release() + if release_materials is not None: + release_materials() def create_runtime_events_router(service=None) -> APIRouter: @@ -274,11 +240,15 @@ async def events( # 必须在发送响应头之前固定水位,客户端 onopen 后的 REST 补读才能覆盖 # “快照 → 订阅”之间的变化。纯执行面的 Host 没有 Workflow Authority。 cursor = service.latest_event_sequence() if service is not None else 0 - # 物料账本基线同样在响应头之前固定:onopen 后的 REST 补读覆盖此前的物料变化。 + # 物料账本基线同样在响应头之前固定:onopen 后的 REST 补读覆盖此前的物料变化。基线在共享轮询的 + # 线程上读,不占默认线程池;读不到时这条连接不订阅物料失效,工作流事件照常 materials = material_notices() - material_cursor = ( - await asyncio.to_thread(_latest_material_sequence, materials, 0) if materials is not None else 0 - ) + material_cursor = 0 + if materials is not None: + try: + material_cursor = await asyncio.wrap_future(materials.baseline()) + except Exception: # noqa: BLE001 - 物料库读不到不影响工作流事件流 + materials = None return StreamingResponse( runtime_event_stream( request, diff --git a/unilabos/server/services/materials/ledger_watch.py b/unilabos/server/services/materials/ledger_watch.py new file mode 100644 index 000000000..c0c8b7156 --- /dev/null +++ b/unilabos/server/services/materials/ledger_watch.py @@ -0,0 +1,239 @@ +"""物料账本的共享轮询:一个物料权威一条专用线程,所有 SSE 连接共用它的结果。 + +``/api/v1/events``(``material.changed``)与 ``/api/v1/materials/events``(``materials.changed``)都要知道 +账本前进了什么。以前每个连接每秒各读一次账本(还占着默认线程池,与 runtime.v1 控制 socket 的出站泵、 +edge 代理抢同一个池),标签页一多、碰上长写入,发往 Host 的消息就被拖慢。现在: + +- 只有一条专用线程读账本:有订阅者时每秒读一次末尾,有新条目就读出这一段(每批最多 + :data:`PAGE` 条,多了下一轮接着读),算好变了哪些物料,分发给全部订阅者; +- 订阅时给出自己的起点:起点落后于共享进度的,这条线程先给它补读那一段;起点超前(库被重置)的 + 直接收到一个重置批次; +- 连接建立前要固定的基线(账本末尾、纪元)也在这条线程上读(:meth:`LedgerWatch.call`),不进默认线程池; +- 读账本出错只写日志,下一轮再读,不会断开订阅;分发出错的订阅者被移除; +- 没有订阅者、也没有待办的读请求时线程退出,下一个请求再启动。 +""" + +from __future__ import annotations + +import logging +import queue +import threading +import time +import weakref +from concurrent.futures import Future +from dataclasses import dataclass, field +from typing import Any, Callable, Optional + +logger = logging.getLogger(__name__) + +#: 一批最多带出的账本条目;也是 ``material.changed`` 列物料的窗口 +PAGE = 500 + + +@dataclass(frozen=True) +class LedgerBatch: + """``(after, upto]`` 这段账本:条目、变了的物料(None 表示列不准、整体重读),或库被重置。""" + + after: int + upto: int + rows: list[Any] = field(default_factory=list) + changed: Optional[list[str]] = None + reset: bool = False + + +Deliver = Callable[[LedgerBatch], None] + + +class LedgerWatch: + """一个物料权威的账本共享轮询(见模块说明)。``deliver`` 在轮询线程上调用,必须很快返回。""" + + def __init__(self, service: Any, *, interval: float = 1.0) -> None: + self._service = service + self._interval = interval + self._lock = threading.Lock() + self._requests: "queue.Queue[tuple[Callable[[], Any], Future]]" = queue.Queue() + self._subscribers: dict[int, Deliver] = {} + self._next_token = 0 + self._latest: Optional[int] = None + self._thread: Optional[threading.Thread] = None + + # ── 读账本(在轮询线程上) ─────────────────────────────────────── + + def latest(self) -> int: + return int(self._service.latest_ledger_sequence()) + + def changed_materials(self, rows: list[Any]) -> Optional[list[str]]: + """这些账本条目里变了的物料 uuid(Site 归到所属物料,拓扑边归到两端);模板变了返回 None。""" + + changed: set[str] = set() + sites: set[str] = set() + for row in rows: + if row.aggregate_type == "material": + changed.add(row.aggregate_uuid) + elif row.aggregate_type == "site": + sites.add(row.aggregate_uuid) + elif row.aggregate_type == "link": + delta = getattr(row, "delta", None) or {} + changed.update( + str(delta[key]) for key in ("source_material_uuid", "target_material_uuid") if delta.get(key) + ) + elif row.aggregate_type == "resource_template": + # 模板变化可能改变很多物料的展示,不逐个列 + return None + # 同一个 Site 在一段账本里常出现多次(占用、释放),每个只查一次所属物料 + for site_uuid in sorted(sites): + site = self._service.get_site(site_uuid, include_deleted=True) + if site is not None: + changed.add(site.owner_material_uuid) + return sorted(changed) + + def read(self, after: int, upto: Optional[int] = None) -> LedgerBatch: + rows = list(self._service.changes(after_sequence=after, limit=PAGE)) + if upto is not None: + rows = [row for row in rows if row.sequence <= upto] + end = rows[-1].sequence if rows else (upto if upto is not None else after) + return LedgerBatch(after=after, upto=end, rows=rows, changed=self.changed_materials(rows)) + + def _catch_up(self, after: int, deliver: Deliver) -> None: + """新订阅者的起点到共享进度之间:补读给它;起点超前(库被重置)时给它一个重置批次。""" + + assert self._latest is not None + if after > self._latest: + deliver(LedgerBatch(after=after, upto=self._latest, reset=True)) + return + while after < self._latest: + batch = self.read(after, self._latest) + if not batch.rows: + break + deliver(batch) + after = batch.upto + + def _tick(self) -> bool: + """读一轮;返回 True 表示这一批没读完,应当马上再读。""" + + latest = self.latest() + previous = self._latest + if previous is None: + self._latest = latest + return False + if latest < previous: + self._latest = latest + self._fan_out(LedgerBatch(after=previous, upto=latest, reset=True)) + return False + if latest == previous: + return False + batch = self.read(previous) + if not batch.rows: + self._latest = latest + return False + self._latest = batch.upto + self._fan_out(batch) + return len(batch.rows) >= PAGE + + def _fan_out(self, batch: LedgerBatch) -> None: + with self._lock: + subscribers = list(self._subscribers.items()) + for token, deliver in subscribers: + try: + deliver(batch) + except Exception: # noqa: BLE001 - 一个订阅者坏了不影响其他订阅者 + logger.exception("物料账本通知分发失败,移除该订阅者") + self._drop(token) + + # ── 线程 ───────────────────────────────────────────────────────── + + def _ensure_thread(self) -> None: + with self._lock: + if self._thread is None: + self._thread = threading.Thread(target=self._run, name="materials-ledger-watch", daemon=True) + self._thread.start() + + def _run(self) -> None: + next_tick = time.monotonic() + failures = 0 + while True: + try: + function, future = self._requests.get(timeout=max(0.0, next_tick - time.monotonic())) + except queue.Empty: + pass + else: + if future.set_running_or_notify_cancel(): + try: + future.set_result(function()) + except BaseException as exc: # noqa: BLE001 - 交给等待方 + future.set_exception(exc) + continue + with self._lock: + if not self._subscribers and self._requests.empty(): + # 没人订阅时进度不再前进:忘掉它,下一个请求重新读账本末尾 + self._thread = None + self._latest = None + return + again = False + try: + again = self._tick() + failures = 0 + except Exception as exc: # noqa: BLE001 - 读不到这一轮就不发,下一轮再读 + failures += 1 + if failures == 1 or failures % 60 == 0: + logger.warning("读物料账本失败(第 %s 次),下一轮再读:%s", failures, exc) + next_tick = time.monotonic() + (0 if again else self._interval) + + def call(self, function: Callable[..., Any], *args: Any, **kwargs: Any) -> Future: + """在轮询线程上执行一次读(连接前的基线、纪元),返回 ``concurrent.futures.Future``。""" + + future: Future = Future() + self._requests.put((lambda: function(*args, **kwargs), future)) + self._ensure_thread() + return future + + def baseline(self) -> Future: + """共享进度(没在轮询时读一次账本末尾):新连接据此固定基线。 + + 有订阅者时共享进度最多落后账本一轮;从它开始订阅不会漏掉变化,最多多收到一次失效。 + """ + + def read() -> int: + if self._latest is None: + self._latest = self.latest() + return self._latest + + return self.call(read) + + def subscribe(self, after: int, deliver: Deliver) -> Callable[[], None]: + """从 ``after`` 之后开始收到每一批账本变化;返回取消订阅的函数。""" + + with self._lock: + self._next_token += 1 + token = self._next_token + + def register() -> None: + if self._latest is None: + self._latest = self.latest() + self._catch_up(after, deliver) + with self._lock: + self._subscribers[token] = deliver + + self.call(register) + return lambda: self._drop(token) + + def _drop(self, token: int) -> None: + with self._lock: + self._subscribers.pop(token, None) + + +_watches: "weakref.WeakKeyDictionary[Any, LedgerWatch]" = weakref.WeakKeyDictionary() +_watches_lock = threading.Lock() + + +def ledger_watch(service: Any) -> LedgerWatch: + """这个物料权威的共享轮询(进程内唯一)。""" + + with _watches_lock: + watch = _watches.get(service) + if watch is None: + watch = _watches[service] = LedgerWatch(service) + return watch + + +__all__ = ["LedgerBatch", "LedgerWatch", "PAGE", "ledger_watch"] From 097b2faaa458e9a68703071837a3c5086abed1ff Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:26 +0800 Subject: [PATCH 38/59] fix(materials): link changes go through the ledger, and material_uuids has defined semantics Topology link writes (upsert_link, delete_link_record, ensure_links) wrote no ledger rows, so with the 30 s polling gone a link change never notified anyone. They now append a ledger row (aggregate_type "link", operation create / update / delete, delta naming both endpoint materials) in the same write transaction. A link deleted and created again keeps counting versions from the ledger, so the (type, uuid, version) uniqueness holds. The ledger CHECK and the protocol's AggregateType gain "link"; the materials baseline fingerprint is updated (still the pre-release v1 baseline). material.changed on /api/v1/events now has a defined meaning: with the key, material_uuids is exactly the materials that changed (Sites map to their owner, links to both endpoints) and an empty list means no material changed (only lots or reservations moved the ledger), so nothing needs rereading; without the key the window could not be listed (template change, ledger reset) and clients reread everything. /api/v1/materials/events sends link rows as materials.changed like any other row. The realtime and V1 migration guides document this. --- docs/developer_guide/api_v1_migration.md | 4 +- docs/developer_guide/interfaces/realtime.md | 17 +++-- tests/server/test_database_schema_versions.py | 2 +- tests/server/test_material_links.py | 24 +++++++ .../test_runtime_events_material_notices.py | 22 +++++- unilabos/protocol/materials.py | 2 +- unilabos/server/database/tables/materials.py | 4 +- unilabos/server/services/materials/core.py | 71 +++++++++++++++++-- unilabos/server/services/materials/store.py | 2 +- 9 files changed, 130 insertions(+), 18 deletions(-) diff --git a/docs/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index d6401daf6..e6186eab6 100644 --- a/docs/developer_guide/api_v1_migration.md +++ b/docs/developer_guide/api_v1_migration.md @@ -151,8 +151,8 @@ dev 内部异常到业务码的映射集中在 `envelope.py`,不在各路由 原载荷字段保留。换名在 API 层(`api/runtime/events.py:to_v1_event`)做,`frontend_event` 表仍存 dev 名。 `runtime.logs.changed`(无 id 的日志通知)与物料的 `/api/v1/materials/events`(`materials.changed`)不在 V1 合同里,暂保持原名。物料失效另以 V1 名 `material.changed`(无 id,`data.sequence` 为账本末尾, - `data.material_uuids` 列出这段账本里变了的物料,Site 的变化归到所属物料;超过 500 条、涉及模板或账本重置时 - 省略,表示整体重读)随 `/api/v1/events` 推送,前端每个工站只维持这一条事件流。CLI `workflow watch` 同步修改。 + `data.material_uuids` 列出这段账本里变了的物料,Site 的变化归到所属物料、拓扑边归到两端;空列表表示没有物料变化, + 涉及模板或账本重置时省略这个键,表示整体重读)随 `/api/v1/events` 推送,前端每个工站只维持这一条事件流。CLI `workflow watch` 同步修改。 ## 库存与工作区(p7-c 落地) diff --git a/docs/developer_guide/interfaces/realtime.md b/docs/developer_guide/interfaces/realtime.md index 9f96db8ab..65255e5fb 100644 --- a/docs/developer_guide/interfaces/realtime.md +++ b/docs/developer_guide/interfaces/realtime.md @@ -33,11 +33,18 @@ 三个游标相互独立:工作流 id、物料 sequence、日志 stream:offset。不能混用,也不能以最后日志通知替换工作流游标。 -`/api/v1/events` 上的 `material.changed` 与日志通知一样**不带 id**:本进程持有物料权威时,后端约每秒比较一次 -账本末尾序号,变了就推 `event: material.changed` + -`data: {"sequence": <账本末尾>, "material_uuids": [<这段账本里变了的物料>]}`(Site 的占用变化归到所属物料)。 -客户端只重读列出的物料;列不准时(一次超过 500 条、资源模板变化、库被重置)省略 `material_uuids`, -表示整体重读。它不回放、不占工作流游标;断线期间的物料变化由重连后的 REST 补读覆盖。浏览器因此每个工站只需维持 +`/api/v1/events` 上的 `material.changed` 与日志通知一样**不带 id**:本进程持有物料权威时,账本前进就推 +`event: material.changed` + `data: {"sequence": <账本末尾>, "material_uuids": [<这段账本里变了的物料>]}`。 +`material_uuids` 的语义: + +- **带这个键**:恰好是这段账本里变了的物料(Site 的占用变化归到所属物料,拓扑边的增删改归到两端物料), + 客户端只重读这些;**空列表 `[]` 表示没有物料变化**(这段账本只动了批次 / 预留),什么都不用重读; +- **不带这个键**:列不准(资源模板变化、库被重置),整体重读。 + +账本由进程内唯一的共享轮询读(`server/services/materials/ledger_watch.py`:一个物料权威一条专用线程,约每秒一次, +每批最多 500 条,多了下一轮接着读),所有连接(含下面的 `/api/v1/materials/events`)共用同一份结果,不按连接重复读, +也不占默认线程池(runtime.v1 控制 socket 的出站泵、edge 代理用它)。通知不回放、不占工作流游标;断线期间的物料变化 +由重连后的 REST 补读覆盖。浏览器因此每个工站只需维持 `/api/v1/events` 一条长连接(HTTP/1.1 下每个源最多约 6 条连接,多开标签页时第二条流会挤占 REST)。 后端内部检查账本不等于要求浏览器每秒 GET 全量数据;前端维持事件流,仅在失效时拉取。 diff --git a/tests/server/test_database_schema_versions.py b/tests/server/test_database_schema_versions.py index 60406f800..397cc6b7c 100644 --- a/tests/server/test_database_schema_versions.py +++ b/tests/server/test_database_schema_versions.py @@ -19,7 +19,7 @@ #: 把对应库的 schema_version +1,在其 migrations 里补上迁移,再更新这里。 PINNED = { "runtime": (1, "bea876e21df263c620db697c4eb74a959bb9b8b4f73866f089a223dfe4b5eb63"), - "materials": (1, "c35dd5def14fe03dcfa7d9355acd0b8d4fb8901b0ba8640fc2c35bae36eaba77"), + "materials": (1, "a32591765329a4b4526bd142b7c8622d991bdacdb10cca2645b78f2c49d1d193"), "telemetry": (1, "a0e00118c131bbae1e4a693563977d7ffff49c17c482ebad0e5ad2b224b548af"), "history": (1, "5005469f86db3fe747ab1f30ea32d0c0c8f2f2779202a81bedb8d8254217f4cc"), } diff --git a/tests/server/test_material_links.py b/tests/server/test_material_links.py index c75c3cfe9..63fa4d881 100644 --- a/tests/server/test_material_links.py +++ b/tests/server/test_material_links.py @@ -213,6 +213,30 @@ def test_upsert_and_delete_roundtrip(self, service) -> None: assert service.delete_link_record(created["link_uuid"]) is False assert service.list_links() == [] + def test_link_changes_go_through_the_ledger(self, service) -> None: + """边的增删改都记账本:物料通知随账本前进;同一条边删了再建,版本接着往下数。""" + + source = _create_root(service, "pump") + target = _create_root(service, "reactor") + + def link_rows() -> list[tuple[str, int, int]]: + return [ + (row.operation, row.previous_version, row.aggregate_version) + for row in service.changes(limit=10_000) + if row.aggregate_type == "link" + ] + + first = service.upsert_link(source_material_uuid=source, target_material_uuid=target, extra={"baud": 9600}) + service.upsert_link(source_material_uuid=source, target_material_uuid=target, extra={"baud": 9600}) + service.upsert_link(source_material_uuid=source, target_material_uuid=target, extra={"baud": 19200}) + service.delete_link_record(first["link_uuid"]) + again = service.upsert_link(source_material_uuid=source, target_material_uuid=target) + + assert link_rows() == [("create", 0, 1), ("update", 1, 2), ("delete", 2, 3), ("create", 3, 4)] + assert again["link_uuid"] == first["link_uuid"] and again["version"] == 4 + [row] = [row for row in service.changes(limit=10_000) if row.aggregate_type == "link"][:1] + assert row.delta == {"source_material_uuid": source, "target_material_uuid": target, "link_type": ""} + def test_delete_material_clears_touching_links(self, service) -> None: source = _create_root(service, "pump") target = _create_root(service, "reactor") diff --git a/tests/server/test_runtime_events_material_notices.py b/tests/server/test_runtime_events_material_notices.py index 690dff7c4..aaa8e8a5e 100644 --- a/tests/server/test_runtime_events_material_notices.py +++ b/tests/server/test_runtime_events_material_notices.py @@ -1,7 +1,7 @@ """/api/v1/events 的物料失效:账本前进就推一条无 id 的 material.changed,不动工作流游标。 前端每个工站只维持这一条事件流(HTTP/1.1 连接数有限),物料失效与工作流、日志通知走同一条。 -通知列出这段账本里变了的物料,前端只重读这些;列不准时省略,前端整体重读。 +通知列出这段账本里变了的物料,前端只重读这些(空列表:没有物料变化);列不准时省略,前端整体重读。 账本由一个物料权威一条的共享轮询线程读,所有连接共用,不占默认线程池。 """ @@ -214,6 +214,12 @@ def mutation(operation: str) -> InventoryMutation: after = notices.latest() assert after > before assert set(notices.read(before, after).changed) == {sample_uuid, device_uuid} + + # 拓扑边也进账本:通知列出两端物料 + service.upsert_link(source_material_uuid=sample_uuid, target_material_uuid=device_uuid, link_type="fluid") + linked = notices.latest() + assert linked == after + 1 + assert notices.read(after, linked).changed == sorted({sample_uuid, device_uuid}) finally: service.close() @@ -229,6 +235,20 @@ def test_notices_exist_only_where_the_materials_authority_lives(monkeypatch): assert notices is not None and notices.latest() == 12 +def test_a_ledger_window_without_material_changes_lists_none(monkeypatch): + """只动了批次 / 预留:带一个空列表(没有物料要重读),不是省略(整体重读)。""" + + _quiet(monkeypatch) + ledger = _Ledger(9, rows=[(8, "lot", "lot-1"), (9, "reservation", "r-1")]) + assert _data(_first_frame(ledger, cursor=7)) == {"sequence": 9, "material_uuids": []} + + +def test_link_changes_name_both_endpoints(monkeypatch): + _quiet(monkeypatch) + ledger = _Ledger(4, rows=[(4, "link", "l-1", {"source_material_uuid": "pump", "target_material_uuid": "flask"})]) + assert _data(_first_frame(ledger, cursor=3)) == {"sequence": 4, "material_uuids": ["flask", "pump"]} + + def test_material_notices_never_use_the_shared_thread_pool(monkeypatch): """runtime.v1 控制 socket 的出站泵与 edge 代理用默认线程池;SSE 的物料轮询不能和它们抢。""" diff --git a/unilabos/protocol/materials.py b/unilabos/protocol/materials.py index 779eaf872..950f047d7 100644 --- a/unilabos/protocol/materials.py +++ b/unilabos/protocol/materials.py @@ -26,7 +26,7 @@ AggregateType = Literal[ - "resource_template", "material", "site", "lot", "reservation" + "resource_template", "material", "site", "lot", "reservation", "link" ] diff --git a/unilabos/server/database/tables/materials.py b/unilabos/server/database/tables/materials.py index 93f5b8e85..29938b2e5 100644 --- a/unilabos/server/database/tables/materials.py +++ b/unilabos/server/database/tables/materials.py @@ -541,7 +541,7 @@ class InventoryLedgerRecord(TableObject, table=True): sequence: Optional[int] = Field(default=None, ge=1, primary_key=True) event_uuid: NonEmptyStr aggregate_type: Literal[ - "resource_template", "material", "site", "lot", "reservation" + "resource_template", "material", "site", "lot", "reservation", "link" ] = Field(sa_type=Text) aggregate_uuid: NonEmptyStr operation: NonEmptyStr @@ -1373,7 +1373,7 @@ class InventoryProcessedCommandRecord(TableObject, table=True): sequence INTEGER PRIMARY KEY AUTOINCREMENT, event_uuid TEXT NOT NULL UNIQUE CHECK (TRIM(event_uuid) <> ''), aggregate_type TEXT NOT NULL CHECK (aggregate_type IN ( - 'resource_template','material','site','lot','reservation' + 'resource_template','material','site','lot','reservation','link' )), aggregate_uuid TEXT NOT NULL CHECK (TRIM(aggregate_uuid) <> ''), operation TEXT NOT NULL CHECK (TRIM(operation) <> ''), diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index a444e73d3..29c69fda2 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -34,6 +34,8 @@ from unilabos.protocol.base import canonical_hash from unilabos.protocol.materials import AggregatePrecondition, AggregateVersion, InventoryChange, InventoryMutation, MutationResult from unilabos.protocol.materials import ( + ACTOR_GRAPH, + ACTOR_HUMAN, ChemicalSummary, InventoryAllocation, InventoryLotCorrection, @@ -2145,6 +2147,45 @@ def list_links( ) ] + def _ledger_link( + self, + record: MaterialLinkRecord, + *, + operation: str, + previous_version: int, + version: int, + actor_type: str, + timestamp: int, + ) -> int: + """拓扑边的变化也进账本(``aggregate_type="link"``):物料通知随账本前进,不再靠轮询。 + + delta 带两端物料,``material.changed`` 据此列出要重读的物料。 + """ + + return self.append_ledger( + InventoryLedgerRecord( + event_uuid=str(uuid4()), + aggregate_type="link", + aggregate_uuid=record.link_uuid, + operation=operation, + previous_version=previous_version, + aggregate_version=version, + state_hash=canonical_hash( + {"deleted": True} if operation == "delete" + else {key: value for key, value in self._link_read(record).items() + if key not in ("created_at_ms", "updated_at_ms")} + ), + delta_json={ + "source_material_uuid": record.source_material_uuid, + "target_material_uuid": record.target_material_uuid, + "link_type": record.link_type, + }, + actor_type=actor_type, + occurred_at_ms=timestamp, + available_at_ms=timestamp, + ) + ) + def _apply_link( self, *, @@ -2155,8 +2196,9 @@ def _apply_link( target_handle: str, extra: Mapping[str, Any], timestamp: int, + actor_type: str, ) -> tuple[str, MaterialLinkRecord]: - """写事务内 upsert 一条边;uuid5 身份稳定,内容一致则不动版本。""" + """写事务内 upsert 一条边;uuid5 身份稳定,内容一致则不动版本,有变化记一条账本。""" link_uuid = material_link_uuid( source_material_uuid, @@ -2167,6 +2209,13 @@ def _apply_link( ) existing = self.get_link(link_uuid) if existing is None: + # 同一条边删掉后再建:版本接着账本里上一次的往下数(账本按 (类型, uuid, 版本) 唯一) + row = self.connection.execute( + "SELECT MAX(aggregate_version) FROM inventory_ledger " + "WHERE aggregate_type = 'link' AND aggregate_uuid = ?", + (link_uuid,), + ).fetchone() + previous = int(row[0] or 0) record = MaterialLinkRecord( link_uuid=link_uuid, source_material_uuid=source_material_uuid, @@ -2177,9 +2226,11 @@ def _apply_link( extra_json=dict(extra), created_at_ms=timestamp, updated_at_ms=timestamp, - version=1, + version=previous + 1, ) self.insert_link(record) + self._ledger_link(record, operation="create", previous_version=previous, version=record.version, + actor_type=actor_type, timestamp=timestamp) return "created", record if existing.extra_json == dict(extra): return "unchanged", existing @@ -2191,6 +2242,8 @@ def _apply_link( } ) self.update_link(record) + self._ledger_link(record, operation="update", previous_version=existing.version, version=record.version, + actor_type=actor_type, timestamp=timestamp) return "updated", record def upsert_link( @@ -2202,6 +2255,7 @@ def upsert_link( source_handle: str = "", target_handle: str = "", extra: Optional[Mapping[str, Any]] = None, + actor_type: str = ACTOR_HUMAN, ) -> dict[str, Any]: source_material_uuid = (source_material_uuid or "").strip() target_material_uuid = (target_material_uuid or "").strip() @@ -2219,12 +2273,18 @@ def upsert_link( target_handle=target_handle or "", extra=extra or {}, timestamp=self._now_ms(), + actor_type=actor_type, ) return self._link_read(record) - def delete_link_record(self, link_uuid: str) -> bool: + def delete_link_record(self, link_uuid: str, *, actor_type: str = ACTOR_HUMAN) -> bool: with self.write(): - return self.delete_link(link_uuid) + existing = self.get_link(link_uuid) + if existing is None or not self.delete_link(link_uuid): + return False + self._ledger_link(existing, operation="delete", previous_version=existing.version, + version=existing.version + 1, actor_type=actor_type, timestamp=self._now_ms()) + return True def ensure_links( self, links: Sequence[Mapping[str, Any]] @@ -2277,6 +2337,7 @@ def ensure_links( if key not in _RESERVED }, timestamp=timestamp, + actor_type=ACTOR_GRAPH, ) stats[outcome] += 1 return stats @@ -3954,7 +4015,7 @@ def apply(timestamp: int) -> _Applied[MaterialDeleteResult]: for site in self.sites_occupied_by(material_uuids) } changed_sites = {**occupied_sites, **owned_sites} - # 拓扑边随节点退场:边不是 ledger 聚合,事务内物理清理即可。 + # 拓扑边随节点退场:事务内物理清理,物料自己的账本行已经让客户端重读。 self.delete_links_for_materials(material_uuids) affected: list[AggregateVersion] = [] diff --git a/unilabos/server/services/materials/store.py b/unilabos/server/services/materials/store.py index 16f796dd5..cb10fc335 100644 --- a/unilabos/server/services/materials/store.py +++ b/unilabos/server/services/materials/store.py @@ -910,7 +910,7 @@ def delete_link(self, link_uuid: str) -> bool: return cursor.rowcount > 0 def delete_links_for_materials(self, material_uuids: Sequence[str]) -> int: - """物料(软)删除时物理清边;边不是 ledger 聚合,不留版本。""" + """物料(软)删除时物理清边:物料自己的账本行已经让客户端重读,不再给每条边记账本。""" uuids = [uuid for uuid in material_uuids if uuid] if not uuids: From 581fbae303b512aeb9da0b24914d8b66546dc632 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:29:16 +0800 Subject: [PATCH 39/59] docs: V1 POST /materials initializes a PLR instance and rejects templates it cannot instantiate --- docs/developer_guide/v1_dev_reconciliation.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/developer_guide/v1_dev_reconciliation.md b/docs/developer_guide/v1_dev_reconciliation.md index ddac075a5..9919ffe2d 100644 --- a/docs/developer_guide/v1_dev_reconciliation.md +++ b/docs/developer_guide/v1_dev_reconciliation.md @@ -108,7 +108,7 @@ Slave 时全部自动接受。现在: | `workflow/source_monitor.py` / `composition.py`(启动恢复与源码监视) | 部分:代码已搬但没有实例化,外部编辑不重编译,`writeback_status=pending` 永不重试 | 已实现 | `setup_local_scheduler` 启动时 `recover_registered_sources`(单个源码失败不挡启动)并起监视线程,`shutdown_backend_services` 关库前停线程;`tests/server/test_workflow_source_monitor_wiring.py`(重启后补写源码、运行期外部编辑出新候选)、`tests/app/test_process_lifetime.py` | | `workflow/authoring_ast.py` `repeat_until(carry=…)` + `loop.next()` / `until()`;`app/scheduler/dag_state.py` carry | 缺失:dev 循环不能跨轮传值,while 条件只有单项比较 | 已实现(原生写法) | 源码直接写 `while <条件>:`(与 if 同一套表达式,and / or / not,默认上限 1000 轮)和 `for i in range(n)`(n 为字面量或工作流输入);循环前赋值、循环体里重新赋值的变量逐轮携带,循环后是最终值;不支持运算、break / continue、循环 else、分支里改写携带的变量(编译报错);携带的值随轮次落 `control_data.loop.carry`,重启续用(`workflow_static_conditions.md`);`tests/server/test_workflow_loop_carry.py`。原 `with ctx.loop_*` 写法不变;V1 标记函数语法不移植 | -| `workflow/authoring_material_io.py`(作者 API 与发布校验);`app/scheduler/inventory/material_io.py`(人工装入 / 取走 / 补量运行时) | 不做(#6):`node_templates.py` 只列入可见类型,编译器没有 `material_io()`,调度器不接 | 已实现(负责人 2026-11-16 决定,结构按 dev) | 作者写 `x = ctx.material_io(mode=..., mount=..., site=..., ...)`(AST 编译,三种模式的必填 / 禁止字段与 V1 规则一致,`reagent` 为对象字面量、`quantity` 正数或工作流输入;新物料名用 `material_name`,`name=` 与 `ctx.run` 一样是步骤名),保存整图与起跑再各校验一次(`protocol/runtime/material_io.py`);`host_node` 名下投影「人工物料」结构模板,`generate-python` 生成同一写法。`executor_kind=material_io` 由权威侧调度器本地执行、从不派发 Host:起跑时物料权威试运行(`POST /inventory/material-io/check`,保存点内回滚)得到锁定集合(`mount`,unload / refill 另加 `material`)——库位被占 / 被其他任务占用按 `resource_wait_policy` 排队不失败;以 attempt 为 owner 取得物料锁(持久区间准入 + 执行 Claim,重启先于任务恢复,其他任务要用该库位的动作按原规则排队),持锁再试运行一次后冻结计划、开 durable 人工确认单(复用 `manual_confirm` 的确认单、超时、取消;5 秒兜底重算现在也收到期确认单);批准后一条 `material.io` 类型化库存命令在一个事务里装入(模板建物料 + 放入库位 + 可选试剂,已有物料不覆盖)/ 取走(`detach` / `soft_delete` × `material_only` / `material_with_contents`)/ 补量(原位唯一试剂加量),命令身份 = attempt,重放只写一次;写库被拒节点失败带物料错误码,拒绝 / 超时失败、库存不变,取消即取消;写库后把变化同步到挂载物料所属设备的台面(负责人 2026-11-17 决定「补一次同步」:load / unload 发 transfer 同款 `MaterialDeviceSync`,refill 发资源树 `update`,权威经 Host 中继;与 transfer 一样设备确认才算完成:失败不回滚库存,attempt 留在 pending、按同一命令身份重发直到设备确认,取消任务即以取消收口,结果在 `device_sync`,普通货架 `skipped`;重放同一命令再送一次是幂等的,终态落库后不再重发)。V1 的自动命名、模板白名单、试剂身份(`reagent_info_uuid` / CAS / 名称)一并保留;装入的模板是注册表 PLR 资源类(注册表同步的模板以资源条目 id 为名)时与 `instantiate_material` 同一条路实例化出整棵树、带默认子物料(负责人 2026-11-17 决定「装入也必须真的同步到台面」),挂载物料属于设备而模板不能实例化时试运行即拒绝,普通货架上不能实例化的模板只写身份(与 `POST /materials` 相同)。`tests/registry/test_workflow_material_io.py`、`tests/server/test_material_io_inventory.py`、`tests/server/test_material_io_scheduler.py`(排队、库位被占前后、重启待决 / 批准未写 / 写后未记各收敛一次、取消、执行器零派发)、`tests/server/test_material_io_device_sync.py` 与 `tests/client/host/hostlink/test_material_io_deck_sync.py`(真实 HostLink 设备台面上装入枪头盒连同孔位与枪头、台面同步三种模式、普通货架跳过、失败保留库存并按同一命令重发、取消收口、重放、权威经 Host 中继) | +| `workflow/authoring_material_io.py`(作者 API 与发布校验);`app/scheduler/inventory/material_io.py`(人工装入 / 取走 / 补量运行时) | 不做(#6):`node_templates.py` 只列入可见类型,编译器没有 `material_io()`,调度器不接 | 已实现(负责人 2026-11-16 决定,结构按 dev) | 作者写 `x = ctx.material_io(mode=..., mount=..., site=..., ...)`(AST 编译,三种模式的必填 / 禁止字段与 V1 规则一致,`reagent` 为对象字面量、`quantity` 正数或工作流输入;新物料名用 `material_name`,`name=` 与 `ctx.run` 一样是步骤名),保存整图与起跑再各校验一次(`protocol/runtime/material_io.py`);`host_node` 名下投影「人工物料」结构模板,`generate-python` 生成同一写法。`executor_kind=material_io` 由权威侧调度器本地执行、从不派发 Host:起跑时物料权威试运行(`POST /inventory/material-io/check`,保存点内回滚)得到锁定集合(`mount`,unload / refill 另加 `material`)——库位被占 / 被其他任务占用按 `resource_wait_policy` 排队不失败;以 attempt 为 owner 取得物料锁(持久区间准入 + 执行 Claim,重启先于任务恢复,其他任务要用该库位的动作按原规则排队),持锁再试运行一次后冻结计划、开 durable 人工确认单(复用 `manual_confirm` 的确认单、超时、取消;5 秒兜底重算现在也收到期确认单);批准后一条 `material.io` 类型化库存命令在一个事务里装入(模板建物料 + 放入库位 + 可选试剂,已有物料不覆盖)/ 取走(`detach` / `soft_delete` × `material_only` / `material_with_contents`)/ 补量(原位唯一试剂加量),命令身份 = attempt,重放只写一次;写库被拒节点失败带物料错误码,拒绝 / 超时失败、库存不变,取消即取消;写库后把变化同步到挂载物料所属设备的台面(负责人 2026-11-17 决定「补一次同步」:load / unload 发 transfer 同款 `MaterialDeviceSync`,refill 发资源树 `update`,权威经 Host 中继;与 transfer 一样设备确认才算完成:失败不回滚库存,attempt 留在 pending、按同一命令身份重发直到设备确认,取消任务即以取消收口,结果在 `device_sync`,普通货架 `skipped`;重放同一命令再送一次是幂等的,终态落库后不再重发)。V1 的自动命名、模板白名单、试剂身份(`reagent_info_uuid` / CAS / 名称)一并保留;装入的模板是注册表 PLR 资源类(注册表同步的模板以资源条目 id 为名)时与 `instantiate_material` 同一条路实例化出整棵树、带默认子物料(负责人 2026-11-17 决定「装入也必须真的同步到台面」),挂载物料属于设备而模板不能实例化时试运行即拒绝,普通货架上不能实例化的模板只写身份(`POST /materials` 不同:先初始化出 PLR 实例,实例化不出来一律拒绝)。`tests/registry/test_workflow_material_io.py`、`tests/server/test_material_io_inventory.py`、`tests/server/test_material_io_scheduler.py`(排队、库位被占前后、重启待决 / 批准未写 / 写后未记各收敛一次、取消、执行器零派发)、`tests/server/test_material_io_device_sync.py` 与 `tests/client/host/hostlink/test_material_io_deck_sync.py`(真实 HostLink 设备台面上装入枪头盒连同孔位与枪头、台面同步三种模式、普通货架跳过、失败保留库存并按同一命令重发、取消收口、重放、权威经 Host 中继) | ### 物料 name 是 uuid(负责人 2026-11-17 决定,与 V1 有意不同) @@ -118,7 +118,7 @@ V1 客户端把物料的 `name` 当显示名。dev 里物料层 `name` 恒等于 | 方面 | 现在 | 证据 | | --- | --- | --- | -| V1 写入 | `POST /materials` 的 `name` 落到 `display_name`(dev 超集可直接给 `display_name`),新根物料的 PLR 键取 `resource_id`;`PUT /materials/{uuid}` 的 `name` / `display_name` 只改 `display_name` | `tests/server/test_v1_resource_contract.py::test_v1_material_name_is_the_display_name` | +| V1 写入 | `POST /materials` 先初始化出 PLR 实例(请求 `config.type`,或注册表 PLR 资源类模板,或模板实现类是已知 PLR 类),按 `instantiate_material` 同一条转换建树、落位、装液(一个事务),实例化不出来报 1000;`name` 落到 `display_name`(dev 超集可直接给 `display_name`),新根物料的 PLR 键取 `resource_id`;`PUT /materials/{uuid}` 的 `name` / `display_name` 只改 `display_name` | `tests/server/test_v1_resource_contract.py::test_v1_material_name_is_the_display_name` | | V1 读取 | **有意差异**:`GET /materials`、`/resources`、`/inventory/instances` 返回的 `name` 是 uuid,显示名在同一对象的 `display_name`;`?name=` 筛选 / 精确搜索按 `display_name` 匹配,根物料按 `display_name` 排序 | `tests/resources/test_material_naming.py` | | 唯一性 | 根物料名唯一索引删除(`material` 表加 `CHECK (name = material_uuid)`,v1 基线原地修改);显示名可重名,唯一的是 `resource_id` | 同上 | | 旧数据 | 旧图在读取边界与 Graph Authority 对账时迁移(已是 UUID 的 name 作为身份复用);旧开发库按 D05 拒绝启动并提示重建 | `tests/server/test_database_schema_versions.py` | From 828548904661f679abac0101fe9eaddb69b76d92 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:57:23 +0800 Subject: [PATCH 40/59] fix(workflow): watch cursor advances only on workflow SSE ids material.changed and runtime log notices carry no SSE id. The watch loop used to fall back to data.sequence, so a materials ledger tail became the workflow cursor and every later task notice was dropped until watch_timeout. Only a frame's own integer id now moves the cursor. --- tests/app/test_workflow_watch_sse.py | 29 ++++++++++++++++++++++++++ unilabos/client/runtime/workflow.py | 31 ++++++++++++---------------- 2 files changed, 42 insertions(+), 18 deletions(-) diff --git a/tests/app/test_workflow_watch_sse.py b/tests/app/test_workflow_watch_sse.py index 0e36a2656..efe9a538f 100644 --- a/tests/app/test_workflow_watch_sse.py +++ b/tests/app/test_workflow_watch_sse.py @@ -13,12 +13,16 @@ import pytest from unilabos.client.runtime.workflow import ( + RUNTIME_CHANGED_EVENT, HTTPWorkflowClient, WorkflowClientError, _SSENoticeStream, _iter_text_lines, _parse_sse_lines, + _sse_frame_notice, ) +from unilabos.server.api.runtime.events import material_changed_frame +from unilabos.server.api.runtime.workflow import format_sse_event def test_sse_lines_split_crlf_across_chunks_without_extra_blank_lines() -> None: @@ -155,6 +159,31 @@ def test_watch_follows_stream_reset_and_skips_unchanged_snapshots() -> None: ] +def test_watch_cursor_ignores_id_less_material_notice() -> None: + # 服务端真实帧:水位帧、物料账本末尾 5000 的 material.changed(无 id)、任务通知 id 42。 + # material.changed 的 data.sequence 是物料账本序号,不能推进工作流游标,否则 42 会被丢弃。 + raw = ( + "retry: 3000\n: connected\n\n" + "id: 40\n\n" + + material_changed_frame(5000, ["m1"]) + + format_sse_event( + {"id": 42, "event": RUNTIME_CHANGED_EVENT, "data": {"kind": "task", "workflow_task_uuid": "task-1"}} + ) + ) + frames = [json.loads(_sse_frame_notice(frame)) for frame in _parse_sse_lines(_iter_text_lines([raw]))] + assert [(frame["action"], frame["id"]) for frame in frames] == [ + ("message", 40), ("material.changed", None), (RUNTIME_CHANGED_EVENT, 42), + ] + http = _Tasks(["running", "running", "succeeded"]) + client = HTTPWorkflowClient("http://edge:8002", http_client=http, notice_connector=lambda *_: _Notices(frames)) + events = list(client.watch_task("task-1", timeout=1)) + + assert [(event["kind"], event["task"]["status"], event["cursor"]) for event in events] == [ + ("task_snapshot", "running", 0), + ("task_changed", "succeeded", 42), + ] + + def test_schedule_addr_is_deprecated_and_not_used_for_watch() -> None: with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") diff --git a/unilabos/client/runtime/workflow.py b/unilabos/client/runtime/workflow.py index 5e19bbf49..7db6ea961 100644 --- a/unilabos/client/runtime/workflow.py +++ b/unilabos/client/runtime/workflow.py @@ -136,6 +136,7 @@ def _sse_frame_notice(frame: Mapping[str, Any]) -> str: data = json.loads(frame["data"]) if frame["data"] else {} except json.JSONDecodeError: data = {} + # 工作流事件流的 id 是十进制序号;其他形状(例如物料事件流的 ``:``)不是工作流游标。 try: sequence = int(frame["id"]) if frame["id"] is not None else None except ValueError: @@ -574,7 +575,7 @@ def watch_task( if sequence is not None: cursor = sequence elif not self._notice_matches_task(notice, task_uuid): - # 水位帧与其他任务的通知只推进游标,便于调用方用 after 续传。 + # 水位帧与其他任务的通知只推进游标,便于调用方用 after 续传;不带 id 的瞬时通知不动游标。 if sequence is not None and sequence > cursor: cursor = sequence continue @@ -659,23 +660,17 @@ def _notice_matches_task( ).lower() return any(token in event_type for token in ("workflow", "task", "job")) - @classmethod - def _notice_sequence(cls, notice: Mapping[str, Any]) -> Optional[int]: - # SSE 帧的 id 是持久通知序号,优先于 data 内的业务字段。 - top = notice.get("id") - if isinstance(top, int) and not isinstance(top, bool) and top >= 0: - return top - data = cls._notice_data(notice) - for key in ("event_sequence", "backend_sequence", "sequence", "id"): - value = data.get(key) - if isinstance(value, bool): - continue - try: - sequence = int(value) - except (TypeError, ValueError): - continue - if sequence >= 0: - return sequence + @staticmethod + def _notice_sequence(notice: Mapping[str, Any]) -> Optional[int]: + """只有带 SSE id 的帧(工作流持久事件、水位帧、``stream.reset``)才有游标序号。 + + ``material.changed``、``runtime.logs.changed`` 等瞬时通知不带 id,``data`` 里的 + ``sequence`` 属于别的账本(例如物料账本末尾),绝不能拿来推进工作流游标。 + """ + + value = notice.get("id") + if isinstance(value, int) and not isinstance(value, bool) and value >= 0: + return value return None From 34131c1332169959085b64503d10dd76ee4e2a6f Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:23:31 +0800 Subject: [PATCH 41/59] fix(workflow): the V1 requirement list follows the execution plan's rules The graph's root inventory_requirements is a projection of the nodes. It now uses the execution plan's rules in one place: - Disabled nodes and their descendants are not listed and do not turn a key into /. The disabled rule is the plan's own, now a shared node_or_ancestor_disabled, so preflight and task bindings, which resolve keys against the plan, accept every listed key. - Composite private sub-graphs are not listed on this layer, but still count for key uniqueness because bindings resolve against the whole plan. - Quantities are normalized like the scheduler reads them, so "1200" is 1200 and not a dynamic 0. The projection test about hiding private sub-graph requirements now uses a graph with private nodes. --- docs/developer_guide/api_v1_route_map.md | 2 +- ...kflow_inventory_requirements_projection.py | 93 ++++++++++- unilabos/server/api/runtime/workflow.py | 6 +- .../runtime/workflow/definition_edit.py | 149 +++++++++++------- .../services/runtime/workflow/service.py | 23 +-- 5 files changed, 185 insertions(+), 88 deletions(-) diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index bc5d752b0..d96e9cb43 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -220,7 +220,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | DTO-DIFF | `PUT /api/v1/workflows/{workflow_uuid}` | unilabos/app/workflow_api.py:1420 | PUT /api/v1/workflows/{workflow_uuid} | **Done (p7-a)**: Type cannot change (1000); category omitted keeps, null clears. Was: Same as POST /workflows | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/authoring/apply` | unilabos/app/workflow_api.py:2218 | POST /api/v1/workflows/{workflow_uuid}/authoring/apply | **Done (p7-a)**: Body `{candidate_hash}` only; draft hash and base revision are derived from the stored candidate (`WorkflowService.apply_authoring_by_candidate`). The triple-CAS body is rejected (1000). Was: V1 {candidate_hash} vs DEV {expected_draft_hash, expected_workflow_revision, expected_candidate_hash}. Both strict | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/composite-invocations` | unilabos/app/workflow_api.py:1597 | POST /api/v1/workflows/{workflow_uuid}/composite-invocations | **Done (p7-a)**: V1 body `{revision, contract_uuid, invocation_uuid, device_bindings, pose, param}`; child = the contract's workflow, child revision = the contract's revision; child must be an experiment operation (1000) whose current revision is published (3003); dev publications have no executor requirements, so `device_bindings` must be `{}`. Returns the parent graph (current layer), HTTP 200. Dev body removed. Was: V1 {revision, contract_uuid, invocation_uuid, device_bindings, pose, param} vs DEV {revision, child_workflow_uuid, child_revision, invocation_uuid, pose, arguments}. Both strict, so each rejects the other's body. V1 returns 200, DEV 201 | -| DTO-DIFF | `GET /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1449 | GET /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `workflow` gains `status`/`workflow_type`/`operation_category_uuid`; current layer only (V1 `definition_graph`); `inventory_requirements` is derived on every read from the nodes' `meta_data.inventory_requirements` (the single source; content→current_substance, lot→lot with allow_split, material→material 1 件; a key used by several nodes becomes `/`; the original entry is in `meta_data.unilab.inventory`). Was: V1 returns {workflow(+status, category), nodes, edges, inventory_requirements} for the current layer only. DEV returns {workflow, nodes, edges, node_templates, handle_templates} | +| DTO-DIFF | `GET /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1449 | GET /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `workflow` gains `status`/`workflow_type`/`operation_category_uuid`; current layer only (V1 `definition_graph`); `inventory_requirements` is derived on every read from the nodes' `meta_data.inventory_requirements` (the single source; quantities normalized as the scheduler reads them; content→current_substance, lot→lot with allow_split, material→material 1 件; disabled nodes and their descendants and composite private sub-graphs are not listed; a key used by several nodes of the execution plan, private sub-graphs included, becomes `/`, the form task bindings accept; the original entry is in `meta_data.unilab.inventory`). Was: V1 returns {workflow(+status, category), nodes, edges, inventory_requirements} for the current layer only. DEV returns {workflow, nodes, edges, node_templates, handle_templates} | | DTO-DIFF | `PUT /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1461 | PUT /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `site_binding_mode` defaults to `preserve` (V1 plain save); programmatic import (`client/runtime/workflow.py`, from-template) sends `resolve` explicitly. `node.manual_confirmation` persisted (runtime.db column). Composite private sub-graphs are restored when the client sends the current layer only. Was: DEV defaults site_binding_mode to 'resolve' (its own doc says browsers must send 'preserve'), so a V1 client's save can fail with site_binding_invalid. DEV also drops node.manual_confirmation | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/publications` | unilabos/app/workflow_api.py:1563 | POST /api/v1/workflows/{workflow_uuid}/publications | **Done (p7-a)**: Returns the V1 contract (`uuid` = contract_uuid, `workflow_revision`, `version`, `input_contract`, `output_contract`, `executor_requirements: []`, `node_template_uuid`, `node_count`, `edge_count`, `revision_fingerprint`) plus dev's palette fields (`revision`, `inputs`, `outputs`, `node_template`, `handle_templates`). Was: Request is the same ({revision}). V1 returns a public contract whose contract_uuid feeds composite-invocations; DEV returns a publication record. Field-level diff UNVERIFIED | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/run-preflight` | unilabos/app/workflow_api.py:1639 | POST /api/v1/workflows/{workflow_uuid}/run-preflight | **Done (p7-a)**: V1 body (`run_mode` string, `inventory_bindings` V1 DTO, extra fields ignored); bindings are applied to the candidate plan like task creation (an unmatched binding is an `invalid_inventory_binding` check, the inventory check reports against the bound source) and echoed in the report. `Cache-Control: no-store`. Was: F02. DEV is strict, forbids inventory_bindings and restricts run_mode to a Literal | diff --git a/tests/server/test_workflow_inventory_requirements_projection.py b/tests/server/test_workflow_inventory_requirements_projection.py index 20e6845dc..e79770641 100644 --- a/tests/server/test_workflow_inventory_requirements_projection.py +++ b/tests/server/test_workflow_inventory_requirements_projection.py @@ -90,15 +90,66 @@ def test_node_requirements_project_to_the_v1_list() -> None: assert (content["target_type"], content["required_quantity"], content["quantity_unit"]) == ("current_substance", 4.0, "ml") assert content["meta_data"]["unilab"]["material_source_node_uuid"] == "node-a" - # 与 definition_graph 的可见性过滤配合:私有子图节点的需求不出现在本层 - assert definition_graph({**graph, "inventory_requirements": items})["inventory_requirements"] == items - def test_graph_without_node_requirements_keeps_an_empty_list() -> None: graph = {"workflow": {"uuid": WORKFLOW}, "nodes": [{"uuid": "n", "meta_data": {}}], "edges": []} assert project_inventory_requirements(graph) == [] +def _water(quantity: Any = 100.0) -> list[dict[str, Any]]: + return [{"key": "water", "kind": "lot", "template_uuid": WATER_TEMPLATE, "quantity": quantity, "unit": "ul"}] + + +def test_private_subgraph_requirements_are_hidden_but_still_make_the_key_unique() -> None: + """组合调用的私有子图只在子操作定义里查看;它仍在执行计划里,同名 key 要写成 ``/`` 才能绑定。""" + + invocation = {"uuid": "call", "type": "workflow", "meta_data": {"unilab": {"composite": {"version": 1}}}} + graph = { + "workflow": {"uuid": WORKFLOW}, + "nodes": [ + _node("visible", _water()), + invocation, + {**_node("private", _water()), "parent_uuid": "call"}, + ], + "edges": [], + } + + [item] = project_inventory_requirements(graph) + assert item["consume_node_uuid"] == "visible" + assert item["requirement_key"] == "visible/water" + # 读图投影同一规则:私有节点本身也不在本层 + assert [node["uuid"] for node in definition_graph(graph)["nodes"]] == ["visible", "call"] + + +def test_disabled_nodes_and_their_descendants_are_not_listed() -> None: + """禁用节点(含禁用分组里的步骤)不进执行计划:需求不列出,也不让同名 key 变成 ``/``。""" + + graph = { + "workflow": {"uuid": WORKFLOW}, + "nodes": [ + _node("enabled", _water()), + {**_node("off", _water()), "disabled": True}, + {"uuid": "group", "type": "group", "disabled": True, "meta_data": {}}, + {**_node("in-group", _water()), "parent_uuid": "group"}, + ], + "edges": [], + } + + [item] = project_inventory_requirements(graph) + assert (item["consume_node_uuid"], item["requirement_key"]) == ("enabled", "water") + + +def test_numeric_string_quantity_is_projected_like_the_scheduler_reads_it() -> None: + """调度按 ``normalize_inventory`` 读 ``"1200"`` 为 1200;列表不能把它当成运行时决定的 0。""" + + [item] = project_inventory_requirements({"workflow": {"uuid": WORKFLOW}, "nodes": [_node("n", _water("1200"))]}) + assert item["required_quantity"] == 1200.0 + assert item["meta_data"]["unilab"]["quantity_dynamic"] is False + assert item["meta_data"]["unilab"]["deferred"] is False + # 原条目原样保留(导入时按它与节点比对) + assert item["meta_data"]["unilab"]["inventory"]["quantity"] == "1200" + + @pytest.fixture def api(): service = WorkflowService(":memory:") @@ -179,3 +230,39 @@ def test_an_exported_graph_imports_again_and_a_handwritten_root_list_is_still_re refused = client.post("/api/v1/workflows/import", json={**exported, "name": "手写", "inventory_requirements": edited}) assert refused.status_code == 200 and refused.json()["code"] == 1000 assert "inventory_requirements" in refused.json()["error"]["msg"] + + +def test_every_listed_requirement_key_binds_in_preflight(api) -> None: + """列表给出的 requirement_key 拿去预检绑定,不会因为禁用节点报 invalid_inventory_binding。""" + + client, service = api + workflow = _ok(client.post("/api/v1/workflows", json={"name": "绑定", "workflow_type": "experiment_operation"}), 201) + container = str(uuid4()) + + def node(name: str, **extra: Any) -> dict[str, Any]: + return { + "uuid": str(uuid4()), "name": name, "type": "device_action", "material_uuid": str(uuid4()), + "action_name": "fill_well", "action_type": "UniLabJsonCommand", "param": {"slot": "T1"}, + "pose": {"x": 0, "y": 0}, "execution_policy": {"depends_on": []}, + "meta_data": {"target_device_id": "material_bench", "inventory_requirements": [ + {"key": "buffer", "kind": "content", "material_uuid": container, "substance_name": "PBS", + "quantity": 4.0, "unit": "ml"}, + ]}, + **extra, + } + + _ok(client.put(f"/api/v1/workflows/{workflow['uuid']}/graph", json={ + "revision": workflow["revision"], "nodes": [node("启用"), node("禁用", disabled=True)], "edges": [], + })) + listed = _ok(client.get(f"/api/v1/workflows/{workflow['uuid']}/graph"))["inventory_requirements"] + assert [item["requirement_key"] for item in listed] == ["buffer"] + for item in listed: + report = service.preflight_workflow( + workflow_uuid=workflow["uuid"], run_mode="normal", target_node_uuid=None, input_value={}, + expected_revision=None, inventory_bindings=[{ + "requirement_key": item["requirement_key"], "inventory_type": "current_substance", + "inventory_uuid": str(uuid4()), "reserved_quantity": item["required_quantity"], + "quantity_unit": item["quantity_unit"], + }], + ) + assert "invalid_inventory_binding" not in {check["code"] for check in report["checks"]}, report["checks"] diff --git a/unilabos/server/api/runtime/workflow.py b/unilabos/server/api/runtime/workflow.py index 30136d552..1aef8da56 100644 --- a/unilabos/server/api/runtime/workflow.py +++ b/unilabos/server/api/runtime/workflow.py @@ -530,9 +530,9 @@ def with_workflow_status(payload: Any) -> Any: return payload projected = dict(payload) projected["workflow"] = public_workflow(workflow) - # 库存需求只存在节点 meta_data 里(调度唯一来源);V1 图根列表每次从节点派生,供客户端查看。 - if not projected.get("inventory_requirements"): - projected["inventory_requirements"] = project_inventory_requirements(projected) + # 库存需求只存在节点 meta_data 里(调度唯一来源);V1 图根列表每次从完整图派生(禁用、私有子图的 + # 规则在投影里),供客户端查看。 + projected["inventory_requirements"] = project_inventory_requirements(projected) return definition_graph(projected) def write_payload(body: BaseModel) -> Dict[str, Any]: diff --git a/unilabos/server/services/runtime/workflow/definition_edit.py b/unilabos/server/services/runtime/workflow/definition_edit.py index e5f25b52e..f94a9f144 100644 --- a/unilabos/server/services/runtime/workflow/definition_edit.py +++ b/unilabos/server/services/runtime/workflow/definition_edit.py @@ -8,12 +8,13 @@ from typing import Any, Mapping from uuid import NAMESPACE_URL, uuid4, uuid5 -from unilabos.protocol.runtime.inventory import inventory_deferred +from unilabos.protocol.runtime.inventory import inventory_deferred, normalize_inventory from unilabos.protocol.runtime.workflow import ( normalize_json_object, normalize_manual_confirmation, validate_uuid, ) +from unilabos.server.services.runtime.workflow.errors import StoreConflict class WorkflowDefinitionInvalid(ValueError): @@ -281,6 +282,24 @@ def duplicate_graph( return nodes, edges, requirements +def node_or_ancestor_disabled(node: Mapping[str, Any], nodes: Mapping[str, Mapping[str, Any]]) -> bool: + """节点自己或任一祖先(分组 / 循环 / 组合调用)被禁用:不进执行计划,需求不预留、不列出。""" + + current: Mapping[str, Any] | None = node + seen: set[str] = set() + while current is not None: + if bool(current.get("disabled", False)): + return True + parent_uuid = current.get("parent_uuid") + if parent_uuid is None: + return False + identity = str(parent_uuid) + if identity in seen: + raise StoreConflict("workflow node parent hierarchy contains a cycle") + seen.add(identity) + current = nodes.get(identity) + return False + def private_node_owners(nodes: list[dict[str, Any]]) -> dict[str, str]: """返回私有后代到最外层子操作入口的映射,不跨越当前定义边界。""" @@ -315,75 +334,92 @@ def _finite_number(value: Any) -> float | None: return number if math.isfinite(number) else None +def _declared_inventory(node: Mapping[str, Any]) -> list[Mapping[str, Any]]: + meta = node.get("meta_data") if isinstance(node.get("meta_data"), Mapping) else {} + return [item for item in meta.get("inventory_requirements") or [] if isinstance(item, Mapping)] + + +def _listable(item: Mapping[str, Any]) -> bool: + """V1 列表能表达的需求条目:kind 已知且 key 非空。""" + + return item.get("kind") in _V1_TARGET_TYPES and bool(str(item.get("key") or "")) + + def project_inventory_requirements(graph: Mapping[str, Any]) -> list[dict[str, Any]]: """节点 ``meta_data.inventory_requirements`` → V1 图根 ``inventory_requirements``(只读投影)。 节点级需求是调度、预检与绑定的唯一来源;V1 图根列表只给客户端看,每次读取都从节点派生, 不单独存储。V1 形状没有 kind / 模板 / 批次 / 容器身份,原条目原样放进 - ``meta_data.unilab.inventory``;数量是运行时引用时记 0 并标 ``quantity_dynamic``。 - 同一 key 出现在多个节点时 ``requirement_key`` 写成 ``/``,与任务绑定的写法一致。 + ``meta_data.unilab.inventory``;数量先按调度同一规则规范化(``normalize_inventory``), + 是运行时引用时记 0 并标 ``quantity_dynamic``。 + + 列哪些条目与执行计划同一规则:禁用节点及其后代不执行,需求不列出;组合调用的私有子图只在子操作 + 定义里查看,本层不列出。``requirement_key`` 在同一 key 出现在执行计划多个节点(含私有子图)时写成 + ``/``:任务绑定按执行计划解析 key,列表给出的 key 必须能直接拿去绑定。 """ workflow = graph.get("workflow") if isinstance(graph.get("workflow"), Mapping) else {} workflow_uuid = str(workflow.get("uuid") or "") - entries: list[tuple[Mapping[str, Any], Mapping[str, Any]]] = [] - for node in graph.get("nodes") or []: - if not isinstance(node, Mapping): - continue - meta = node.get("meta_data") if isinstance(node.get("meta_data"), Mapping) else {} - for item in meta.get("inventory_requirements") or []: - if isinstance(item, Mapping) and item.get("kind") in _V1_TARGET_TYPES and str(item.get("key") or ""): - entries.append((node, item)) - key_counts = Counter(str(item["key"]) for _, item in entries) + nodes = [node for node in graph.get("nodes") or [] if isinstance(node, Mapping)] + index = {str(node["uuid"]): node for node in nodes} + executed = [node for node in nodes if not node_or_ancestor_disabled(node, index)] + key_counts = Counter( + str(item["key"]) for node in executed for item in _declared_inventory(node) if _listable(item) + ) + private = private_node_owners(nodes) projected: list[dict[str, Any]] = [] - for node, item in entries: - node_uuid = str(node.get("uuid") or "") - if not node_uuid: + for node in executed: + node_uuid = str(node["uuid"]) + if node_uuid in private: continue + declared = _declared_inventory(node) meta = node.get("meta_data") if isinstance(node.get("meta_data"), Mapping) else {} - node_items = [entry for entry in meta.get("inventory_requirements") or [] if isinstance(entry, Mapping)] policy = node.get("execution_policy") if isinstance(node.get("execution_policy"), Mapping) else {} mode = str(meta.get("inventory_mode") or "task") try: - deferred = inventory_deferred([dict(entry) for entry in node_items], policy=policy, mode=mode) + normalized = normalize_inventory([dict(item) for item in declared]) + deferred = inventory_deferred(normalized, policy=policy, mode=mode) except ValueError: - deferred = True - kind = str(item["kind"]) - key = str(item["key"]) - if kind == "material": - quantity, unit = _MATERIAL_QUANTITY - dynamic = False - else: - number = _finite_number(item.get("quantity")) - raw_unit = item.get("unit") - dynamic = number is None or not isinstance(raw_unit, str) or not raw_unit.strip() - quantity = number if number is not None else 0.0 - unit = raw_unit.strip() if isinstance(raw_unit, str) and raw_unit.strip() else _DYNAMIC_UNIT - unilab: dict[str, Any] = { - "inventory": deepcopy(dict(item)), - "inventory_mode": mode, - "deferred": deferred, - "quantity_dynamic": dynamic, - } - source = item.get("material_uuid") - if isinstance(source, Mapping) and source.get("kind") == "node_output": - source_node = str(source.get("workflow_node_uuid") or "") - if source_node: - unilab["material_source_node_uuid"] = source_node - projected.append( - { - "uuid": str(uuid5(NAMESPACE_URL, f"unilabos://workflow/{workflow_uuid}/{node_uuid}/{key}")), - "workflow_uuid": workflow_uuid, - "consume_node_uuid": node_uuid, - "requirement_key": key if key_counts[key] == 1 else f"{node_uuid}/{key}", - "target_type": _V1_TARGET_TYPES[kind], - "required_quantity": quantity, - "quantity_unit": unit, - "allow_split": kind == "lot", - "meta_data": {"unilab": unilab}, + normalized, deferred = [dict(item) for item in declared], True + for raw, item in zip(declared, normalized): + if not _listable(raw): + continue + kind = str(item["kind"]) + key = str(item["key"]) + if kind == "material": + quantity, unit = _MATERIAL_QUANTITY + dynamic = False + else: + number = _finite_number(item.get("quantity")) + raw_unit = item.get("unit") + dynamic = number is None or not isinstance(raw_unit, str) or not raw_unit.strip() + quantity = number if number is not None else 0.0 + unit = raw_unit.strip() if isinstance(raw_unit, str) and raw_unit.strip() else _DYNAMIC_UNIT + unilab: dict[str, Any] = { + "inventory": deepcopy(dict(raw)), + "inventory_mode": mode, + "deferred": deferred, + "quantity_dynamic": dynamic, } - ) + source = raw.get("material_uuid") + if isinstance(source, Mapping) and source.get("kind") == "node_output": + source_node = str(source.get("workflow_node_uuid") or "") + if source_node: + unilab["material_source_node_uuid"] = source_node + projected.append( + { + "uuid": str(uuid5(NAMESPACE_URL, f"unilabos://workflow/{workflow_uuid}/{node_uuid}/{key}")), + "workflow_uuid": workflow_uuid, + "consume_node_uuid": node_uuid, + "requirement_key": key if key_counts[key] == 1 else f"{node_uuid}/{key}", + "target_type": _V1_TARGET_TYPES[kind], + "required_quantity": quantity, + "quantity_unit": unit, + "allow_split": kind == "lot", + "meta_data": {"unilab": unilab}, + } + ) return projected @@ -414,14 +450,6 @@ def definition_graph(graph: Mapping[str, Any]) -> dict[str, Any]: for edge in result["edges"] if edge["source_node_uuid"] in visible and edge["target_node_uuid"] in visible ] - if "inventory_requirements" in result: - # 子操作的数量需求在其定义中查看;本层只列自己声明的需求。 - result["inventory_requirements"] = [ - item - for item in result.get("inventory_requirements") or [] - if str(item.get("consume_node_uuid") or "") in visible - and not ((item.get("meta_data") or {}).get("unilab") or {}).get("composite_origin") - ] templates = {node.get("workflow_node_template_uuid") for node in result["nodes"]} result["node_templates"] = [ item for item in result.get("node_templates", []) if item["uuid"] in templates @@ -498,6 +526,7 @@ def restore_private_subgraphs( "duplicate_graph", "duplicate_node", "is_derived_inventory_requirements", + "node_or_ancestor_disabled", "patch_node", "private_node_owners", "project_inventory_requirements", diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 21a32f119..4a7d3d440 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -89,6 +89,7 @@ publication_source_hash, publication_summary, ) +from unilabos.server.services.runtime.workflow.definition_edit import node_or_ancestor_disabled from unilabos.server.services.runtime.workflow.definition_service import WorkflowDefinitionEditing from unilabos.server.services.runtime.workflow.node_templates import NodeTemplateCatalog from unilabos.server.services.runtime.workflow.operation_category import ( @@ -2143,7 +2144,7 @@ def stable_key(node_uuid: str) -> Tuple[int, int, str, str]: continue kind = self._executor_kind(raw_kind) all_kinds[node["uuid"]] = kind - if self._node_or_ancestor_disabled(node, node_index) or kind == "group": + if node_or_ancestor_disabled(node, node_index) or kind == "group": continue enabled[node["uuid"]] = node node_kinds[node["uuid"]] = kind @@ -2493,26 +2494,6 @@ def order_level(container: Optional[str]) -> List[str]: raise StoreConflict(str(exc)) from None return plan, jobs - @staticmethod - def _node_or_ancestor_disabled( - node: Mapping[str, Any], - nodes: Mapping[str, Mapping[str, Any]], - ) -> bool: - current: Mapping[str, Any] | None = node - seen: set[str] = set() - while current is not None: - if bool(current.get("disabled", False)): - return True - parent_uuid = current.get("parent_uuid") - if parent_uuid is None: - return False - identity = str(parent_uuid) - if identity in seen: - raise StoreConflict("workflow node parent hierarchy contains a cycle") - seen.add(identity) - current = nodes.get(identity) - return False - @staticmethod def _template_param_schema(schema: Any) -> Any: """节点模板行里的 schema 是 JSON 文本,执行计划里的 ``param_schema`` 按字典读取。 From de4c2748bb23b6261e22750020d22b666cb594ec Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:28:08 +0800 Subject: [PATCH 42/59] fix(workflow): import and copy remap every reference to a node duplicate_graph gave nodes and edges new ids but only rewrote parent_uuid and edge ends. Everything else kept the old ids: a node_output material source on an inventory requirement, depends_on, condition_guards, condition and loop expressions, carry_next, result references in params and composite mappings. An exported graph with a node_output source was therefore refused on import. Node ids are UUIDs, so remap_node_references rewrites every string or key that equals an old node id, without listing shapes. Copying a workflow also runs the workflow's own reserved metadata (output bindings, resource scopes) through the same table, so they point at the copy's nodes. The unused requirement duplication is gone. --- docs/developer_guide/api_v1_route_map.md | 4 +- .../test_workflow_export_import_roundtrip.py | 183 ++++++++++++++++++ .../runtime/workflow/definition_edit.py | 71 ++++--- .../runtime/workflow/definition_service.py | 6 +- .../services/runtime/workflow/service.py | 2 +- 5 files changed, 223 insertions(+), 43 deletions(-) create mode 100644 tests/server/test_workflow_export_import_roundtrip.py diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index d96e9cb43..6ac582b23 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -207,9 +207,9 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | MISSING | `GET /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1664 | - | **Done (p7-a)**: | | MISSING | `PATCH /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1676 | - | **Done (p7-a)**: Only explicitly sent fields are applied. | | MISSING | `POST /api/v1/workflow-nodes/{node_uuid}/duplicate` | unilabos/app/workflow_api.py:1693 | - | **Done (p7-a)**: | -| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`); `workflow_type` honoured; a root `inventory_requirements` list is rejected as in V1 unless it is exactly the list the graph read derives from the imported nodes (an exported graph imports again; uuids are ignored in the comparison). Was: Legacy JSON import. Used by the V1 console | +| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`; every string or key equal to an old node uuid is rewritten, so edges, `parent_uuid`, `depends_on` / `condition_guards`, condition and loop expressions, `node_output` references in params and inventory requirements and composite mappings all follow); `workflow_type` honoured; a root `inventory_requirements` list is rejected as in V1 unless it is exactly the list the graph read derives from the imported nodes (an exported graph imports again; uuids are ignored in the comparison). Was: Legacy JSON import. Used by the V1 console | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/batch-delete` | unilabos/app/workflow_api.py:1532 | - | **Done (p7-a)**: | -| MISSING | `POST /api/v1/workflows/{workflow_uuid}/duplicate` | unilabos/app/workflow_api.py:1549 | - | **Done (p7-a)**: Copies kind/category too. | +| MISSING | `POST /api/v1/workflows/{workflow_uuid}/duplicate` | unilabos/app/workflow_api.py:1549 | - | **Done (p7-a)**: Copies kind/category too; node references in the graph and in the workflow's reserved metadata (output bindings, resource scopes) point at the copy's own nodes. | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/edges` | unilabos/app/workflow_api.py:1515 | (whole-graph PUT only) | **Done (p7-a)**: Returns the saved graph (201). Was: Used by the V1 console | | MISSING | `GET /api/v1/workflows/{workflow_uuid}/nodes` | unilabos/app/workflow_api.py:1494 | - | **Done (p7-a)**: Current layer only (composite private sub-graphs hidden). | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/nodes` | unilabos/app/workflow_api.py:1477 | (whole-graph PUT only) | **Done (p7-a)**: Template nodes derive type/action/defaults from `/workflow-node-templates`; a fixed material also writes `meta_data.target_device_id` (dev dispatch key). Returns the saved graph (201). Was: Used by the V1 console | diff --git a/tests/server/test_workflow_export_import_roundtrip.py b/tests/server/test_workflow_export_import_roundtrip.py new file mode 100644 index 000000000..b1f45b41f --- /dev/null +++ b/tests/server/test_workflow_export_import_roundtrip.py @@ -0,0 +1,183 @@ +"""导入与复制换掉节点身份时,图里所有指向节点的引用一并改写。""" + +from __future__ import annotations + +import json +import uuid +from typing import Any, TypedDict + +import pytest +from fastapi.testclient import TestClient + +from unilabos.registry.workflows import ( + DeviceCatalog, + build_workflow_template_payload, + clear_registered_workflows, + get_registered_workflows, + materialize_workflow_template, + upsert_workflow, + workflow, +) +from unilabos.server.api.runtime.workflow import create_workflow_app +from unilabos.server.services.runtime.workflow.definition_edit import duplicate_graph +from unilabos.server.services.runtime.workflow.service import WorkflowService + +WATER = "33333333-3333-4333-8333-333333333333" +DEVICE = "44444444-4444-4444-8444-444444444444" + + +@pytest.fixture(autouse=True) +def _isolated_workflow_registry(): + from unilabos.registry.workflows import _registered_workflows + + snapshot = get_registered_workflows() + clear_registered_workflows() + yield + clear_registered_workflows() + for definition in snapshot.values(): + _registered_workflows[definition.uuid] = definition + + +@pytest.fixture +def api(): + service = WorkflowService(":memory:") + try: + yield TestClient(create_workflow_app(service)), service + finally: + service.close() + + +def _ok(response, status: int = 200) -> Any: + assert response.status_code == status, response.text + body = response.json() + assert body["code"] == 0, body + return body.get("data") + + +def _store(service: WorkflowService, display_name: str) -> dict[str, Any]: + definition = next(item for item in get_registered_workflows().values() if item.display_name == display_name) + catalog = DeviceCatalog() + catalog.add("carry-device", "carry_demo_class", DEVICE) + return upsert_workflow(service, materialize_workflow_template(build_workflow_template_payload(definition), catalog)) + + +def _import(client: TestClient, exported: dict[str, Any], name: str) -> str: + imported = _ok(client.post("/api/v1/workflows/import", json={**exported, "name": name}), 201) + return imported["workflow"]["uuid"] + + +def test_duplicate_graph_remaps_every_node_reference() -> None: + """图里每一种指向节点的引用都换成新身份;旧身份一个不剩。""" + + ids = {name: str(uuid.uuid4()) for name in ("source", "loop", "body", "cond", "call", "group", "member")} + handle = str(uuid.uuid4()) + graph = { + "nodes": [ + {"uuid": ids["source"], "name": "source", "param": {}, "meta_data": {}}, + {"uuid": ids["group"], "name": "group", "type": "group", "meta_data": {}}, + {"uuid": ids["member"], "name": "member", "parent_uuid": ids["group"], + "execution_policy": {"depends_on": [ids["source"]], + "condition_guards": [{"node_uuid": ids["cond"], "equals": True}]}, + "param": {"value": {"kind": "node_output", "workflow_node_uuid": ids["source"], "data_key": "v"}}, + "meta_data": {"inventory_requirements": [ + {"key": "buffer", "kind": "content", "substance_name": "PBS", "quantity": 4, "unit": "ml", + "material_uuid": {"kind": "node_output", "workflow_node_uuid": ids["source"], "data_key": "plate"}}, + ]}}, + {"uuid": ids["loop"], "name": "loop", "type": "loop", + "param": {"expression": {"op": "lt", "args": [{"field": {"node_uuid": ids["loop"]}, "name": "n"}, {"lit": 3}]}, + "condition": {"source": "node_output", "node_uuid": ids["body"], "field": "ok"}, + "carry_next": {"n": {"kind": "node_output", "workflow_node_uuid": ids["body"], "data_key": "v"}}}, + "meta_data": {}}, + {"uuid": ids["body"], "name": "body", "parent_uuid": ids["loop"], "meta_data": {}}, + {"uuid": ids["cond"], "name": "cond", "type": "condition", + "param": {"version": 1, "expression": {"field": {"node_uuid": ids["source"]}, "name": "ok"}}, "meta_data": {}}, + {"uuid": ids["call"], "name": "call", "type": "workflow", + "param": {"x": {"kind": "node_output", "workflow_node_uuid": ids["source"], "source_handle_uuid": handle}}, + "meta_data": {"unilab": {"composite": { + "target_mappings": {handle: [{"workflow_node_uuid": ids["body"], "target_handle_uuid": handle}]}, + "resource_scopes": [{"node_uuids": [ids["body"]], "entry_node_uuid": ids["body"]}], + }}}}, + ], + "edges": [{"uuid": str(uuid.uuid4()), "source_node_uuid": ids["source"], "target_node_uuid": ids["cond"], + "source_handle_uuid": handle, "target_handle_uuid": handle}], + } + + nodes, edges, identity = duplicate_graph(graph) + + text = json.dumps({"nodes": nodes, "edges": edges}) + assert not any(old in text for old in ids.values()) + new = {name: identity[old] for name, old in ids.items()} + by_name = {node["name"]: node for node in nodes} + member, loop, call = by_name["member"], by_name["loop"], by_name["call"] + assert member["parent_uuid"] == new["group"] and by_name["body"]["parent_uuid"] == new["loop"] + assert member["execution_policy"] == {"depends_on": [new["source"]], + "condition_guards": [{"node_uuid": new["cond"], "equals": True}]} + assert member["param"]["value"]["workflow_node_uuid"] == new["source"] + assert member["meta_data"]["inventory_requirements"][0]["material_uuid"]["workflow_node_uuid"] == new["source"] + assert loop["param"]["expression"]["args"][0]["field"] == {"node_uuid": new["loop"]} + assert loop["param"]["condition"]["node_uuid"] == new["body"] + assert loop["param"]["carry_next"]["n"]["workflow_node_uuid"] == new["body"] + assert by_name["cond"]["param"]["expression"]["field"] == {"node_uuid": new["source"]} + assert call["param"]["x"]["workflow_node_uuid"] == new["source"] + composite = call["meta_data"]["unilab"]["composite"] + assert composite["target_mappings"][handle][0]["workflow_node_uuid"] == new["body"] + assert composite["resource_scopes"][0] == {"node_uuids": [new["body"]], "entry_node_uuid": new["body"]} + assert (edges[0]["source_node_uuid"], edges[0]["target_node_uuid"]) == (new["source"], new["cond"]) + # 非节点引用(Handle、字面量)不动 + assert edges[0]["source_handle_uuid"] == handle and loop["param"]["expression"]["args"][1] == {"lit": 3} + + +def test_node_output_material_source_survives_export_and_import(api) -> None: + """库存需求的来源是上游节点的结果:导入后指向副本里的那个节点(以前留着旧身份,导入被拒)。""" + + client, _service = api + workflow_record = _ok(client.post("/api/v1/workflows", json={"name": "来源"}), 201) + + def node(name: str, requirements: list[dict[str, Any]], depends_on: list[str]) -> dict[str, Any]: + return { + "uuid": str(uuid.uuid4()), "name": name, "type": "device_action", "material_uuid": str(uuid.uuid4()), + "action_name": "fill_well", "action_type": "UniLabJsonCommand", "param": {"slot": "T1"}, + "pose": {"x": 0, "y": 0}, "execution_policy": {"depends_on": depends_on}, + "meta_data": {"target_device_id": "material_bench", "inventory_requirements": requirements}, + } + + plate = node("取板", [], []) + fill = node("加液", [{"key": "buffer", "kind": "content", "substance_name": "PBS", "quantity": 4, "unit": "ml", + "material_uuid": {"kind": "node_output", "workflow_node_uuid": plate["uuid"], "data_key": "plate"}}], + [plate["uuid"]]) + _ok(client.put(f"/api/v1/workflows/{workflow_record['uuid']}/graph", json={ + "revision": workflow_record["revision"], "nodes": [plate, fill], "edges": []})) + exported = _ok(client.get(f"/api/v1/workflows/{workflow_record['uuid']}/graph")) + + copy = _ok(client.get(f"/api/v1/workflows/{_import(client, exported, '来源副本')}/graph")) + by_name = {item["name"]: item for item in copy["nodes"]} + source = by_name["加液"]["meta_data"]["inventory_requirements"][0]["material_uuid"]["workflow_node_uuid"] + assert source == by_name["取板"]["uuid"] != plate["uuid"] + assert by_name["加液"]["execution_policy"]["depends_on"] == [by_name["取板"]["uuid"]] + assert copy["inventory_requirements"][0]["meta_data"]["unilab"]["material_source_node_uuid"] == source + + +class Result(TypedDict): + value: float + + +def test_copy_remaps_workflow_level_references() -> None: + """复制工作流:输出绑定与资源作用域引用的是副本自己的节点,不再指向原工作流。""" + + @workflow(display_name="复制") + def flow(ctx) -> Result: + out = ctx.run("carry-device/add", {"value": 1}, name="加") + with ctx.lock("carry-device", name="锁"): + ctx.run("carry-device/note", {"text": "x"}, name="记") + return {"value": out.value} + + service = WorkflowService(":memory:") + try: + source = service.get_graph(_store(service, "复制")["uuid"]) + copy = service.duplicate_workflow(source["workflow"]["uuid"], name="副本") + unilab = copy["workflow"]["meta_data"]["unilab"] + by_name = {node["name"]: node["uuid"] for node in copy["nodes"]} + assert unilab["output_bindings"]["value"]["workflow_node_uuid"] == by_name["加"] + assert unilab["resource_scopes"][0]["node_uuids"] == [by_name["记"]] + finally: + service.close() diff --git a/unilabos/server/services/runtime/workflow/definition_edit.py b/unilabos/server/services/runtime/workflow/definition_edit.py index f94a9f144..9ac58cafa 100644 --- a/unilabos/server/services/runtime/workflow/definition_edit.py +++ b/unilabos/server/services/runtime/workflow/definition_edit.py @@ -228,58 +228,52 @@ def create_edge(payload: Mapping[str, Any]) -> dict[str, Any]: } +def remap_node_references(value: Any, identity: Mapping[str, str]) -> Any: + """按身份表改写 ``value`` 里所有指向节点的引用,返回新对象。 + + 节点身份是 UUID:任何与某个旧节点身份相等的字符串(值或字典键)都是对该节点的引用, + 不按字段逐个列举形状。图里现有的形状:``parent_uuid``(分组 / 循环体 / 组合调用私有子图)、 + 连线两端、``execution_policy`` 的 ``depends_on`` 与 ``condition_guards[].node_uuid``、条件与循环 + 表达式的 ``{"node_uuid"}``、旧式循环条件 ``condition.node_uuid``、参数 / 循环 ``carry_next`` / + 库存需求里的结果引用 ``{"kind": "node_output", "workflow_node_uuid"}``、组合调用实参的结果引用, + 以及组合调用 ``meta_data.unilab.composite`` 的边界映射与资源作用域成员。 + """ + + if isinstance(value, str): + return identity.get(value, value) + if isinstance(value, Mapping): + return { + identity.get(key, key) if isinstance(key, str) else key: remap_node_references(item, identity) + for key, item in value.items() + } + if isinstance(value, (list, tuple)): + return [remap_node_references(item, identity) for item in value] + return deepcopy(value) + + def duplicate_graph( graph: Mapping[str, Any], -) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: - """复制完整图并重建节点、父子、连线和数量需求身份引用。""" +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, str]]: + """复制完整图:节点与连线换新身份,图里所有指向节点的引用随之改写。 + + 返回 ``(节点, 连线, 旧身份 → 新身份)``;调用方用同一张表改写图外(例如工作流元数据)的引用。 + """ - node_identity = {str(node["uuid"]): str(uuid4()) for node in graph["nodes"]} + identity = {str(node["uuid"]): str(uuid4()) for node in graph["nodes"]} nodes: list[dict[str, Any]] = [] for source in graph["nodes"]: - node = deepcopy(dict(source)) - node["uuid"] = node_identity[str(source["uuid"])] - parent_uuid = source.get("parent_uuid") - node["parent_uuid"] = node_identity.get(str(parent_uuid)) if parent_uuid else None + node = remap_node_references(source, identity) for field in ("create_time", "update_time", "deleted_at", "workflow_uuid"): node.pop(field, None) nodes.append(node) edges: list[dict[str, Any]] = [] for source in graph["edges"]: - edge = deepcopy(dict(source)) + edge = remap_node_references(source, identity) edge["uuid"] = str(uuid4()) - edge["source_node_uuid"] = node_identity[str(source["source_node_uuid"])] - edge["target_node_uuid"] = node_identity[str(source["target_node_uuid"])] for field in ("create_time", "update_time", "deleted_at"): edge.pop(field, None) edges.append(edge) - requirements: list[dict[str, Any]] = [] - for source in graph.get("inventory_requirements", []): - requirement = deepcopy(dict(source)) - requirement["uuid"] = str(uuid4()) - requirement["consume_node_uuid"] = node_identity[ - str(source["consume_node_uuid"]) - ] - metadata = requirement.get("meta_data") - unilab = metadata.get("unilab") if isinstance(metadata, dict) else None - source_node_uuid = ( - unilab.get("material_source_node_uuid") - if isinstance(unilab, dict) - else None - ) - if source_node_uuid is not None: - unilab["material_source_node_uuid"] = node_identity[ - str(source_node_uuid) - ] - for field in ( - "create_time", - "update_time", - "deleted_at", - "workflow_uuid", - "sort_order", - ): - requirement.pop(field, None) - requirements.append(requirement) - return nodes, edges, requirements + return nodes, edges, identity def node_or_ancestor_disabled(node: Mapping[str, Any], nodes: Mapping[str, Mapping[str, Any]]) -> bool: @@ -530,5 +524,6 @@ def restore_private_subgraphs( "patch_node", "private_node_owners", "project_inventory_requirements", + "remap_node_references", "restore_private_subgraphs", ] diff --git a/unilabos/server/services/runtime/workflow/definition_service.py b/unilabos/server/services/runtime/workflow/definition_service.py index d2975bc44..16b007df3 100644 --- a/unilabos/server/services/runtime/workflow/definition_service.py +++ b/unilabos/server/services/runtime/workflow/definition_service.py @@ -20,6 +20,7 @@ duplicate_graph, duplicate_node, patch_node, + remap_node_references, restore_private_subgraphs, ) @@ -288,7 +289,7 @@ def duplicate_workflow(self, workflow_uuid: str, *, name: Optional[str]) -> Dict copied_name = name.strip() if isinstance(name, str) else f"{source['workflow']['name']} copy" if not copied_name: raise WorkflowError("invalid_input") - nodes, edges, _requirements = duplicate_graph(source) + nodes, edges, identity = duplicate_graph(source) workflow_type, category = self.operation_categories.workflow_kind(source["workflow"]["uuid"]) # type: ignore[attr-defined] record = self.create_workflow( # type: ignore[attr-defined] workflow_uuid=str(uuid4()), @@ -303,7 +304,8 @@ def duplicate_workflow(self, workflow_uuid: str, *, name: Optional[str]) -> Dict return self._save_reserved_graph( # type: ignore[attr-defined] record["uuid"], revision=record["revision"], - workflow_meta_data=dict(source["workflow"].get("meta_data", {})), + # 输出绑定、资源作用域等工作流级保留元数据也引用节点,按同一张身份表改写 + workflow_meta_data=remap_node_references(source["workflow"].get("meta_data", {}), identity), nodes=nodes, edges=edges, ) diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 4a7d3d440..73d5182a7 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -3380,7 +3380,7 @@ def import_legacy_workflow(self, *, payload: Dict[str, Any]) -> Dict[str, Any]: if not isinstance(node, dict): raise ValueError(f"nodes[{index}] 必须是对象") validate_uuid(node.get("uuid")) - new_nodes, new_edges, _requirements = duplicate_graph({"nodes": nodes, "edges": edges}) + new_nodes, new_edges, _identity = duplicate_graph({"nodes": nodes, "edges": edges}) except (KeyError, TypeError, ValueError) as exc: raise WorkflowError("invalid_input", detail=str(exc)) from None record = self.create_workflow( From bad71362822d537983f956cf8898b51bae4bed4d Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:03 +0800 Subject: [PATCH 43/59] fix(workflow): an exported composite workflow imports again Two things stopped export -> import of a composite parent: - The import re-derived the root inventory_requirements from the visible nodes and compared the whole projection. The export's requirement_key counts the private sub-graph (water becomes /water), so the echo was refused. An entry is now an echo when it is a requirement declared on its consume_node_uuid, compared on that node and meta_data.unilab.inventory. The projected fields are read-only and cannot disagree across projection rules; a hand-written or edited entry is still refused. - The export holds only the visible layer and import dropped the reserved metadata, so the invocation came back as a hollow node without its private sub-graph. Import now expands each composite invocation again from its pinned publication under the new invocation uuid and saves once. The expansion is shared with insert_composite_invocation. Export -> import -> export is now stable for composite parents with loops and carry in the child, groups, loops, conditions, disabled nodes and node_output sources. --- docs/developer_guide/api_v1_route_map.md | 2 +- .../test_workflow_export_import_roundtrip.py | 131 ++++++++++++++- ...kflow_inventory_requirements_projection.py | 20 ++- .../runtime/workflow/definition_edit.py | 37 +++-- .../services/runtime/workflow/service.py | 152 +++++++++++++++--- 5 files changed, 302 insertions(+), 40 deletions(-) diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index 6ac582b23..705fc4a25 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -207,7 +207,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | MISSING | `GET /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1664 | - | **Done (p7-a)**: | | MISSING | `PATCH /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1676 | - | **Done (p7-a)**: Only explicitly sent fields are applied. | | MISSING | `POST /api/v1/workflow-nodes/{node_uuid}/duplicate` | unilabos/app/workflow_api.py:1693 | - | **Done (p7-a)**: | -| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`; every string or key equal to an old node uuid is rewritten, so edges, `parent_uuid`, `depends_on` / `condition_guards`, condition and loop expressions, `node_output` references in params and inventory requirements and composite mappings all follow); `workflow_type` honoured; a root `inventory_requirements` list is rejected as in V1 unless it is exactly the list the graph read derives from the imported nodes (an exported graph imports again; uuids are ignored in the comparison). Was: Legacy JSON import. Used by the V1 console | +| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`; every string or key equal to an old node uuid is rewritten, so edges, `parent_uuid`, `depends_on` / `condition_guards`, condition and loop expressions, `node_output` references in params and inventory requirements and composite mappings all follow); `workflow_type` honoured; reserved `meta_data.unilab` in the file is not taken, except that each composite invocation is expanded again from its pinned publication (private sub-graph and composite metadata regenerated for the new invocation uuid); a root `inventory_requirements` list is rejected as in V1 unless every entry is a requirement declared on its `consume_node_uuid` (compared on that node and `meta_data.unilab.inventory`; the projected fields are read-only and ignored), so an exported graph imports again. Was: Legacy JSON import. Used by the V1 console | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/batch-delete` | unilabos/app/workflow_api.py:1532 | - | **Done (p7-a)**: | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/duplicate` | unilabos/app/workflow_api.py:1549 | - | **Done (p7-a)**: Copies kind/category too; node references in the graph and in the workflow's reserved metadata (output bindings, resource scopes) point at the copy's own nodes. | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/edges` | unilabos/app/workflow_api.py:1515 | (whole-graph PUT only) | **Done (p7-a)**: Returns the saved graph (201). Was: Used by the V1 console | diff --git a/tests/server/test_workflow_export_import_roundtrip.py b/tests/server/test_workflow_export_import_roundtrip.py index b1f45b41f..29d58c74b 100644 --- a/tests/server/test_workflow_export_import_roundtrip.py +++ b/tests/server/test_workflow_export_import_roundtrip.py @@ -1,4 +1,9 @@ -"""导入与复制换掉节点身份时,图里所有指向节点的引用一并改写。""" +"""导出(读图)→ 导入 → 再导出:图结构稳定,节点引用随新身份改写,组合调用的私有子图重新展开。 + +导出只含本层(组合调用的私有子图隐藏),图根 ``inventory_requirements`` 是从节点派生的只读投影; +导入换掉全部节点 / 连线身份。覆盖:组合调用父图(子操作与本层同名需求、子操作里的循环与携带)、 +分组、循环、条件分支、禁用节点、以上游结果为来源的库存需求,以及工作流复制。 +""" from __future__ import annotations @@ -66,6 +71,35 @@ def _import(client: TestClient, exported: dict[str, Any], name: str) -> str: return imported["workflow"]["uuid"] +def _canonical(client: TestClient, service: WorkflowService, workflow_uuid: str) -> dict[str, Any]: + """读图结果里的节点身份换成名字路径(私有子图节点带上所属调用节点的名字),去掉随身份变的字段。""" + + exported = _ok(client.get(f"/api/v1/workflows/{workflow_uuid}/graph")) + full = {node["uuid"]: node for node in service.get_graph(workflow_uuid)["nodes"]} + + def label(identity: str) -> str: + names, node = [], full.get(identity) + while node is not None: + names.append(node["name"]) + node = full.get(node.get("parent_uuid")) + return "<" + "/".join(reversed(names)) + ">" + + volatile = {"uuid", "create_time", "update_time", "workflow_uuid"} + payload = { + "nodes": [{key: value for key, value in node.items() if key not in volatile - {"uuid"}} for node in exported["nodes"]], + "edges": [{key: value for key, value in edge.items() if key not in volatile} for edge in exported["edges"]], + "inventory_requirements": [ + {key: value for key, value in item.items() if key not in volatile} for item in exported["inventory_requirements"] + ], + } + text = json.dumps(payload, ensure_ascii=False, sort_keys=True) + # 按长度倒序替换,``/`` 形式的 requirement_key 里的身份一并换掉 + for identity in sorted(full, key=len, reverse=True): + text = text.replace(identity, label(identity)) + canonical = json.loads(text) + return {key: sorted(items, key=lambda item: json.dumps(item, sort_keys=True)) for key, items in canonical.items()} + + def test_duplicate_graph_remaps_every_node_reference() -> None: """图里每一种指向节点的引用都换成新身份;旧身份一个不剩。""" @@ -157,6 +191,101 @@ def node(name: str, requirements: list[dict[str, Any]], depends_on: list[str]) - assert copy["inventory_requirements"][0]["meta_data"]["unilab"]["material_source_node_uuid"] == source +def test_composite_parent_with_a_shared_requirement_key_round_trips(api) -> None: + """本层与子操作都要 ``water``:导出的 key 是 ``/water``,原样导入不再被拒;私有子图按发布重新展开。""" + + client, service = api + requirement = [{"key": "water", "kind": "lot", "template_uuid": WATER, "quantity": 100.0, "unit": "ul"}] + + def node(name: str) -> dict[str, Any]: + return { + "uuid": str(uuid.uuid4()), "name": name, "type": "device_action", "material_uuid": str(uuid.uuid4()), + "action_name": "fill_well", "action_type": "UniLabJsonCommand", "param": {"slot": "T1"}, + "pose": {"x": 0, "y": 0}, "execution_policy": {"depends_on": []}, + "meta_data": {"target_device_id": "material_bench", "inventory_requirements": requirement}, + } + + child = _ok(client.post("/api/v1/workflows", json={"name": "子操作", "workflow_type": "experiment_operation"}), 201) + saved = _ok(client.put(f"/api/v1/workflows/{child['uuid']}/graph", json={ + "revision": child["revision"], "nodes": [node("子步骤")], "edges": []})) + contract = _ok(client.post(f"/api/v1/workflows/{child['uuid']}/publications", + json={"revision": saved["workflow"]["revision"]}), 201) + parent = _ok(client.post("/api/v1/workflows", json={"name": "父流程"}), 201) + saved = _ok(client.put(f"/api/v1/workflows/{parent['uuid']}/graph", json={ + "revision": parent["revision"], "nodes": [node("本层步骤")], "edges": []})) + _ok(client.post(f"/api/v1/workflows/{parent['uuid']}/composite-invocations", json={ + "revision": saved["workflow"]["revision"], "contract_uuid": contract["uuid"], "invocation_uuid": str(uuid.uuid4()), + "device_bindings": {}, "pose": {"x": 1, "y": 1}, "param": {}})) + + exported = _ok(client.get(f"/api/v1/workflows/{parent['uuid']}/graph")) + [listed] = exported["inventory_requirements"] + assert listed["requirement_key"].endswith("/water") + + copy_uuid = _import(client, exported, "父流程副本") + stored = service.get_graph(copy_uuid)["nodes"] + call = next(item for item in stored if item["type"] == "workflow") + assert call["meta_data"]["unilab"]["composite"]["child_workflow_uuid"] == child["uuid"] + assert [item["name"] for item in stored if item.get("parent_uuid") == call["uuid"]] == ["子步骤"] + assert _canonical(client, service, copy_uuid) == _canonical(client, service, parent["uuid"]) + + +def test_rich_workflow_export_import_export_is_stable(api) -> None: + """分组、循环、条件分支、禁用节点、上游结果来源与含循环携带的组合调用:再导出与原导出一致,且可再次导入。""" + + client, service = api + + @workflow(display_name="子操作") + def child(ctx): + n = 0 + while n < 2: + out = ctx.run("carry-device/add", {"value": n}, name="累加", + inventory=[{"key": "water", "kind": "lot", "template_uuid": WATER, "quantity": 100.0, "unit": "ul"}]) + n = out.value + ctx.run("carry-device/note", {"text": n}, name="记录") + + @workflow(display_name="父流程") + def parent(ctx): + first = ctx.run("carry-device/add", {"value": 1}, name="首步", + inventory=[{"key": "water", "kind": "lot", "template_uuid": WATER, "quantity": 5.0, "unit": "ul"}]) + with ctx.parallel("并行"): + ctx.run("carry-device/note", {"text": first.value}, name="并行一") + ctx.run("carry-device/note", {"text": "x"}, name="并行二", + inventory=[{"key": "tips", "kind": "material", "template_uuid": WATER}]) + for i in range(2): + ctx.run("carry-device/mark", {"index": i}, name="循环体", + inventory=[{"key": "buffer", "kind": "content", "substance_name": "PBS", "quantity": 4, "unit": "ml", + "material_uuid": first.plate}]) + if first.value > 1: + ctx.run("carry-device/note", {"text": "big"}, name="大") + else: + ctx.run("carry-device/note", {"text": "small"}, name="小") + + child_record = _store(service, "子操作") + published = service.publish_workflow(child_record["uuid"], revision=service.get_workflow(child_record["uuid"])["revision"]) + parent_record = _store(service, "父流程") + service.insert_composite_invocation( + parent_record["uuid"], revision=service.get_workflow(parent_record["uuid"])["revision"], + child_workflow_uuid=child_record["uuid"], child_revision=published["revision"], invocation_uuid=str(uuid.uuid4()), + ) + disabled = next(item for item in service.get_graph(parent_record["uuid"])["nodes"] if item["name"] == "并行二") + service.patch_workflow_node(disabled["uuid"], patch={"disabled": True}) + assert {item["type"] for item in service.get_graph(parent_record["uuid"])["nodes"]} >= { + "group", "loop", "condition", "workflow", "device_action"} + + original = _canonical(client, service, parent_record["uuid"]) + # 子操作同名的 water 计入 key;禁用节点的 tips 不列出 + assert sorted(item["requirement_key"] for item in original["inventory_requirements"]) == ["<首步>/water", "buffer"] + + exported = _ok(client.get(f"/api/v1/workflows/{parent_record['uuid']}/graph")) + first_copy = _import(client, exported, "副本一") + assert _canonical(client, service, first_copy) == original + second_copy = _import(client, _ok(client.get(f"/api/v1/workflows/{first_copy}/graph")), "副本二") + assert _canonical(client, service, second_copy) == original + # 私有子图(循环、携带)跟着新调用节点重新展开 + stored = service.get_graph(second_copy)["nodes"] + assert len(stored) == len(service.get_graph(parent_record["uuid"])["nodes"]) + + class Result(TypedDict): value: float diff --git a/tests/server/test_workflow_inventory_requirements_projection.py b/tests/server/test_workflow_inventory_requirements_projection.py index e79770641..a8a2182f8 100644 --- a/tests/server/test_workflow_inventory_requirements_projection.py +++ b/tests/server/test_workflow_inventory_requirements_projection.py @@ -196,7 +196,11 @@ def test_saved_node_requirements_come_back_in_the_v1_graph(api) -> None: def test_an_exported_graph_imports_again_and_a_handwritten_root_list_is_still_refused(api) -> None: - """读图带回派生的图根列表;原样导入时它只是回声,导入后从新节点重新派生。改过的列表不是回声,照旧拒绝。""" + """读图带回派生的图根列表;原样导入时它只是回声,导入后从新节点重新派生。 + + 回声按 (消耗节点, 节点上的需求原条目) 认:投影字段只读、改了也不生效;条目对不上节点(改了需求本身、 + 手写一条)就不是回声,照旧拒绝。 + """ client, _service = api workflow = _ok(client.post("/api/v1/workflows", json={"name": "导出", "workflow_type": "experiment_operation"}), 201) @@ -226,10 +230,16 @@ def test_an_exported_graph_imports_again_and_a_handwritten_root_list_is_still_re assert item["workflow_uuid"] == copy_uuid and item["consume_node_uuid"] == copy["nodes"][0]["uuid"] assert (item["requirement_key"], item["required_quantity"]) == ("water", 1200.0) - edited = [{**exported["inventory_requirements"][0], "required_quantity": 5.0}] - refused = client.post("/api/v1/workflows/import", json={**exported, "name": "手写", "inventory_requirements": edited}) - assert refused.status_code == 200 and refused.json()["code"] == 1000 - assert "inventory_requirements" in refused.json()["error"]["msg"] + echoed = exported["inventory_requirements"][0] + edited_inventory = {**echoed["meta_data"]["unilab"]["inventory"], "quantity": 5.0} + handwritten = {key: value for key, value in echoed.items() if key != "meta_data"} + for listed in ( + [{**echoed, "meta_data": {"unilab": {**echoed["meta_data"]["unilab"], "inventory": edited_inventory}}}], + [echoed, handwritten], + ): + refused = client.post("/api/v1/workflows/import", json={**exported, "name": "手写", "inventory_requirements": listed}) + assert refused.status_code == 200 and refused.json()["code"] == 1000 + assert "inventory_requirements" in refused.json()["error"]["msg"] def test_every_listed_requirement_key_binds_in_preflight(api) -> None: diff --git a/unilabos/server/services/runtime/workflow/definition_edit.py b/unilabos/server/services/runtime/workflow/definition_edit.py index 9ac58cafa..b7727d7ad 100644 --- a/unilabos/server/services/runtime/workflow/definition_edit.py +++ b/unilabos/server/services/runtime/workflow/definition_edit.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import math from collections import Counter from copy import deepcopy @@ -417,20 +418,38 @@ def project_inventory_requirements(graph: Mapping[str, Any]) -> list[dict[str, A return projected +def _canonical(value: Any) -> str: + return json.dumps(value, sort_keys=True, ensure_ascii=False) + + def is_derived_inventory_requirements(graph: Mapping[str, Any], requirements: Any) -> bool: - """图根 ``inventory_requirements`` 是不是读图时从节点派生的那份(导出后原样导入的回声)。 + """图根 ``inventory_requirements`` 是不是读图时从节点派生的列表(导出后原样导入的回声)。 - 比较时不看 ``uuid`` / ``workflow_uuid``:它们按工作流身份生成,导入会换身份。别的任何不同 - (改了数量、多一条、手写一条)都不是回声。 + 派生列表的每一条都是某个节点上声明的需求原条目(``consume_node_uuid`` + ``meta_data.unilab.inventory``), + 只按这一对比较:``requirement_key``、数量、``deferred`` 等投影字段随投影规则(可见性、禁用、重名、 + 规范化)变化,导入时重新派生会和导出时对不上。对不上任何节点条目(手写、改了需求本身)就不是回声。 + 投影字段只读,改了也不生效。 """ - if not isinstance(requirements, list) or not all(isinstance(item, Mapping) for item in requirements): + if not isinstance(requirements, list): return False - - def essence(items: list[Mapping[str, Any]]) -> list[dict[str, Any]]: - return [{key: value for key, value in item.items() if key not in ("uuid", "workflow_uuid")} for item in items] - - return essence(requirements) == essence(project_inventory_requirements(graph)) + declared = { + (str(node.get("uuid") or ""), _canonical(item)) + for node in graph.get("nodes") or [] + if isinstance(node, Mapping) + for item in _declared_inventory(node) + } + for item in requirements: + if not isinstance(item, Mapping): + return False + meta = item.get("meta_data") + unilab = meta.get("unilab") if isinstance(meta, Mapping) else None + inventory = unilab.get("inventory") if isinstance(unilab, Mapping) else None + if not isinstance(inventory, Mapping): + return False + if (str(item.get("consume_node_uuid") or ""), _canonical(inventory)) not in declared: + return False + return True def definition_graph(graph: Mapping[str, Any]) -> dict[str, Any]: diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 73d5182a7..4ea1aa00d 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -64,6 +64,7 @@ ) from unilabos.server.services.runtime.workflow.composite_expansion import ( CompositeAuthoring, + CompositeExpansion, ) from unilabos.server.services.runtime.workflow.entry_parameters import ( EntryParameterError, @@ -1119,31 +1120,15 @@ def insert_composite_invocation( graph = WorkflowStore.get_graph(self, parent) if graph["workflow"]["revision"] != revision: raise WorkflowConflict("conflict") - selected = self.find_workflow_publication(child, child_revision) - if selected is None: - raise WorkflowError("not_found", detail="子工作流没有该发布修订") - try: - authoring, projection = self._composite_authoring(selected) - except PublicationError as exc: - raise WorkflowError("invalid_input", detail=str(exc)) from None parent_unilab = graph["workflow"]["meta_data"].get("unilab") or {} - expansion = authoring.compile_invocation( - parent_workflow_uuid=parent, - invocation_uuid=invocation, - module=PUBLICATION_MODULE, - symbol=projection.source.symbol, - keyword_arguments=arguments, - parent_input_contract=( - parent_unilab.get("input_contract") - or {"version": 1, "parameters": []} - ), + selected, expansion = self._compile_composite_invocation( + parent, + invocation=invocation, + child=child, + child_revision=child_revision, + arguments=arguments, + parent_input_contract=parent_unilab.get("input_contract"), ) - if expansion.diagnostics: - diagnostic = expansion.diagnostics[0] - raise WorkflowError( - "invalid_input", - detail=f"{diagnostic['code']}({diagnostic['path']})", - ) nodes, edges, templates, handles = merged_invocation_entities( expansion, name=selected["name"], @@ -1181,6 +1166,41 @@ def insert_composite_invocation( "graph": saved, } + def _compile_composite_invocation( + self, + parent: str, + *, + invocation: str, + child: str, + child_revision: Optional[int], + arguments: Dict[str, Any], + parent_input_contract: Optional[Dict[str, Any]], + ) -> Tuple[Dict[str, Any], CompositeExpansion]: + """按子工作流的一次发布展开一次组合调用,返回 ``(发布行, 展开结果)``;展开失败映射成 WorkflowError。""" + + selected = self.find_workflow_publication(child, child_revision) + if selected is None: + raise WorkflowError("not_found", detail="子工作流没有该发布修订") + try: + authoring, projection = self._composite_authoring(selected) + except PublicationError as exc: + raise WorkflowError("invalid_input", detail=str(exc)) from None + expansion = authoring.compile_invocation( + parent_workflow_uuid=parent, + invocation_uuid=invocation, + module=PUBLICATION_MODULE, + symbol=projection.source.symbol, + keyword_arguments=arguments, + parent_input_contract=parent_input_contract or {"version": 1, "parameters": []}, + ) + if expansion.diagnostics: + diagnostic = expansion.diagnostics[0] + raise WorkflowError( + "invalid_input", + detail=f"{diagnostic['code']}({diagnostic['path']})", + ) + return selected, expansion + # V1 发布合同 / 组合调用 ------------------------------------------------ def publication_contract(self, row: Dict[str, Any]) -> Dict[str, Any]: @@ -3391,12 +3411,96 @@ def import_legacy_workflow(self, *, payload: Dict[str, Any]) -> Dict[str, Any]: workflow_type=str(definition.get("workflow_type") or "normal"), ) try: - return self.save_graph(record["uuid"], revision=record["revision"], nodes=new_nodes, edges=new_edges) + return self._save_imported_graph(record, new_nodes, new_edges) except BaseException: with suppress(Exception): self.delete_workflow(record["uuid"]) raise + def _save_imported_graph( + self, + record: Dict[str, Any], + nodes: List[Dict[str, Any]], + edges: List[Dict[str, Any]], + ) -> Dict[str, Any]: + """导入的本层图落库:组合调用按固定的发布修订重新展开私有子图,再整图保存一次。 + + 与整图保存同一规则,文件里的保留元数据(``meta_data.unilab``)一律不采用;组合调用的保留元数据 + 与私有子图都由展开重新生成,身份按新的调用节点派生。 + """ + + from unilabos.server.scheduler.interval_plan import ( + graph_declares_resource_scopes, validate_graph_resource_scopes, + ) + + identity = record["uuid"] + for edge in edges: + if isinstance(edge.get("meta_data"), dict): + edge["meta_data"].pop("unilab", None) + pins: Dict[str, Mapping[str, Any]] = {} + for node in nodes: + meta_data = node.get("meta_data") + unilab = meta_data.pop("unilab", None) if isinstance(meta_data, dict) else None + if isinstance(unilab, Mapping) and isinstance(unilab.get("composite"), Mapping): + pins[node["uuid"]] = unilab["composite"] + if any(node.get("workflow_node_template_uuid") for node in nodes): + # 引用设备动作模板的节点:先把注册表投影同步进模板表,图校验才能找到模板 + self._sync_registry_templates_best_effort() + private_nodes: List[Dict[str, Any]] = [] + private_edges: List[Dict[str, Any]] = [] + templates: Dict[str, Dict[str, Any]] = {} + handles: Dict[str, Dict[str, Any]] = {} + with self._authoring_lock(identity): + for node in nodes: + pin = pins.get(node["uuid"]) + if pin is None: + continue + child_revision = pin.get("child_workflow_revision") + try: + child = validate_uuid(pin.get("child_workflow_uuid")) + if isinstance(child_revision, bool) or not isinstance(child_revision, int): + raise ValueError + except (TypeError, ValueError): + raise WorkflowError("invalid_input", detail=f"组合调用 {node['uuid']} 缺少子工作流发布修订") from None + # 与新插入同一规则:子工作流已删除时不能再引用它 + self.get_workflow(child) + _selected, expansion = self._compile_composite_invocation( + identity, + invocation=node["uuid"], + child=child, + child_revision=child_revision, + arguments=node.get("param") or {}, + parent_input_contract=None, + ) + expanded, expanded_edges, node_templates, handle_templates = merged_invocation_entities( + expansion, name=str(node.get("name") or ""), pose=node.get("pose"), + ) + invocation, *inner = expanded + # 本层字段(名称、位置、分组、依赖、禁用等)以文件为准;实参、模板与保留元数据取展开结果 + node["param"] = invocation["param"] + node["workflow_node_template_uuid"] = invocation["workflow_node_template_uuid"] + node["meta_data"] = {**(node.get("meta_data") or {}), "unilab": invocation["meta_data"]["unilab"]} + private_nodes.extend(inner) + private_edges.extend(expanded_edges) + templates.update((item["uuid"], item) for item in node_templates) + handles.update((item["uuid"], item) for item in handle_templates) + saved = self._save_reserved_graph( + identity, + revision=record["revision"], + workflow_meta_data=record["meta_data"], + nodes=[*nodes, *private_nodes], + edges=[*edges, *private_edges], + node_templates=list(templates.values()), + handle_templates=list(handles.values()), + ) + if graph_declares_resource_scopes(saved): + # 子操作带来的资源作用域要能在新父图里规划(与插入组合调用同一校验) + try: + validate_graph_resource_scopes(saved) + except (ValueError, TypeError) as exc: + raise WorkflowError("invalid_input", detail=str(exc)) from None + return saved + def _read_source( self, registration: Dict[str, Any], From 1eb793e90bea252988a151636aaf6fbbad9486d9 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:41:40 +0800 Subject: [PATCH 44/59] fix(workflow): import keeps the declared I/O, resource scopes and bindings Import dropped all reserved metadata, so a workflow whose nodes use a declared input could not be imported again ("references an undeclared input"), and output bindings, resource scopes, node input bindings and authoring order silently disappeared. The request model also discarded the exported workflow object. Import now takes the author's declarations from the exported workflow.meta_data.unilab (input/output contract, output_bindings, resource_scopes) and each node's input_bindings and authoring_source_order. Node references are rewritten to the new ids, then the save path's validators run: the input contract against the nodes that use it, output bindings and scopes against existing nodes, and the normalized contract is stored. A failure is refused with 1000 naming the item. Composite invocations compile against the imported input contract. Other reserved metadata, such as source registration, is still not taken. --- docs/developer_guide/api_v1_route_map.md | 2 +- .../test_workflow_export_import_roundtrip.py | 83 +++++++++++- .../server/api/runtime/workflow_definition.py | 2 + .../services/runtime/workflow/service.py | 123 +++++++++++++++--- 4 files changed, 185 insertions(+), 25 deletions(-) diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index 705fc4a25..3ae96c1f3 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -207,7 +207,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | MISSING | `GET /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1664 | - | **Done (p7-a)**: | | MISSING | `PATCH /api/v1/workflow-nodes/{node_uuid}` | unilabos/app/workflow_api.py:1676 | - | **Done (p7-a)**: Only explicitly sent fields are applied. | | MISSING | `POST /api/v1/workflow-nodes/{node_uuid}/duplicate` | unilabos/app/workflow_api.py:1693 | - | **Done (p7-a)**: | -| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`; every string or key equal to an old node uuid is rewritten, so edges, `parent_uuid`, `depends_on` / `condition_guards`, condition and loop expressions, `node_output` references in params and inventory requirements and composite mappings all follow); `workflow_type` honoured; reserved `meta_data.unilab` in the file is not taken, except that each composite invocation is expanded again from its pinned publication (private sub-graph and composite metadata regenerated for the new invocation uuid); a root `inventory_requirements` list is rejected as in V1 unless every entry is a requirement declared on its `consume_node_uuid` (compared on that node and `meta_data.unilab.inventory`; the projected fields are read-only and ignored), so an exported graph imports again. Was: Legacy JSON import. Used by the V1 console | +| MISSING | `POST /api/v1/workflows/import` | unilabos/app/workflow_api.py:1183 | (different) POST /api/v1/workflows/from-template | **Done (p7-a)**: Legacy JSON (direct or `data`-wrapped) with node/edge identities rebuilt (ported V1 `duplicate_graph`; every string or key equal to an old node uuid is rewritten, so edges, `parent_uuid`, `depends_on` / `condition_guards`, condition and loop expressions, `node_output` references in params and inventory requirements and composite mappings all follow); `workflow_type` honoured; of the reserved `meta_data.unilab` in the file only the author's declarations are taken, never verbatim: the exported `workflow.meta_data.unilab` I/O contract (`input_contract` / `output_contract` / `output_bindings`) and `resource_scopes`, and each node's `input_bindings` and `authoring_source_order`, with node references rewritten to the new uuids and then checked by the same validators as a save (parameters match the nodes that use them, output bindings and scopes reference existing nodes; the normalized contract is stored), a failure refused with 1000 naming the item; each composite invocation is expanded again from its pinned publication (private sub-graph and composite metadata regenerated for the new invocation uuid); other reserved metadata (source registration) is not taken; a root `inventory_requirements` list is rejected as in V1 unless every entry is a requirement declared on its `consume_node_uuid` (compared on that node and `meta_data.unilab.inventory`; the projected fields are read-only and ignored), so an exported graph imports again. Was: Legacy JSON import. Used by the V1 console | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/batch-delete` | unilabos/app/workflow_api.py:1532 | - | **Done (p7-a)**: | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/duplicate` | unilabos/app/workflow_api.py:1549 | - | **Done (p7-a)**: Copies kind/category too; node references in the graph and in the workflow's reserved metadata (output bindings, resource scopes) point at the copy's own nodes. | | MISSING | `POST /api/v1/workflows/{workflow_uuid}/edges` | unilabos/app/workflow_api.py:1515 | (whole-graph PUT only) | **Done (p7-a)**: Returns the saved graph (201). Was: Used by the V1 console | diff --git a/tests/server/test_workflow_export_import_roundtrip.py b/tests/server/test_workflow_export_import_roundtrip.py index 29d58c74b..b6b7607ec 100644 --- a/tests/server/test_workflow_export_import_roundtrip.py +++ b/tests/server/test_workflow_export_import_roundtrip.py @@ -2,11 +2,13 @@ 导出只含本层(组合调用的私有子图隐藏),图根 ``inventory_requirements`` 是从节点派生的只读投影; 导入换掉全部节点 / 连线身份。覆盖:组合调用父图(子操作与本层同名需求、子操作里的循环与携带)、 -分组、循环、条件分支、禁用节点、以上游结果为来源的库存需求,以及工作流复制。 +分组、循环、条件分支、禁用节点、以上游结果为来源的库存需求、作者声明的 I/O 合同、节点输入绑定、 +资源作用域与创作顺序,以及工作流复制。 """ from __future__ import annotations +import copy import json import uuid from typing import Any, TypedDict @@ -26,8 +28,15 @@ from unilabos.server.api.runtime.workflow import create_workflow_app from unilabos.server.services.runtime.workflow.definition_edit import duplicate_graph from unilabos.server.services.runtime.workflow.service import WorkflowService +from tests.server.test_workflow_publication import ( + DEVICE_TEMPLATE, + NUMBER, + VOLUME_SOURCE, + VOLUME_TARGET, + _install_device_template, +) -WATER = "33333333-3333-4333-8333-333333333333" +WATER ="33333333-3333-4333-8333-333333333333" DEVICE = "44444444-4444-4444-8444-444444444444" @@ -86,7 +95,8 @@ def label(identity: str) -> str: volatile = {"uuid", "create_time", "update_time", "workflow_uuid"} payload = { - "nodes": [{key: value for key, value in node.items() if key not in volatile - {"uuid"}} for node in exported["nodes"]], + "workflow_unilab": [exported["workflow"]["meta_data"].get("unilab") or {}], + "nodes":[{key: value for key, value in node.items() if key not in volatile - {"uuid"}} for node in exported["nodes"]], "edges": [{key: value for key, value in edge.items() if key not in volatile} for edge in exported["edges"]], "inventory_requirements": [ {key: value for key, value in item.items() if key not in volatile} for item in exported["inventory_requirements"] @@ -286,6 +296,73 @@ def parent(ctx): assert len(stored) == len(service.get_graph(parent_record["uuid"])["nodes"]) +def test_declared_io_and_resource_scopes_round_trip_and_are_validated(api) -> None: + """入口参数、输出绑定、节点输入绑定、资源作用域与创作顺序随导入保留,节点引用换成新身份。 + + 以前导入丢掉工作流的保留元数据:引用入口参数的节点被拒(1000),其余声明悄悄消失。文件内容不原样 + 信任:输出绑定、作用域指向不存在的节点,或节点引用了没声明的入口参数,整次导入失败并指明哪一项。 + """ + + client, service = api + _install_device_template(service) + record = _ok(client.post("/api/v1/workflows", json={"name": "带接口"}), 201) + path = f"/api/v1/workflows/{record['uuid']}" + for name in ("加样一", "加样二"): + _ok(client.post(f"{path}/nodes", json={ + "workflow_node_template_uuid": DEVICE_TEMPLATE, "name": name, "param": {"volume": 1}, + "material_uuid": DEVICE, "meta_data": {"target_device_id": "pump-1"}, + }), 201) + graph = _ok(client.get(f"{path}/graph")) + first, second = (next(node["uuid"] for node in graph["nodes"] if node["name"] == name) for name in ("加样一", "加样二")) + declared = _ok(client.put(f"{path}/io", json={ + "revision": graph["workflow"]["revision"], + "input_contract": {"version": 1, "parameters": [{"name": "volume", "schema": NUMBER, "required": True}]}, + "output_contract": {"version": 1, "outputs": [{"name": "dosed", "schema": NUMBER}]}, + "output_bindings": {"dosed": {"kind": "node_output", "workflow_node_uuid": second, "source_handle_uuid": VOLUME_SOURCE}}, + "node_input_bindings": {first: {VOLUME_TARGET: {"parameter": "volume"}}}, + "node_params": {second: {"volume": {"kind": "workflow_input", "parameter": "volume"}}}, + })) + _ok(client.put(f"{path}/resource-scopes", json={"revision": declared["workflow"]["revision"], "scopes": [ + {"scope_id": "锁", "kind": "with", "resources": ["pump-1"], "node_uuids": [first, second]}, + ]})) + + original = _canonical(client, service, record["uuid"]) + [unilab] = original["workflow_unilab"] + assert unilab["output_bindings"]["dosed"]["workflow_node_uuid"] == "<加样二>" + assert unilab["resource_scopes"][0]["node_uuids"] == ["<加样一>", "<加样二>"] + by_name = {node["name"]: node for node in original["nodes"]} + assert by_name["加样一"]["meta_data"]["unilab"] == { + "authoring_source_order": 0, "input_bindings": {VOLUME_TARGET: {"parameter": "volume"}}} + assert by_name["加样二"]["param"]["volume"] == {"kind": "workflow_input", "parameter": "volume"} + + exported = _ok(client.get(f"{path}/graph")) + first_copy = _import(client, exported, "带接口副本") + assert _canonical(client, service, first_copy) == original + second_copy = _import(client, _ok(client.get(f"/api/v1/workflows/{first_copy}/graph")), "带接口副本二") + assert _canonical(client, service, second_copy) == original + + def tampered(change) -> dict[str, Any]: + payload = copy.deepcopy(exported) + change(payload["workflow"]["meta_data"]["unilab"]) + return payload + + # 合法但未规范化的合同按保存路径落库规范化后的形状 + loose = tampered(lambda meta: meta["output_contract"]["outputs"][0].pop("implicit")) + normalized_copy = _import(client, loose, "未规范化") + assert _canonical(client, service, normalized_copy) == original + + before = service.list_workflows()["total"] + for payload, item in ( + (tampered(lambda meta: meta["output_bindings"]["dosed"].update(workflow_node_uuid=str(uuid.uuid4()))), + "output_bindings"), + (tampered(lambda meta: meta["resource_scopes"][0]["node_uuids"].append(str(uuid.uuid4()))), "resource_scopes"), + (tampered(lambda meta: meta.pop("input_contract")), "input_binding"), + ): + refused = client.post("/api/v1/workflows/import", json={**payload, "name": "坏文件"}).json() + assert refused["code"] == 1000 and item in refused["error"]["msg"], refused + assert service.list_workflows()["total"] == before + + class Result(TypedDict): value: float diff --git a/unilabos/server/api/runtime/workflow_definition.py b/unilabos/server/api/runtime/workflow_definition.py index a4a6e84a6..a415a1b8c 100644 --- a/unilabos/server/api/runtime/workflow_definition.py +++ b/unilabos/server/api/runtime/workflow_definition.py @@ -148,6 +148,8 @@ class LegacyWorkflowImportRequest(_BackendModel): nodes: List[Dict[str, Any]] = Field(default_factory=list) edges: List[Dict[str, Any]] = Field(default_factory=list) inventory_requirements: List[Dict[str, Any]] = Field(default_factory=list) + #: 导出(读图)的工作流对象;其 ``meta_data.unilab`` 里的 I/O 合同与资源作用域经校验后随图导入 + workflow: Optional[Dict[str, Any]] = None data: Optional[Dict[str, Any]] = None diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 4ea1aa00d..0bab6525e 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -90,7 +90,10 @@ publication_source_hash, publication_summary, ) -from unilabos.server.services.runtime.workflow.definition_edit import node_or_ancestor_disabled +from unilabos.server.services.runtime.workflow.definition_edit import ( + node_or_ancestor_disabled, + remap_node_references, +) from unilabos.server.services.runtime.workflow.definition_service import WorkflowDefinitionEditing from unilabos.server.services.runtime.workflow.node_templates import NodeTemplateCatalog from unilabos.server.services.runtime.workflow.operation_category import ( @@ -102,6 +105,7 @@ ) from unilabos.server.services.runtime.workflow.workflow_io import ( WorkflowIOValidationError, + normalize_input_contract, validate_workflow_graph_io, ) from unilabos.server.database.sqlite_domain import DomainDatabase @@ -3400,9 +3404,13 @@ def import_legacy_workflow(self, *, payload: Dict[str, Any]) -> Dict[str, Any]: if not isinstance(node, dict): raise ValueError(f"nodes[{index}] 必须是对象") validate_uuid(node.get("uuid")) - new_nodes, new_edges, _identity = duplicate_graph({"nodes": nodes, "edges": edges}) + new_nodes, new_edges, node_identity = duplicate_graph({"nodes": nodes, "edges": edges}) except (KeyError, TypeError, ValueError) as exc: raise WorkflowError("invalid_input", detail=str(exc)) from None + # 导出(读图)的工作流级保留元数据在 workflow.meta_data.unilab:I/O 合同与资源作用域随图导入 + source_workflow = definition.get("workflow") + source_meta = source_workflow.get("meta_data") if isinstance(source_workflow, Mapping) else None + workflow_unilab = source_meta.get("unilab") if isinstance(source_meta, Mapping) else None record = self.create_workflow( name=name, tags=list(definition.get("tags") or []), @@ -3411,7 +3419,13 @@ def import_legacy_workflow(self, *, payload: Dict[str, Any]) -> Dict[str, Any]: workflow_type=str(definition.get("workflow_type") or "normal"), ) try: - return self._save_imported_graph(record, new_nodes, new_edges) + return self._save_imported_graph( + record, + new_nodes, + new_edges, + workflow_unilab=workflow_unilab if isinstance(workflow_unilab, Mapping) else {}, + node_identity=node_identity, + ) except BaseException: with suppress(Exception): self.delete_workflow(record["uuid"]) @@ -3422,26 +3436,70 @@ def _save_imported_graph( record: Dict[str, Any], nodes: List[Dict[str, Any]], edges: List[Dict[str, Any]], + *, + workflow_unilab: Mapping[str, Any], + node_identity: Mapping[str, str], ) -> Dict[str, Any]: - """导入的本层图落库:组合调用按固定的发布修订重新展开私有子图,再整图保存一次。 + """导入的本层图落库:保留作者声明的保留元数据,组合调用按固定的发布修订重新展开,再整图保存。 + + 文件里的保留元数据(``meta_data.unilab``)只采用作者声明的部分,且不原样信任: - 与整图保存同一规则,文件里的保留元数据(``meta_data.unilab``)一律不采用;组合调用的保留元数据 - 与私有子图都由展开重新生成,身份按新的调用节点派生。 + - 工作流的 I/O 合同(``input_contract`` / ``output_contract`` / ``output_bindings``)与 + ``resource_scopes``:节点引用按新身份改写,再走保存路径同一套校验(入口参数与节点引用一致、 + 输出绑定与作用域只引用存在的节点),落库规范化后的合同; + - 节点的 ``input_bindings`` 与 ``authoring_source_order``:随 I/O 合同一起校验; + - 组合调用的保留元数据与私有子图由展开重新生成,身份按新的调用节点派生。 + + 其余保留元数据(源码登记等)不采用。校验不过整次导入失败,错误指明是哪一项。 """ + from unilabos.protocol.runtime.resource_intervals import WorkflowResourceScopesRequest from unilabos.server.scheduler.interval_plan import ( graph_declares_resource_scopes, validate_graph_resource_scopes, ) - identity = record["uuid"] + def io_invalid(exc: WorkflowIOValidationError) -> WorkflowError: + return WorkflowError("invalid_input", detail=f"工作流 I/O 无效:{exc.code}({exc.path})") + + workflow_uuid = record["uuid"] + io_keys = ("input_contract", "output_contract", "output_bindings") + declared = remap_node_references( + {key: workflow_unilab[key] for key in (*io_keys, "resource_scopes") if key in workflow_unilab}, + node_identity, + ) + if "resource_scopes" in declared: + try: + checked_scopes = WorkflowResourceScopesRequest(revision=record["revision"], scopes=declared["resource_scopes"]) + except ValidationError as exc: + error = exc.errors(include_input=False, include_url=False)[0] + location = ".".join(map(str, error["loc"])) + raise WorkflowError("invalid_input", detail=f"resource_scopes 无效:{location}: {error['msg']}") from None + declared["resource_scopes"] = [scope.model_dump(exclude_none=True) for scope in checked_scopes.scopes] + try: + parent_input_contract = normalize_input_contract(declared.get("input_contract")) + except WorkflowIOValidationError as exc: + raise io_invalid(exc) from None + workflow_meta = {**record["meta_data"], "unilab": declared} if declared else record["meta_data"] + for edge in edges: if isinstance(edge.get("meta_data"), dict): edge["meta_data"].pop("unilab", None) pins: Dict[str, Mapping[str, Any]] = {} + has_input_bindings = False for node in nodes: meta_data = node.get("meta_data") unilab = meta_data.pop("unilab", None) if isinstance(meta_data, dict) else None - if isinstance(unilab, Mapping) and isinstance(unilab.get("composite"), Mapping): + if not isinstance(unilab, Mapping): + continue + kept = {key: unilab[key] for key in ("input_bindings", "authoring_source_order") if key in unilab} + if "authoring_source_order" in kept and type(kept["authoring_source_order"]) is not int: + raise WorkflowError( + "invalid_input", detail=f"节点 {node.get('name') or node['uuid']} 的 authoring_source_order 必须是整数", + ) + if kept: + meta_data["unilab"] = kept + has_input_bindings = has_input_bindings or "input_bindings" in kept + if isinstance(unilab.get("composite"), Mapping): pins[node["uuid"]] = unilab["composite"] if any(node.get("workflow_node_template_uuid") for node in nodes): # 引用设备动作模板的节点:先把注册表投影同步进模板表,图校验才能找到模板 @@ -3450,7 +3508,7 @@ def _save_imported_graph( private_edges: List[Dict[str, Any]] = [] templates: Dict[str, Dict[str, Any]] = {} handles: Dict[str, Dict[str, Any]] = {} - with self._authoring_lock(identity): + with self._authoring_lock(workflow_uuid): for node in nodes: pin = pins.get(node["uuid"]) if pin is None: @@ -3465,40 +3523,63 @@ def _save_imported_graph( # 与新插入同一规则:子工作流已删除时不能再引用它 self.get_workflow(child) _selected, expansion = self._compile_composite_invocation( - identity, + workflow_uuid, invocation=node["uuid"], child=child, child_revision=child_revision, arguments=node.get("param") or {}, - parent_input_contract=None, + parent_input_contract=parent_input_contract, ) expanded, expanded_edges, node_templates, handle_templates = merged_invocation_entities( expansion, name=str(node.get("name") or ""), pose=node.get("pose"), ) invocation, *inner = expanded - # 本层字段(名称、位置、分组、依赖、禁用等)以文件为准;实参、模板与保留元数据取展开结果 + # 本层字段(名称、位置、分组、依赖、禁用等)以文件为准;实参、模板与组合调用元数据取展开结果 node["param"] = invocation["param"] node["workflow_node_template_uuid"] = invocation["workflow_node_template_uuid"] - node["meta_data"] = {**(node.get("meta_data") or {}), "unilab": invocation["meta_data"]["unilab"]} + meta_data = node.get("meta_data") or {} + node["meta_data"] = { + **meta_data, "unilab": {**(meta_data.get("unilab") or {}), **invocation["meta_data"]["unilab"]}, + } private_nodes.extend(inner) private_edges.extend(expanded_edges) templates.update((item["uuid"], item) for item in node_templates) handles.update((item["uuid"], item) for item in handle_templates) + # 节点引用的入口参数按 workflow_meta 里的输入合同校验(与整图保存同一校验器) saved = self._save_reserved_graph( - identity, + workflow_uuid, revision=record["revision"], - workflow_meta_data=record["meta_data"], + workflow_meta_data=workflow_meta, nodes=[*nodes, *private_nodes], edges=[*edges, *private_edges], node_templates=list(templates.values()), handle_templates=list(handles.values()), ) - if graph_declares_resource_scopes(saved): - # 子操作带来的资源作用域要能在新父图里规划(与插入组合调用同一校验) - try: - validate_graph_resource_scopes(saved) - except (ValueError, TypeError) as exc: - raise WorkflowError("invalid_input", detail=str(exc)) from None + if graph_declares_resource_scopes(saved): + # 作用域只能引用图里存在的节点;子操作带来的作用域要能在新父图里规划 + try: + validate_graph_resource_scopes(saved) + except (ValueError, TypeError) as exc: + raise WorkflowError("invalid_input", detail=f"resource_scopes 无效:{exc}") from None + if has_input_bindings or any(key in declared for key in io_keys): + # 输入绑定、输出绑定与合同一致,输出绑定只引用存在的节点;落库规范化后的合同(与保存路径一致) + try: + checked = validate_workflow_graph_io(saved) + except WorkflowIOValidationError as exc: + raise io_invalid(exc) from None + normalized = { + "input_contract": checked.input_contract.to_dict(), + "output_contract": checked.output_contract.to_dict(), + "output_bindings": {name: dict(binding) for name, binding in checked.output_bindings.items()}, + } + if any(declared.get(key) != value for key, value in normalized.items()): + saved = self._save_reserved_graph( + workflow_uuid, + revision=saved["workflow"]["revision"], + workflow_meta_data={**record["meta_data"], "unilab": {**declared, **normalized}}, + nodes=saved["nodes"], + edges=saved["edges"], + ) return saved def _read_source( From 83fe4e63a065f6ebf271208814e432fb2c372dff Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:41:40 +0800 Subject: [PATCH 45/59] docs: the requirement list shows this layer, keys are unique across the plan State the rule plainly in the route map: the graph's inventory_requirements lists only this layer, while requirement_key is unique across the whole execution plan because bindings and preflight resolve keys against it. The V1 file index still said the graph list was always empty and that inventory_bindings took no part in reservation. --- docs/developer_guide/api_v1_route_map.md | 2 +- docs/developer_guide/v1_file_index/app.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index 3ae96c1f3..06b2d775d 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -220,7 +220,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | DTO-DIFF | `PUT /api/v1/workflows/{workflow_uuid}` | unilabos/app/workflow_api.py:1420 | PUT /api/v1/workflows/{workflow_uuid} | **Done (p7-a)**: Type cannot change (1000); category omitted keeps, null clears. Was: Same as POST /workflows | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/authoring/apply` | unilabos/app/workflow_api.py:2218 | POST /api/v1/workflows/{workflow_uuid}/authoring/apply | **Done (p7-a)**: Body `{candidate_hash}` only; draft hash and base revision are derived from the stored candidate (`WorkflowService.apply_authoring_by_candidate`). The triple-CAS body is rejected (1000). Was: V1 {candidate_hash} vs DEV {expected_draft_hash, expected_workflow_revision, expected_candidate_hash}. Both strict | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/composite-invocations` | unilabos/app/workflow_api.py:1597 | POST /api/v1/workflows/{workflow_uuid}/composite-invocations | **Done (p7-a)**: V1 body `{revision, contract_uuid, invocation_uuid, device_bindings, pose, param}`; child = the contract's workflow, child revision = the contract's revision; child must be an experiment operation (1000) whose current revision is published (3003); dev publications have no executor requirements, so `device_bindings` must be `{}`. Returns the parent graph (current layer), HTTP 200. Dev body removed. Was: V1 {revision, contract_uuid, invocation_uuid, device_bindings, pose, param} vs DEV {revision, child_workflow_uuid, child_revision, invocation_uuid, pose, arguments}. Both strict, so each rejects the other's body. V1 returns 200, DEV 201 | -| DTO-DIFF | `GET /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1449 | GET /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `workflow` gains `status`/`workflow_type`/`operation_category_uuid`; current layer only (V1 `definition_graph`); `inventory_requirements` is derived on every read from the nodes' `meta_data.inventory_requirements` (the single source; quantities normalized as the scheduler reads them; content→current_substance, lot→lot with allow_split, material→material 1 件; disabled nodes and their descendants and composite private sub-graphs are not listed; a key used by several nodes of the execution plan, private sub-graphs included, becomes `/`, the form task bindings accept; the original entry is in `meta_data.unilab.inventory`). Was: V1 returns {workflow(+status, category), nodes, edges, inventory_requirements} for the current layer only. DEV returns {workflow, nodes, edges, node_templates, handle_templates} | +| DTO-DIFF | `GET /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1449 | GET /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `workflow` gains `status`/`workflow_type`/`operation_category_uuid`; current layer only (V1 `definition_graph`); `inventory_requirements` is derived on every read from the nodes' `meta_data.inventory_requirements` (the single source; quantities normalized as the scheduler reads them; content→current_substance, lot→lot with allow_split, material→material 1 件; the list shows only this layer: disabled nodes and their descendants and composite private sub-graphs are not listed; `requirement_key` is unique across the whole execution plan, private sub-graphs included, because task `inventory_bindings` and preflight resolve keys against the plan: a key used by several plan nodes becomes `/` even when only one of them is listed; the original entry is in `meta_data.unilab.inventory`). Was: V1 returns {workflow(+status, category), nodes, edges, inventory_requirements} for the current layer only. DEV returns {workflow, nodes, edges, node_templates, handle_templates} | | DTO-DIFF | `PUT /api/v1/workflows/{workflow_uuid}/graph` | unilabos/app/workflow_api.py:1461 | PUT /api/v1/workflows/{workflow_uuid}/graph | **Done (p7-a)**: `site_binding_mode` defaults to `preserve` (V1 plain save); programmatic import (`client/runtime/workflow.py`, from-template) sends `resolve` explicitly. `node.manual_confirmation` persisted (runtime.db column). Composite private sub-graphs are restored when the client sends the current layer only. Was: DEV defaults site_binding_mode to 'resolve' (its own doc says browsers must send 'preserve'), so a V1 client's save can fail with site_binding_invalid. DEV also drops node.manual_confirmation | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/publications` | unilabos/app/workflow_api.py:1563 | POST /api/v1/workflows/{workflow_uuid}/publications | **Done (p7-a)**: Returns the V1 contract (`uuid` = contract_uuid, `workflow_revision`, `version`, `input_contract`, `output_contract`, `executor_requirements: []`, `node_template_uuid`, `node_count`, `edge_count`, `revision_fingerprint`) plus dev's palette fields (`revision`, `inputs`, `outputs`, `node_template`, `handle_templates`). Was: Request is the same ({revision}). V1 returns a public contract whose contract_uuid feeds composite-invocations; DEV returns a publication record. Field-level diff UNVERIFIED | | DTO-DIFF | `POST /api/v1/workflows/{workflow_uuid}/run-preflight` | unilabos/app/workflow_api.py:1639 | POST /api/v1/workflows/{workflow_uuid}/run-preflight | **Done (p7-a)**: V1 body (`run_mode` string, `inventory_bindings` V1 DTO, extra fields ignored); bindings are applied to the candidate plan like task creation (an unmatched binding is an `invalid_inventory_binding` check, the inventory check reports against the bound source) and echoed in the report. `Cache-Control: no-store`. Was: F02. DEV is strict, forbids inventory_bindings and restricts run_mode to a Literal | diff --git a/docs/developer_guide/v1_file_index/app.md b/docs/developer_guide/v1_file_index/app.md index ec90ddab9..a6a923779 100644 --- a/docs/developer_guide/v1_file_index/app.md +++ b/docs/developer_guide/v1_file_index/app.md @@ -81,7 +81,7 @@ MISSING:`app/cli/lab.py`。 | unilabos/app/web/utils/device_utils.py | 59 | DROPPED | 只服务 V1-DEPRECATED 的状态页 / `/ws/status_page`(route map) | | | unilabos/app/web/utils/host_utils.py | 67 | DROPPED | 同上(`/ws/device_status`、状态页) | | | unilabos/app/web/utils/ros_utils.py | 74 | DROPPED | 同上 | | -| unilabos/app/workflow_api.py | 2465 | PARTIAL | `server/api/runtime/workflow.py`、`workflow_definition.py`、`tasks_v1.py`、`interventions_v1.py`、`scheduling_v1.py`、`station_invocations_v1.py`、`inventory_seam_v1.py`、`events.py` | 全部路由已移植(route map Workflow authoring / Task lifecycle 两节,p7-a/b/d)。行为缺口(根因在 workflow 区):①`inventory_bindings` 在建任务时只校验、存盘(`workflow_task.inventory_bindings`)、进幂等指纹,`run-preflight` 只回显——不参与任何预留或检查(V1 `workflow/quantity_inventory.py:prepare_task_allocations` 按绑定把工作流级 `inventory_requirements` 落到指定库存;统一分支 graph 的 `inventory_requirements` 恒为空);②`/workflow-tasks/{uuid}/human-interactions` 与 `/workflow-human-interactions/{uuid}/reply` 无生产者:`HumanInteractions.open` 没有调用者(V1 由 `workflow/human_commands.py` 的 `HumanCommands.*` 原生命令开启),读到的永远是空列表 | +| unilabos/app/workflow_api.py | 2465 | PARTIAL | `server/api/runtime/workflow.py`、`workflow_definition.py`、`tasks_v1.py`、`interventions_v1.py`、`scheduling_v1.py`、`station_invocations_v1.py`、`inventory_seam_v1.py`、`events.py` | 全部路由已移植(route map Workflow authoring / Task lifecycle 两节,p7-a/b/d)。与 V1 的差异:①`inventory_bindings` 在建任务与 `run-preflight` 时由 `task_lifecycle.bind_plan_inventory` 落到冻结计划里对应的节点库存需求,决定从哪份库存预留(对应 V1 `workflow/quantity_inventory.py:prepare_task_allocations`);graph 的 `inventory_requirements` 不单独存储,每次读取从节点 `meta_data.inventory_requirements` 派生:只列本层(不列禁用节点及其后代、不列组合调用私有子图),`requirement_key` 在整个执行计划内唯一(重名写成 `<节点 uuid>/`,可直接用于绑定)。行为缺口(根因在 workflow 区):②`/workflow-tasks/{uuid}/human-interactions` 与 `/workflow-human-interactions/{uuid}/reply` 无生产者:`HumanInteractions.open` 没有调用者(V1 由 `workflow/human_commands.py` 的 `HumanCommands.*` 原生命令开启),读到的永远是空列表 | | unilabos/app/workflow_authoring_transform.py | 483 | PARTIAL | `server/services/runtime/workflow/authoring_compiler.py:WorkflowAuthoringCompiler`,路由在 `server/api/runtime/workflow_definition.py` | `/authoring/compile`、`/authoring/validate` 已有。`/authoring/generate-python` 只能渲染动作、循环、group/parallel;条件节点、py_script、人工确认、组合调用、具名输出、资源作用域、Handle 连线都返回 `graph_not_representable`(`render_block` / `fail`)。V1 `workflow/authoring_python.py:render_authoring_python` 能渲染条件、人工确认和展开的组合调用。影响:图编辑器里含 if/else 或组合调用的工作流无法生成源码 | | unilabos/app/workflow_openapi.py | 153 | PARTIAL | `server/api/envelope.py`(`Envelope[T]`、`EnvelopeRoute` 自动包 `response_model`) | 信封形状进 OpenAPI;但工作流 / 实验操作路由没有声明 `response_model`(`WorkflowReadModel`、列表、发布、类别读模型等 V1 响应 Schema 不在 OpenAPI 中)。仅影响文档与生成类型 | | unilabos/app/workflow_template_api.py | 390 | PARTIAL | `server/services/runtime/workflow/node_templates.py`(注册表 → runtime.db `workflow_node_template`),`GET /workflow-node-templates[/{uuid}]` | 设备动作模板已投影(V1 确定性 UUID)。结构模板 condition / repeat_until(及 group)未投影(route map p7-a 注明);`material_io` 按 #6 不做。影响:FE 节点面板拿不到条件 / 循环模板 | From b3e289997430107562b39941d1220bac48484385 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:47:36 +0800 Subject: [PATCH 46/59] fix(scheduler): a rejected manual confirmation cancels the task Rejecting a confirmation used to fail the step, so the task ended failed with node_execution_failed. A rejection is the operator stopping the run. The step is now canceled and keeps manual_confirmation_rejected as its reason, for both manual_confirm and material_io (they share the workflow_manual_confirmation gate). The DAG stops as on any canceled step: downstream nodes are not dispatched and end canceled, the task ends canceled with error code manual_confirmation_rejected, and task-level inventory reservations are released as on a normal cancel. A rejected material_io still leaves the inventory unchanged. A timeout still ends the step as timeout and the task as failed. --- .../scheduling_and_execution.md | 3 +- tests/server/test_material_io_scheduler.py | 7 ++- .../test_workflow_manual_confirmation.py | 54 +++++++++++++++++++ unilabos/server/scheduler/service.py | 34 +++++++----- 4 files changed, 81 insertions(+), 17 deletions(-) diff --git a/docs/developer_guide/scheduling_and_execution.md b/docs/developer_guide/scheduling_and_execution.md index fd4936996..94d516428 100644 --- a/docs/developer_guide/scheduling_and_execution.md +++ b/docs/developer_guide/scheduling_and_execution.md @@ -257,7 +257,8 @@ edge、不占设备动作锁,执行器永远收不到它。作者写法见 | 批准,unload 完成 | succeeded,`affected_material_uuids`、`device_sync` | `detach`:解除挂载,物料留在库存;`soft_delete`:软删除(`material_with_contents` 连同子物料与内容物) | | 批准,refill 完成 | succeeded,`quantity_added` / `quantity`、`device_sync` | 原位容器唯一试剂加量(单位可换算),记一条 `add` 内容物历史;位置不变、不新建物料 | | 批准但写库被拒(如确认期间有人手工占了库位) | failed,`material_io_rejected` + `material_error_code`(`conflict:site_occupied`)+ `business_code`(6007) | 不变 | -| 拒绝 / 超时 | failed(`manual_confirmation_rejected`)/ timeout(`manual_confirmation_timed_out`) | 不变 | +| 拒绝 | canceled(`manual_confirmation_rejected`);按取消收口:下游不派发、canceled,任务 canceled(`error_info[0].code=manual_confirmation_rejected`),整任务预留的库存与正常取消一样释放。普通人工确认(`manual_confirm`)被拒绝同样如此 | 不变 | +| 超时 | timeout(`manual_confirmation_timed_out`),任务 failed | 不变 | | 批准、写库完成,台面同步失败 | 仍是 running(attempt `pending`),按同一命令身份重提直到设备确认,之后同上 | 已写入,不回滚,重提不再写 | | 取消任务 | 确认单收为 `canceled`,节点 canceled;等台面同步时取消也是 canceled(`material_io_device_sync_failed`) | 确认前取消:不变;写库后取消:保持已写入 | diff --git a/tests/server/test_material_io_scheduler.py b/tests/server/test_material_io_scheduler.py index ceef016ff..bd10c0cb3 100644 --- a/tests/server/test_material_io_scheduler.py +++ b/tests/server/test_material_io_scheduler.py @@ -161,11 +161,14 @@ def test_reject_and_timeout_leave_the_inventory_as_it_was(tmp_path) -> None: scheduler = _scheduler(stack, executor) body = f'ctx.material_io(mode="load", mount="{mount}", site="A1", resource_template="tip_box", timeout_seconds=60)' try: + # 拒绝按取消处理:步骤 canceled(保留拒绝原因),任务 canceled;超时仍是 timeout,任务 failed rejected = _task(stack, body) _decide(stack, _pending(stack, rejected), "reject") - wait_for(lambda: _status(stack, rejected) == "failed") + wait_for(lambda: _status(stack, rejected) == "canceled") [job] = _material_io_jobs(stack, rejected) - assert job["status"] == "failed" and job["error_info"] == [{"code": "manual_confirmation_rejected"}] + assert job["status"] == "canceled" and job["error_info"] == [{"code": "manual_confirmation_rejected"}] + assert stack.workflow.get_workflow_task(rejected["uuid"])["error_info"][0]["code"] == "manual_confirmation_rejected" + assert _tip_boxes(stack) == [] and not scheduler.resources.held_by(job["uuid"]) timed_out = _task(stack, body) _pending(stack, timed_out) diff --git a/tests/server/test_workflow_manual_confirmation.py b/tests/server/test_workflow_manual_confirmation.py index da3e4e408..c8658b36d 100644 --- a/tests/server/test_workflow_manual_confirmation.py +++ b/tests/server/test_workflow_manual_confirmation.py @@ -264,6 +264,60 @@ def test_scheduler_holds_manual_node_until_decision_without_device_dispatch() -> service.close() +def test_rejection_cancels_the_task_and_releases_its_inventory(tmp_path) -> None: + """拒绝人工确认按取消处理:确认节点 canceled(原因 manual_confirmation_rejected),下游不派发、canceled, + 任务 canceled;整任务预留的库存像正常取消一样释放。""" + + from uuid import uuid4 + + from tests.server.test_scheduler_inventory_authority import _inbound, _template + from tests.server.test_workflow_inventory_recovery import Stack + from tests.server.test_workflow_parallel_execution import Executor, wait_for + from unilabos.protocol.materials import InventoryRequirement + from unilabos.registry.workflows import upsert_workflow + + stack, executor = Stack(tmp_path), Executor() + _template(stack.materials, "reagent-template", "reagent") + _inbound(stack.materials, lot_uuid="lot-a", quantity=20) + scheduler = BackendScheduler(stack.workflow, executor, materials_gateway=stack.client) # type: ignore[arg-type] + stack.workflow.set_task_submitter(scheduler.submit) + try: + confirm = {"uuid": str(uuid4()), "name": "确认", "type": "device_action", "material_uuid": str(uuid4()), + "action_name": "manual_confirm", "execution_policy": {"always_free": True}, + "param": {"assignee_user_ids": [], "timeout_seconds": 3600}, + "meta_data": {"target_device_id": "host_node"}} + requirement = InventoryRequirement(key="solvent", kind="lot", template_uuid="reagent-template", quantity=5, unit="ul") + action = {"uuid": str(uuid4()), "name": "操作", "type": "device_action", "material_uuid": str(uuid4()), + "action_name": "operate", "param": {}, "execution_policy": {"depends_on": [confirm["uuid"]]}, + "meta_data": {"target_device_id": "reactor", + "inventory_requirements": [requirement.model_dump(mode="json")]}} + record = upsert_workflow(stack.workflow, {"workflow_uuid": str(uuid4()), "name": "拒绝即取消", "description": "", + "tags": [], "nodes": [confirm, action], "edges": []}) + task = stack.workflow.create_workflow_task(workflow_uuid=record["uuid"], run_mode="normal", target_node_uuid=None, + input_value={}, description=None, meta_data={}) + runs = {run["workflow_node_uuid"]: run for run in stack.workflow.list_workflow_node_runs(task["uuid"])} + job = runs[confirm["uuid"]]["current_job_uuid"] + wait_for(lambda: (stack.workflow.get_manual_confirmation_for_job(job) or {}).get("status") == "pending") + assert stack.quantities() == (20, 15, 5) + + stack.workflow.decide_workflow_manual_confirmation( + stack.workflow.get_manual_confirmation_for_job(job)["uuid"], action="reject", confirmed_by="operator", + decision_idempotency_key="reject-1", + ) + wait_for(lambda: stack.workflow.get_workflow_task(task["uuid"])["status"] == "canceled") + finished = stack.workflow.get_workflow_task(task["uuid"]) + assert finished["error_info"][0]["code"] == "manual_confirmation_rejected" + settled = stack.workflow.get_workflow_node_job(job) + assert settled["status"] == "canceled" and settled["error_info"] == [{"code": "manual_confirmation_rejected"}] + runs = {run["workflow_node_uuid"]: run for run in stack.workflow.list_workflow_node_runs(task["uuid"])} + assert runs[action["uuid"]]["status"] == "canceled" and executor.dispatched == [] + assert stack.quantities() == (20, 20, 0) + finally: + stack.workflow.set_task_submitter(None) + scheduler.stop() + stack.close() + + def test_scheduler_rejects_missing_assignee_key_before_opening_gate() -> None: service = WorkflowService(":memory:") executor = _Executor() diff --git a/unilabos/server/scheduler/service.py b/unilabos/server/scheduler/service.py index dbdfe4b2f..4a204c83b 100644 --- a/unilabos/server/scheduler/service.py +++ b/unilabos/server/scheduler/service.py @@ -2058,7 +2058,8 @@ def _settle_material_io( elif status == "approved": job_status = "skipped" elif status == "rejected": - job_status, errors = "failed", [{"code": "manual_confirmation_rejected"}] + # 拒绝按取消处理:节点 canceled、保留拒绝原因,任务随之取消收口;库存不变 + job_status, errors = "canceled", [{"code": "manual_confirmation_rejected"}] elif status == "timed_out": job_status, errors = "timeout", [{"code": "manual_confirmation_timed_out"}] else: @@ -3216,14 +3217,16 @@ def _on_manual_confirmation_decided( decision_action = str( (confirmation.get("meta_data") or {}).get("decision_action") or "" ).strip().lower() + errors: list[Dict[str, Any]] = [] if status == "approved": job_status = "skipped" if decision_action == "skip" else "succeeded" node_state = NodeState.SUCCESS elif status == "rejected": - job_status = "failed" - node_state = NodeState.FAILED + # 拒绝按取消处理:节点 canceled、保留拒绝原因,下游不派发,任务以 canceled 收口 + job_status, errors = "canceled", [{"code": "manual_confirmation_rejected"}] + node_state = NodeState.CANCELLED elif status == "timed_out": - job_status = "timeout" + job_status, errors = "timeout", [{"code": "manual_confirmation_timed_out"}] node_state = NodeState.FAILED elif status == "canceled": job_status = "canceled" @@ -3251,11 +3254,7 @@ def _on_manual_confirmation_decided( "comment": confirmation.get("comment"), }, }, - error_info=( - [] - if job_status in {"succeeded", "skipped", "canceled"} - else [{"code": f"manual_confirmation_{status}"}] - ), + error_info=errors, ) except Exception: # noqa: BLE001 - 保留 durable 决策,等待恢复重试 logger.exception( @@ -3707,14 +3706,21 @@ def _restart_after_preflight(self, pending: Dict[str, Any]) -> None: self._notify_start_failure(node.node_id) def _task_failure_error(self, task_uuid: str) -> Dict[str, Any]: - """任务因节点失败而结束:失败节点都是动作执行前预检未通过的记预检报错,否则记执行报错。""" + """任务没有成功结束:失败节点都是动作执行前预检未通过的记预检报错;没有失败节点、因人工确认被拒绝而取消的 + 记拒绝;否则记执行报错。""" try: - failed = [run for run in self.workflow.list_workflow_node_runs(task_uuid) if run.get("status") == "failed"] + runs = self.workflow.list_workflow_node_runs(task_uuid) except Exception: # noqa: BLE001 - 读不到明细时按执行报错记 - failed = [] - if failed and all(((run.get("error_info") or [{}])[0] or {}).get("stage") == ERROR_STAGE_PREFLIGHT - for run in failed): + runs = [] + + def first_error(run: Mapping[str, Any]) -> Mapping[str, Any]: + return (run.get("error_info") or [{}])[0] or {} + + failed = [run for run in runs if run.get("status") == "failed"] + if failed and all(first_error(run).get("stage") == ERROR_STAGE_PREFLIGHT for run in failed): return {"code": "node_preflight_failed", "stage": ERROR_STAGE_PREFLIGHT, "scope": "action"} + if not failed and any(first_error(run).get("code") == "manual_confirmation_rejected" for run in runs): + return {"code": "manual_confirmation_rejected", "stage": ERROR_STAGE_EXECUTION} return {"code": "node_execution_failed", "stage": ERROR_STAGE_EXECUTION} def _action_max_retries(self, device_id: str, action_name: str) -> int: From bc7e668ba3a8ee286437879ca49d831d82f7cf12 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:29:20 +0800 Subject: [PATCH 47/59] feat(events): material and log notices share the /api/v1/events sequence material.changed and runtime.logs.changed are now frontend_event rows, written by the authority process that owns the Workflow Authority. The writer is a permanent subscriber of the shared materials ledger poller and of the in-process log notice hub (Host notices arrive there through runtime_logs_changed). Each kind is coalesced and written at most once per second; the first notice after a quiet period is written at once. material_uuids keeps its meaning and is dropped above 500 entries. Every frame on /api/v1/events now has an integer id from one sequence, so Last-Event-ID resume, stream.reset and retention cleanup cover material and log notices too. A written row wakes the local SSE connections instead of waiting for the next poll. On restart the writer resumes after the ledger sequence recorded in the last material row. --- tests/app/test_workflow_watch_sse.py | 11 +- tests/server/test_log_notices.py | 56 +- .../test_runtime_events_material_notices.py | 527 +++++++++++++----- unilabos/server/api/runtime/events.py | 168 ++---- unilabos/server/execution_composition.py | 32 +- .../server/services/materials/ledger_watch.py | 10 +- .../runtime/workflow/frontend_notices.py | 239 ++++++++ .../server/services/runtime/workflow/store.py | 19 + unilabos/utils/log_notices.py | 6 +- 9 files changed, 754 insertions(+), 314 deletions(-) create mode 100644 unilabos/server/services/runtime/workflow/frontend_notices.py diff --git a/tests/app/test_workflow_watch_sse.py b/tests/app/test_workflow_watch_sse.py index efe9a538f..f6a34a501 100644 --- a/tests/app/test_workflow_watch_sse.py +++ b/tests/app/test_workflow_watch_sse.py @@ -21,7 +21,6 @@ _parse_sse_lines, _sse_frame_notice, ) -from unilabos.server.api.runtime.events import material_changed_frame from unilabos.server.api.runtime.workflow import format_sse_event @@ -159,20 +158,20 @@ def test_watch_follows_stream_reset_and_skips_unchanged_snapshots() -> None: ] -def test_watch_cursor_ignores_id_less_material_notice() -> None: - # 服务端真实帧:水位帧、物料账本末尾 5000 的 material.changed(无 id)、任务通知 id 42。 - # material.changed 的 data.sequence 是物料账本序号,不能推进工作流游标,否则 42 会被丢弃。 +def test_watch_cursor_follows_the_frame_id_not_the_material_ledger_sequence() -> None: + # 服务端真实帧:水位帧、物料账本末尾 5000 的 material.changed(id 41)、任务通知 id 42。 + # material.changed 的 data.sequence 是物料账本序号,不能当游标,否则 42 会被当成旧帧丢弃。 raw = ( "retry: 3000\n: connected\n\n" "id: 40\n\n" - + material_changed_frame(5000, ["m1"]) + + format_sse_event({"id": 41, "event": "material.changed", "data": {"sequence": 5000, "material_uuids": ["m1"]}}) + format_sse_event( {"id": 42, "event": RUNTIME_CHANGED_EVENT, "data": {"kind": "task", "workflow_task_uuid": "task-1"}} ) ) frames = [json.loads(_sse_frame_notice(frame)) for frame in _parse_sse_lines(_iter_text_lines([raw]))] assert [(frame["action"], frame["id"]) for frame in frames] == [ - ("message", 40), ("material.changed", None), (RUNTIME_CHANGED_EVENT, 42), + ("message", 40), ("material.changed", 41), (RUNTIME_CHANGED_EVENT, 42), ] http = _Tasks(["running", "running", "succeeded"]) client = HTTPWorkflowClient("http://edge:8002", http_client=http, notice_connector=lambda *_: _Notices(frames)) diff --git a/tests/server/test_log_notices.py b/tests/server/test_log_notices.py index 9914afb87..1cfc6742a 100644 --- a/tests/server/test_log_notices.py +++ b/tests/server/test_log_notices.py @@ -1,9 +1,10 @@ -"""日志轻通知:空闲静默、突发合并、来源鉴别、SSE 游标及 WS 快速通道。""" +"""日志轻通知:空闲静默、突发合并、来源鉴别及 WS 快速通道。 + +写进 frontend_event、在 /api/v1/events 上带 id 发出的部分见 ``test_runtime_events_material_notices.py``。 +""" from __future__ import annotations -import asyncio -import json import logging import threading from unittest.mock import Mock @@ -12,7 +13,6 @@ from pydantic import ValidationError from unilabos.protocol.runtime.logs import RuntimeLogNotice -from unilabos.server.api.runtime import events from unilabos.utils import log_notices as notices @@ -127,43 +127,13 @@ def test_edge_control_notice_is_ephemeral_and_resyncs_on_attach_detach(monkeypat assert hub.changed.call_count == 2 -def test_sse_notice_merges_slow_reader_without_changing_workflow_cursor(monkeypatch): - class Hub: - listener = None - - def subscribe(self, listener): - self.listener = listener - return lambda: setattr(self, "listener", None) - - hub = Hub() - monkeypatch.setattr(events, "log_notices", hub) - monkeypatch.setattr(events, "shutting_down", lambda: False) - - class Request: - async def is_disconnected(self): - return False - - workflow = Mock() - workflow.read_event_window.return_value = (1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}]) +def test_notice_writer_logs_do_not_trigger_notices(monkeypatch): + """权威把通知写进 frontend_event 的线程写失败会记日志;这些日志再触发通知就成了自激循环。""" - async def scenario(): - stream = events.runtime_event_stream(Request(), workflow, cursor=41) - assert "connected" in await anext(stream) - durable = await anext(stream) - # 库里存 dev 事件名,SSE 按 V1 发 workflow.runtime.changed,种类放进 data.kind - assert durable.startswith("id: 42\nevent: workflow.runtime.changed\n") - assert json.loads(durable.split("data: ")[1]) == {"uuid": "t", "kind": "task"} - # 慢读者停在 yield 期间,重复通知只保留合并后的一个槽位。 - for _ in range(100): - hub.listener(RuntimeLogNotice(source_ids=["host"])) - hub.listener(RuntimeLogNotice(source_ids=["slave:a"], sources_changed=True)) - await asyncio.sleep(0) - frame = await asyncio.wait_for(anext(stream), 1) - assert "event: runtime.logs.changed\n" in frame and "id:" not in frame - payload = json.loads(frame.split("data: ")[1]) - assert payload["source_ids"] == ["host", "slave:a"] and payload["sources_changed"] - workflow.read_event_window.assert_called_once_with(after_id=41, limit=101) - await stream.aclose() - assert hub.listener is None - - asyncio.run(scenario()) + hub = Mock() + monkeypatch.setattr(notices, "log_notices", hub) + handler = notices.LogAppendHandler() + record = logging.LogRecord("frontend_notices", logging.WARNING, "", 0, "写前端通知失败", (), None) + record.threadName = notices.NOTICE_WRITER_THREAD + handler.emit(record) + hub.changed.assert_not_called() diff --git a/tests/server/test_runtime_events_material_notices.py b/tests/server/test_runtime_events_material_notices.py index aaa8e8a5e..d52acc9c6 100644 --- a/tests/server/test_runtime_events_material_notices.py +++ b/tests/server/test_runtime_events_material_notices.py @@ -1,29 +1,32 @@ -"""/api/v1/events 的物料失效:账本前进就推一条无 id 的 material.changed,不动工作流游标。 +"""/api/v1/events 的物料与日志通知:权威进程合并、限速后写进 frontend_event,与工作流事件同一序列。 -前端每个工站只维持这一条事件流(HTTP/1.1 连接数有限),物料失效与工作流、日志通知走同一条。 +每一帧都带整数 id:断线期间的物料变化在重连(Last-Event-ID)后补发,过期 / 超前游标照常 stream.reset。 通知列出这段账本里变了的物料,前端只重读这些(空列表:没有物料变化);列不准时省略,前端整体重读。 -账本由一个物料权威一条的共享轮询线程读,所有连接共用,不占默认线程池。 +账本由一个物料权威一条的共享轮询线程读,写入器是它的常驻订阅者。 """ from __future__ import annotations import asyncio import json +import time +from contextlib import contextmanager from types import SimpleNamespace -from unittest.mock import Mock - -from unilabos.server.api.runtime import events -from unilabos.server.services.materials.ledger_watch import LedgerWatch +import pytest -class _Request: - async def is_disconnected(self): - return False +from unilabos.protocol.runtime.logs import RuntimeLogNotice +from unilabos.server.api.runtime import events +from unilabos.server.api.runtime.workflow import create_workflow_app +from unilabos.server.services.materials.ledger_watch import LedgerBatch, LedgerWatch +from unilabos.server.services.runtime.workflow.frontend_notices import ( + MATERIAL_UUIDS_LIMIT, + FrontendNoticeWriter, + material_notice_data, +) +from unilabos.server.services.runtime.workflow.service import WorkflowService - -class _NoLogNotices: - def subscribe(self, listener): - return lambda: None +NOW = "2026-11-04T00:00:00Z" class _Ledger: @@ -31,12 +34,15 @@ class _Ledger: def __init__(self, tail: int, rows=(), sites=None): self.tail = tail - self.rows = [ - SimpleNamespace(sequence=row[0], aggregate_type=row[1], aggregate_uuid=row[2], - delta=row[3] if len(row) > 3 else {}) - for row in rows - ] + self.rows = [] self.sites = dict(sites or {}) + self.add(*rows) + + def add(self, *rows) -> None: + for row in rows: + self.rows.append(SimpleNamespace(sequence=row[0], aggregate_type=row[1], aggregate_uuid=row[2], + delta=row[3] if len(row) > 3 else {})) + self.tail = max(self.tail, row[0]) def latest_ledger_sequence(self) -> int: return self.tail @@ -49,114 +55,335 @@ def get_site(self, site_uuid: str, *, include_deleted: bool = False): return SimpleNamespace(owner_material_uuid=owner) if owner else None -def _quiet(monkeypatch): - monkeypatch.setattr(events, "log_notices", _NoLogNotices()) - monkeypatch.setattr(events, "shutting_down", lambda: False) +class _NoLogs: + def subscribe(self, listener): + return lambda: None -def _workflow(events_window=None): - workflow = Mock() - workflow.read_event_window.return_value = events_window or (1, 41, []) - return workflow +class _Hub: + listener = None + def subscribe(self, listener): + self.listener = listener + return lambda: setattr(self, "listener", None) -def _first_frame(materials, cursor: int, workflow=None) -> str: - async def scenario(): - stream = events.runtime_event_stream( - _Request(), workflow or _workflow(), cursor=41, - materials=LedgerWatch(materials), material_cursor=cursor, - ) - assert "connected" in await anext(stream) - frame = await asyncio.wait_for(anext(stream), 2) - await stream.aclose() - return frame - return asyncio.run(scenario()) +class _ManualWatch(LedgerWatch): + """手动投递账本批次:记下订阅起点与回调,由测试决定每一批什么时候到。""" + def __init__(self) -> None: + super().__init__(None) + self.after: object = "unset" + self.deliver = None -def _data(frame: str) -> dict: - return json.loads(frame.split("data: ")[1]) + def subscribe(self, after, deliver): + self.after, self.deliver = after, deliver + return lambda: None -def test_ledger_advance_lists_the_changed_materials_without_an_id(monkeypatch): - _quiet(monkeypatch) - ledger = _Ledger( - 7, - rows=[(5, "material", "old"), (6, "site", "site-1"), (6, "material", "plate"), (7, "lot", "lot-1"), (7, "material", "plate")], - sites={"site-1": "deck"}, - ) - frame = _first_frame(ledger, cursor=5) - assert frame.startswith("event: material.changed\n") - assert "id:" not in frame # 不占工作流游标 - # 区间 (5, 7]:Site 归到所属台面,批次不进物料图,重复的物料去重 - assert _data(frame) == {"sequence": 7, "material_uuids": ["deck", "plate"]} +@pytest.fixture +def workflow(monkeypatch): + monkeypatch.setattr(events, "shutting_down", lambda: False) + service = WorkflowService(":memory:") + yield service + service.close() -def test_a_slow_ledger_read_does_not_stall_the_event_loop(monkeypatch): - """读账本要拿物料库的锁,写事务持锁时读会等;这段等待在工作线程里,不卡住事件循环上的其它连接。""" +def _rows(service: WorkflowService, event: str | None = None) -> list[dict]: + items = service.list_events(after_id=0, limit=1000)["items"] + return [item for item in items if event is None or item["event"] == event] - import time - _quiet(monkeypatch) +def _wait(predicate, timeout: float = 3.0) -> None: + deadline = time.monotonic() + timeout + while not predicate(): + if time.monotonic() > deadline: + raise AssertionError("等待超时") + time.sleep(0.02) - class _SlowLedger(_Ledger): - def latest_ledger_sequence(self) -> int: - time.sleep(0.6) - return self.tail - async def scenario(): - stream = events.runtime_event_stream( - _Request(), _workflow(), cursor=41, - materials=LedgerWatch(_SlowLedger(3, rows=[(3, "material", "m")])), material_cursor=2, - ) - assert "connected" in await anext(stream) - ticks: list[float] = [] +@contextmanager +def _writer(service: WorkflowService, *, hub=None, materials=None, interval: float = 0.1): + writer = FrontendNoticeWriter(service, materials=materials, hub=hub or _NoLogs(), interval=interval) + writer.start() + if isinstance(materials, LedgerWatch) and not isinstance(materials, _ManualWatch): + _wait(lambda: materials._subscribers) # 订阅在轮询线程上登记 + try: + yield writer + finally: + writer.stop() - async def ticker(): - for _ in range(30): - ticks.append(time.monotonic()) - await asyncio.sleep(0.02) - beat = asyncio.create_task(ticker()) - frame = await asyncio.wait_for(anext(stream), 3) - await beat - await stream.aclose() - return frame, max(later - earlier for earlier, later in zip(ticks, ticks[1:])) +def _material_rows_after(service: WorkflowService, recorded: int, ledger: _Ledger) -> list[dict]: + """先记下一条“上次写到 recorded”的物料通知,再启动写入器,返回它续写出的物料通知。""" - frame, worst_gap = asyncio.run(scenario()) - assert _data(frame) == {"sequence": 3, "material_uuids": ["m"]} - assert worst_gap < 0.3 + service.append_frontend_event("material.changed", {"sequence": recorded}) + with _writer(service, materials=LedgerWatch(ledger, interval=0.05)): + _wait(lambda: len(_rows(service, "material.changed")) >= 2) + return [row["data"] for row in _rows(service, "material.changed")[1:]] -def test_template_change_asks_for_a_full_reload(monkeypatch): - _quiet(monkeypatch) - ledger = _Ledger(9, rows=[(8, "material", "plate"), (9, "resource_template", "tpl")]) - assert _data(_first_frame(ledger, cursor=7)) == {"sequence": 9} +async def _read(app, headers: list[tuple[bytes, bytes]], steps) -> str: + """直接驱动 ASGI 应用读 SSE:依次等待 steps 中每个 (predicate, action),文本满足 predicate 后执行 action。""" + chunks: list[str] = [] + changed = asyncio.Event() + disconnect = asyncio.Event() + + async def receive(): + await disconnect.wait() + return {"type": "http.disconnect"} + + async def send(message): + if message["type"] == "http.response.body": + chunks.append(message.get("body", b"").decode("utf-8")) + changed.set() + + scope = { + "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", + "scheme": "http", "path": "/api/v1/events", "raw_path": b"/api/v1/events", "query_string": b"", + "root_path": "", "headers": headers, "client": ("127.0.0.1", 1), "server": ("testserver", 80), + } + task = asyncio.create_task(app(scope, receive, send)) + try: + for predicate, action in steps: + while not predicate("".join(chunks)): + changed.clear() + await asyncio.wait_for(changed.wait(), 5.0) + if action is not None: + await asyncio.to_thread(action) + finally: + disconnect.set() + await asyncio.wait_for(task, 5.0) + return "".join(chunks) -def test_ledger_reset_asks_for_a_full_reload(monkeypatch): - _quiet(monkeypatch) - # 库被重置:末尾比基线小,列不准 - assert _data(_first_frame(_Ledger(2), cursor=40)) == {"sequence": 2} +def _frame(text: str, sequence: int) -> dict: + block = next(item for item in text.split("\n\n") if item.startswith(f"id: {sequence}\nevent:")) + lines = dict(line.split(": ", 1) for line in block.split("\n")) + return {"event": lines["event"], "data": json.loads(lines["data"])} -def test_unchanged_ledger_sends_nothing_before_workflow_events(monkeypatch): - _quiet(monkeypatch) - workflow = _workflow((1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}])) - frame = _first_frame(_Ledger(7), cursor=7, workflow=workflow) - assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") +# ── 物料通知 ───────────────────────────────────────────────────────── -def test_ledger_read_failure_does_not_break_the_workflow_stream(monkeypatch): - _quiet(monkeypatch) +def test_a_material_change_while_disconnected_arrives_after_reconnect(workflow): + """断线期间账本前进:重连带 Last-Event-ID 后收到带 id 的 material.changed,不靠 REST 补读兜底。""" + + workflow.append_frontend_event("workflow.task.changed", {"workflow_task_uuid": "t"}) + ledger = _Ledger(3) + app = create_workflow_app(workflow) + with _writer(workflow, materials=LedgerWatch(ledger, interval=0.05)): + first = asyncio.run(_read(app, [], [(lambda body: "id: 1\n\n" in body, None)])) + assert "material.changed" not in first + # 客户端已断开;这时物料变了 + ledger.add((4, "material", "plate")) + _wait(lambda: _rows(workflow, "material.changed")) + again = asyncio.run(_read(app, [(b"last-event-id", b"1")], [(lambda body: "id: 2\nevent:" in body, None)])) + assert _frame(again, 2) == {"event": "material.changed", "data": {"sequence": 4, "material_uuids": ["plate"]}} + assert "stream.reset" not in again + + +def test_ledger_window_names_the_changed_materials(workflow): + ledger = _Ledger( + 7, + rows=[(5, "material", "old"), (6, "site", "site-1"), (6, "material", "plate"), (7, "lot", "lot-1"), (7, "material", "plate")], + sites={"site-1": "deck"}, + ) + # 区间 (5, 7]:Site 归到所属台面,批次不进物料图,重复的物料去重 + assert _material_rows_after(workflow, 5, ledger) == [{"sequence": 7, "material_uuids": ["deck", "plate"]}] + + +@pytest.mark.parametrize("recorded,ledger,expected", [ + # 模板变化:列不准,整体重读 + (7, _Ledger(9, rows=[(8, "material", "plate"), (9, "resource_template", "tpl")]), {"sequence": 9}), + # 只动了批次 / 预留:空列表(没有物料要重读),不是省略(整体重读) + (7, _Ledger(9, rows=[(8, "lot", "lot-1"), (9, "reservation", "r-1")]), {"sequence": 9, "material_uuids": []}), + # 拓扑边:列出两端物料 + (3, _Ledger(4, rows=[(4, "link", "l-1", {"source_material_uuid": "pump", "target_material_uuid": "flask"})]), + {"sequence": 4, "material_uuids": ["flask", "pump"]}), + # 账本比上次记下的还短(库被重置):整体重读 + (40, _Ledger(2), {"sequence": 2}), +]) +def test_material_uuids_semantics(workflow, recorded, ledger, expected): + assert _material_rows_after(workflow, recorded, ledger) == [expected] + + +def test_more_materials_than_the_limit_ask_for_a_full_reload(): + many = [f"m{index:04d}" for index in range(MATERIAL_UUIDS_LIMIT + 1)] + assert material_notice_data(LedgerBatch(after=0, upto=9, changed=many)) == {"sequence": 9} + assert material_notice_data(LedgerBatch(after=0, upto=9, changed=many[:3])) == { + "sequence": 9, "material_uuids": many[:3], + } + + +def test_batches_inside_the_interval_merge_into_one_row(workflow): + watch = _ManualWatch() + with _writer(workflow, materials=watch, interval=0.4): + watch.deliver(LedgerBatch(after=0, upto=1, changed=["a"])) + # 空闲后的第一批立即写 + _wait(lambda: len(_rows(workflow, "material.changed")) == 1, timeout=0.35) + watch.deliver(LedgerBatch(after=1, upto=2, changed=["b"])) + watch.deliver(LedgerBatch(after=2, upto=3, changed=["c", "b"])) + _wait(lambda: len(_rows(workflow, "material.changed")) == 2) + watch.deliver(LedgerBatch(after=3, upto=4, changed=["d"])) + watch.deliver(LedgerBatch(after=4, upto=5, changed=None)) + _wait(lambda: len(_rows(workflow, "material.changed")) == 3) + time.sleep(0.5) + assert [row["data"] for row in _rows(workflow, "material.changed")] == [ + {"sequence": 1, "material_uuids": ["a"]}, + {"sequence": 3, "material_uuids": ["b", "c"]}, + {"sequence": 5}, # 合并进来的一批列不准,整批整体重读 + ] + + +def test_writer_resumes_after_the_recorded_ledger_sequence(workflow): + watch = _ManualWatch() + with _writer(workflow, materials=watch): + pass + assert watch.after is None # 没有记下的物料通知:从当前账本末尾开始 + workflow.append_frontend_event("material.changed", {"sequence": 12, "material_uuids": []}) + with _writer(workflow, materials=watch): + pass + assert watch.after == 12 + + +def test_a_failed_write_is_retried_without_losing_the_window(workflow, monkeypatch): + watch = _ManualWatch() + real = workflow.append_frontend_event + failures = iter([RuntimeError("database is locked")]) + + def flaky(event, data): + error = next(failures, None) + if error is not None: + raise error + return real(event, data) + + monkeypatch.setattr(workflow, "append_frontend_event", flaky) + with _writer(workflow, materials=watch, interval=0.05): + watch.deliver(LedgerBatch(after=0, upto=1, changed=["a"])) + time.sleep(0.1) + watch.deliver(LedgerBatch(after=1, upto=2, changed=["b"])) + _wait(lambda: _rows(workflow, "material.changed")) + assert [row["data"] for row in _rows(workflow, "material.changed")] == [ + {"sequence": 2, "material_uuids": ["a", "b"]}, + ] + + +def test_a_broken_ledger_does_not_stop_log_notices(workflow): class Broken(_Ledger): def latest_ledger_sequence(self) -> int: raise RuntimeError("materials.db is locked") - workflow = _workflow((1, 42, [{"id": 42, "event": "workflow.task.changed", "data": {"uuid": "t"}}])) - frame = _first_frame(Broken(0), cursor=3, workflow=workflow) - assert frame.startswith("id: 42\nevent: workflow.runtime.changed\n") + hub = _Hub() + writer = FrontendNoticeWriter(workflow, materials=LedgerWatch(Broken(0), interval=0.05), hub=hub, interval=0.1) + writer.start() + try: + hub.listener(RuntimeLogNotice(source_ids=["host"])) + _wait(lambda: _rows(workflow, "runtime.logs.changed")) + finally: + writer.stop() + + +# ── 日志通知 ───────────────────────────────────────────────────────── + + +def test_log_notices_get_ids_and_are_coalesced(workflow): + hub = _Hub() + app = create_workflow_app(workflow) + with _writer(workflow, hub=hub, interval=0.3): + for _ in range(100): + hub.listener(RuntimeLogNotice(source_ids=["host"])) + hub.listener(RuntimeLogNotice(source_ids=["slave:a"], sources_changed=True)) + time.sleep(0.8) + rows = _rows(workflow, "runtime.logs.changed") + text = asyncio.run(_read(app, [(b"last-event-id", b"0")], [ + (lambda body: f"id: {rows[-1]['id']}\nevent:" in body, None), + ])) + # 200 条通知最多两行:空闲后的第一条立即写,其余在间隔内并进下一行 + assert 1 <= len(rows) <= 2 + assert set().union(*(row["data"]["source_ids"] for row in rows)) == {"host", "slave:a"} + assert any(row["data"]["sources_changed"] for row in rows) + for row in rows: + assert _frame(text, row["id"]) == {"event": "runtime.logs.changed", "data": row["data"]} + + +def test_log_rows_are_rate_limited(workflow): + hub = _Hub() + with _writer(workflow, hub=hub, interval=0.3): + started = time.monotonic() + while time.monotonic() - started < 1.0: + hub.listener(RuntimeLogNotice(source_ids=["host"])) + time.sleep(0.01) + time.sleep(0.4) + rows = _rows(workflow, "runtime.logs.changed") + # 1 秒持续刷日志、间隔 0.3 秒:约 4 行,而不是上百行 + assert 2 <= len(rows) <= 6 + + +# ── 同一序列:续传、重置与唤醒 ──────────────────────────────────────── + + +def test_stale_and_ahead_cursors_reset_over_notice_rows(workflow): + for index in range(3): + workflow.append_frontend_event("material.changed", {"sequence": index + 1, "material_uuids": ["m"]}) + for _ in range(2): + workflow.append_frontend_event("runtime.logs.changed", RuntimeLogNotice(source_ids=["host"]).model_dump()) + # 保留窗口 4..5(清理一视同仁地越过物料与日志通知) + workflow.prune_frontend_events(before="0001-01-01T00:00:00.000000Z", max_count=2, batch_size=1000) + app = create_workflow_app(workflow) + + expired = asyncio.run(_read(app, [(b"last-event-id", b"1")], [ + (lambda body: "event: stream.reset" in body, + lambda: workflow.append_frontend_event("material.changed", {"sequence": 9})), + (lambda body: "id: 6\nevent: material.changed" in body, None), + ])) + reset = next(block for block in expired.split("\n\n") if "event: stream.reset" in block) + assert reset.startswith("id: 5\n") and json.loads(reset.split("data: ", 1)[1]) == {"reason": "cursor_expired"} + assert "id: 4\nevent:" not in expired + + ahead = asyncio.run(_read(app, [(b"last-event-id", b"99")], [(lambda body: "event: stream.reset" in body, None)])) + reset = next(block for block in ahead.split("\n\n") if "event: stream.reset" in block) + assert reset.startswith("id: 6\n") and json.loads(reset.split("data: ", 1)[1]) == {"reason": "cursor_ahead"} + + +def test_every_frame_on_the_stream_has_an_id(workflow): + workflow.append_frontend_event("workflow.task.changed", {"workflow_task_uuid": "t"}) + workflow.append_frontend_event("material.changed", {"sequence": 4, "material_uuids": ["m"]}) + workflow.append_frontend_event("runtime.logs.changed", RuntimeLogNotice(source_ids=["host"]).model_dump()) + app = create_workflow_app(workflow) + text = asyncio.run(_read(app, [(b"last-event-id", b"0")], [(lambda body: "id: 3\nevent:" in body, None)])) + blocks = [block for block in text.split("\n\n") if block and not block.startswith(("retry:", ":"))] + assert [block.split("\n", 1)[0] for block in blocks] == ["id: 1", "id: 2", "id: 3"] + assert [_frame(text, index)["event"] for index in (1, 2, 3)] == [ + "workflow.runtime.changed", "material.changed", "runtime.logs.changed", + ] + + +def test_a_written_notice_wakes_the_stream_at_once(workflow): + """写入器写完一行就唤醒本进程的连接,不等约 1 秒一轮的轮询。""" + + hub = _Hub() + app = create_workflow_app(workflow) + marks: dict[str, float] = {} + + def notify() -> None: + time.sleep(0.1) # 让连接先完成首轮读取,进入等待 + marks["sent"] = time.monotonic() + hub.listener(RuntimeLogNotice(source_ids=["host"])) + + def arrived(body: str) -> bool: + if "event: runtime.logs.changed" in body: + marks.setdefault("arrived", time.monotonic()) + return True + return False + + with _writer(workflow, hub=hub, interval=0.1): + asyncio.run(_read(app, [], [(lambda body: "id: 0\n\n" in body, notify), (arrived, None)])) + assert marks["arrived"] - marks["sent"] < 0.5 + + +# ── 账本共享轮询(物料通知与 /api/v1/materials/events 共用) ───────────── def test_real_authority_names_the_placed_material_and_the_site_owner(tmp_path): @@ -224,49 +451,10 @@ def mutation(operation: str) -> InventoryMutation: service.close() -def test_notices_exist_only_where_the_materials_authority_lives(monkeypatch): - from unilabos.server import execution_composition - - monkeypatch.setattr(execution_composition, "get_materials_service", lambda: None) - assert events.material_notices() is None - - monkeypatch.setattr(execution_composition, "get_materials_service", lambda: _Ledger(12)) - notices = events.material_notices() - assert notices is not None and notices.latest() == 12 - - -def test_a_ledger_window_without_material_changes_lists_none(monkeypatch): - """只动了批次 / 预留:带一个空列表(没有物料要重读),不是省略(整体重读)。""" - - _quiet(monkeypatch) - ledger = _Ledger(9, rows=[(8, "lot", "lot-1"), (9, "reservation", "r-1")]) - assert _data(_first_frame(ledger, cursor=7)) == {"sequence": 9, "material_uuids": []} - - -def test_link_changes_name_both_endpoints(monkeypatch): - _quiet(monkeypatch) - ledger = _Ledger(4, rows=[(4, "link", "l-1", {"source_material_uuid": "pump", "target_material_uuid": "flask"})]) - assert _data(_first_frame(ledger, cursor=3)) == {"sequence": 4, "material_uuids": ["flask", "pump"]} - - -def test_material_notices_never_use_the_shared_thread_pool(monkeypatch): - """runtime.v1 控制 socket 的出站泵与 edge 代理用默认线程池;SSE 的物料轮询不能和它们抢。""" - - _quiet(monkeypatch) - - def forbidden(*_args, **_kwargs): - raise AssertionError("SSE 物料轮询用了默认线程池") - - monkeypatch.setattr(events.asyncio, "to_thread", forbidden) - ledger = _Ledger(7, rows=[(6, "material", "plate"), (7, "material", "plate")]) - assert _data(_first_frame(ledger, cursor=5)) == {"sequence": 7, "material_uuids": ["plate"]} - - def test_many_connections_share_one_ledger_read_per_tick(): """N 个订阅者共用一次读:账本末尾的读取次数与连接数无关。""" import threading - import time class _Counting(_Ledger): def __init__(self, *args, **kwargs): @@ -284,8 +472,7 @@ def latest_ledger_sequence(self) -> int: received: list[list] = [[] for _ in range(20)] releases = [watch.subscribe(3, received[index].append) for index in range(20)] time.sleep(0.3) - ledger.rows.append(SimpleNamespace(sequence=4, aggregate_type="material", aggregate_uuid="m", delta={})) - ledger.tail = 4 + ledger.add((4, "material", "m")) deadline = time.monotonic() + 3 while time.monotonic() < deadline and not all(batches for batches in received): time.sleep(0.02) @@ -303,8 +490,6 @@ def latest_ledger_sequence(self) -> int: def test_a_late_subscriber_catches_up_from_its_own_cursor(): - import time - ledger = _Ledger(5, rows=[(4, "material", "a"), (5, "material", "b")]) watch = LedgerWatch(ledger, interval=0.05) first: list = [] @@ -318,3 +503,67 @@ def test_a_late_subscriber_catches_up_from_its_own_cursor(): release_late() assert first == [] assert [(batch.after, batch.upto, batch.changed) for batch in late] == [(3, 5, ["a", "b"])] + + +def test_a_subscriber_without_a_cursor_starts_at_the_shared_progress(): + ledger = _Ledger(5, rows=[(4, "material", "a"), (5, "material", "b")]) + watch = LedgerWatch(ledger, interval=0.05) + received: list = [] + release = watch.subscribe(None, received.append) + try: + _wait(lambda: watch._subscribers) + assert received == [] # 不补读订阅前的账本 + ledger.add((6, "material", "c")) + _wait(lambda: received) + assert [(batch.after, batch.upto, batch.changed) for batch in received] == [(5, 6, ["c"])] + finally: + release() + + +# ── 装配:写入器在持有 Workflow Authority 的进程里 ──────────────────────── + + +def test_the_authority_writes_host_log_notices_and_material_notices(tmp_path, monkeypatch): + from unittest.mock import Mock + from uuid import uuid4 + + from unilabos.config.config import BasicConfig + from unilabos.protocol.materials import InventoryMutation, ResourceTemplateWrite + from unilabos.server.database import ServerDatabasePaths + from unilabos.server.edge_dispatch import EdgeControlService + from unilabos.server.services.materials.ledger_watch import ledger_watch + from unilabos.server.execution_composition import ( + reset_for_test, + setup_execution_backend, + setup_local_scheduler, + setup_materials_service, + ) + + paths = ServerDatabasePaths.resolve(tmp_path) + monkeypatch.setattr(BasicConfig, "backend", "hostlink") + monkeypatch.setattr(BasicConfig, "machine_name", "test-host") + monkeypatch.setattr(BasicConfig, "server_database_paths", paths) + try: + materials = setup_materials_service(database_paths=paths) + backend = setup_execution_backend(database_paths=paths) + workflow_service = setup_local_scheduler(backend=backend) + _wait(lambda: ledger_watch(materials)._subscribers) # 写入器常驻订阅物料账本 + + # Host 的日志通知经 runtime.v1 runtime_logs_changed 到达权威 + EdgeControlService(payload_client=Mock()).handle_message("runtime_logs_changed", {"source_ids": ["slave:a"]}) + _wait(lambda: _rows(workflow_service, "runtime.logs.changed")) + assert "slave:a" in _rows(workflow_service, "runtime.logs.changed")[0]["data"]["source_ids"] + + command = str(uuid4()) + materials.put_template( + InventoryMutation(command_uuid=command, effect_key=f"put_template:{command}", operation="put_template", + actor_type="test", actor_uuid="frontend-notices"), + ResourceTemplateWrite(name="notice_tpl", display_name="notice", class_name="Resource"), + ) + _wait(lambda: _rows(workflow_service, "material.changed")) + # 模板变化:列不准,整体重读;sequence 是物料账本末尾 + assert _rows(workflow_service, "material.changed")[0]["data"] == { + "sequence": materials.latest_ledger_sequence(), + } + finally: + reset_for_test() diff --git a/unilabos/server/api/runtime/events.py b/unilabos/server/api/runtime/events.py index 5e1634c46..cadb874fb 100644 --- a/unilabos/server/api/runtime/events.py +++ b/unilabos/server/api/runtime/events.py @@ -1,4 +1,4 @@ -"""复用 /events:持久工作流通知 + 瞬时日志失效通知,不混用游标。 +"""``/api/v1/events``:一个整数序列上的前端失效通知(工作流、物料、日志),每一帧都带 id。 订阅语义对齐 v1.0 ADR 0006(前端事件订阅):通知只表示 REST 状态失效,新页面经 REST 读取当前状态,不需要回放历史。 @@ -12,32 +12,27 @@ 保留窗口边界与事件页在同一 SQL 快照内读取,每页都检查,慢连接也不会被清理静默越过。 -事件名按 V1 合同输出(:func:`to_v1_event`):持久库里 dev 的细粒度事件 -``workflow.task|node_run|node_job|manual_confirmation|resource.changed`` 一律发成 -``workflow.runtime.changed``,原事件的种类放进 ``data.kind``(``task`` / ``node_run`` / -``node_job`` / ``manual_confirmation`` / ``resource``),原载荷字段保留。 -``workflow.authoring.changed`` 在库里就是 V1 名,原样发送:``@workflow`` 源码创作的状态迁移 -(``data.cause``),以及工作流定义的变化(``data.change``:``created`` / ``updated`` / ``deleted`` / -``graph_saved`` / ``published``),都与变更同一事务写入。游标与 ``stream.reset`` 协议不变。 - -物料失效:本进程持有物料权威时,物料账本前进就推一条**不带 id** 的 ``material.changed`` -(``data: {"sequence": <账本末尾序号>, "material_uuids": [...]}``),与日志通知一样不动工作流游标。 -``material_uuids`` 的语义: - -- 带这个键:恰好是这段账本里变了的物料(Site 的变化归到所属物料,拓扑边的变化归到两端物料), - 客户端只重读这些;**空列表就是没有物料变化**(这段账本只动了批次 / 预留),什么都不用重读, - ``sequence`` 照常前进; -- 不带这个键:列不准(模板变化、库被重置),整体重读。 - -账本由进程内唯一的共享轮询读(``server/services/materials/ledger_watch.py``),所有连接共用一份结果, -不占默认线程池。只维持这一条事件流的前端据此重读物料;要按账本 sequence 续传的客户端仍用 -``/api/v1/materials/events``(``materials.changed``)。 +所有通知都是 ``frontend_event`` 的行,同一个序列: + +- 事件名按 V1 合同输出(:func:`to_v1_event`):持久库里 dev 的细粒度事件 + ``workflow.task|node_run|node_job|manual_confirmation|resource.changed`` 一律发成 + ``workflow.runtime.changed``,原事件的种类放进 ``data.kind``(``task`` / ``node_run`` / + ``node_job`` / ``manual_confirmation`` / ``resource``),原载荷字段保留。 + ``workflow.authoring.changed`` 在库里就是 V1 名,原样发送:``@workflow`` 源码创作的状态迁移 + (``data.cause``),以及工作流定义的变化(``data.change``:``created`` / ``updated`` / ``deleted`` / + ``graph_saved`` / ``published``),都与变更同一事务写入。 +- ``material.changed``(``data: {"sequence": <物料账本末尾>, "material_uuids": [...]}``)与 + ``runtime.logs.changed``(``RuntimeLogNotice``)由权威进程的通知写入器合并、限速后写入 + (``server/services/runtime/workflow/frontend_notices.py``)。``material_uuids`` 带这个键:恰好是这段账本里 + 变了的物料,客户端只重读这些(空列表就是没有物料变化);不带:列不准,整体重读。``data.sequence`` 是物料账本 + 的序号,不是这条流的游标。 + +写入器写完一行会唤醒本进程的连接立即读;工作流事件按约 1 秒一轮读取。 """ from __future__ import annotations import asyncio -import json import time from typing import Any, Dict @@ -45,19 +40,16 @@ from fastapi import APIRouter, Header, Request from fastapi.responses import Response, StreamingResponse -from unilabos.protocol.runtime.logs import RuntimeLogNotice -from unilabos.server.services.materials.ledger_watch import LedgerBatch, LedgerWatch, ledger_watch from unilabos.server.api.envelope import WORKFLOW, envelope_router from unilabos.server.lifecycle import shutting_down -from unilabos.utils.log_notices import LOG_NOTICE_EVENT, log_notices, merge_notices +from unilabos.server.services.runtime.workflow.frontend_notices import MATERIAL_CHANGED_EVENT, appended +from unilabos.utils.log_notices import LOG_NOTICE_EVENT STREAM_RESET_EVENT = "stream.reset" #: V1 前端事件名(``/api/v1/events``) RUNTIME_CHANGED_EVENT = "workflow.runtime.changed" AUTHORING_CHANGED_EVENT = "workflow.authoring.changed" ERROR_HANDLING_CHANGED_EVENT = "station.error_handling.changed" -#: 物料账本前进的瞬时失效通知(无 id,不占工作流游标) -MATERIAL_CHANGED_EVENT = "material.changed" #: dev 持久事件名 → (V1 事件名, data.kind)。不在表里的事件名原样发送。 _V1_EVENTS: Dict[str, tuple[str, str | None]] = { @@ -82,45 +74,6 @@ def to_v1_event(event: Dict[str, Any]) -> Dict[str, Any]: return {**event, "event": name, "data": data} -def material_notices() -> LedgerWatch | None: - """本进程持有物料权威时返回它的共享账本轮询;Host 子进程等没有权威的进程返回 None。""" - - try: - from unilabos.server.execution_composition import get_materials_service - except ImportError: - return None - service = get_materials_service() - if service is None or not callable(getattr(service, "latest_ledger_sequence", None)): - return None - return ledger_watch(service) - - -def material_changed_frame(sequence: int, material_uuids: list[str] | None = None) -> str: - """不写 SSE id:Last-Event-ID 只表示工作流持久事件的序号。 - - ``material_uuids`` 为 None 时省略这个键,表示"列不准,整体重读";空列表表示没有物料变化。 - """ - - payload: Dict[str, Any] = {"sequence": sequence} - if material_uuids is not None: - payload["material_uuids"] = material_uuids - data = json.dumps(payload, separators=(",", ":")) - return f"event: {MATERIAL_CHANGED_EVENT}\ndata: {data}\n\n" - - -def _merge_material_batches(current: LedgerBatch | None, batch: LedgerBatch) -> LedgerBatch: - """连接来不及发时把多批合成一批:区间取并、物料取并;任一批列不准或重置就整体重读。""" - - if current is None: - return batch - changed = ( - None - if current.reset or batch.reset or current.changed is None or batch.changed is None - else sorted(set(current.changed) | set(batch.changed)) - ) - return LedgerBatch(after=current.after, upto=batch.upto, changed=changed, reset=current.reset or batch.reset) - - async def runtime_event_stream( request: Request, service=None, @@ -128,41 +81,23 @@ async def runtime_event_stream( *, watermark: bool = False, replay: bool = False, - materials: LedgerWatch | None = None, - material_cursor: int = 0, ): from unilabos.server.api.runtime.workflow import format_sse_event loop = asyncio.get_running_loop() - pending: asyncio.Queue[RuntimeLogNotice] = asyncio.Queue(maxsize=1) + wake = asyncio.Event() closed = False - material_batch: LedgerBatch | None = None - - def put_material(batch: LedgerBatch) -> None: - nonlocal material_batch - if not closed: - material_batch = _merge_material_batches(material_batch, batch) - def receive_material(batch: LedgerBatch) -> None: - # 共享轮询线程上调用:只把这一批交回事件循环 + def woken() -> None: + # 写入器线程上调用:只把唤醒交回事件循环 if not closed: - loop.call_soon_threadsafe(put_material, batch) - - def put(notice: RuntimeLogNotice): - if closed: - return - if pending.full(): - notice = merge_notices(pending.get_nowait(), notice) - pending.put_nowait(notice) - - def receive(notice: RuntimeLogNotice): - if not closed: - loop.call_soon_threadsafe(put, notice) + try: + loop.call_soon_threadsafe(wake.set) + except RuntimeError: # 事件循环已关闭 + pass - release = log_notices.subscribe(receive) - # 从基线之后订阅共享账本轮询:基线到共享进度之间由轮询线程补读,此后每批都分到这里 - release_materials = materials.subscribe(material_cursor, receive_material) if materials is not None else None - next_workflow = 0.0 + release = appended.subscribe(woken) + next_poll = 0.0 heartbeat = time.monotonic() + 15 try: yield "retry: 3000\n: connected\n\n" @@ -171,12 +106,8 @@ def receive(notice: RuntimeLogNotice): yield f"id: {cursor}\n\n" while not shutting_down() and not await request.is_disconnected(): now = time.monotonic() - if material_batch is not None: - # 账本前进了就发一次失效,列出这段区间里变了的物料;库被重置或模板变了不列,整体重读 - batch, material_batch = material_batch, None - yield material_changed_frame(batch.upto, None if batch.reset else batch.changed) - if now >= next_workflow: - next_workflow = now + 1 + if now >= next_poll: + next_poll = now + 1 if service is not None: oldest, latest, events = service.read_event_window(after_id=cursor, limit=101) reason = None @@ -190,27 +121,26 @@ def receive(notice: RuntimeLogNotice): # 无法续传:给出新水位,由客户端重读 REST 校准。 cursor = latest yield format_sse_event({"id": cursor, "event": STREAM_RESET_EVENT, "data": {"reason": reason}}) - next_workflow = now + next_poll = now continue for event in events[:100]: cursor = event["id"] yield format_sse_event(to_v1_event(event)) if len(events) > 100: - next_workflow = now + next_poll = now try: - notice = await asyncio.wait_for(pending.get(), timeout=max(.01, next_workflow - time.monotonic())) + await asyncio.wait_for(wake.wait(), timeout=max(.01, next_poll - time.monotonic())) except TimeoutError: if time.monotonic() >= heartbeat: yield ": keepalive\n\n" heartbeat = time.monotonic() + 15 continue - # 不写 SSE id:Last-Event-ID 继续只表示工作流持久事件的序号。 - yield f"event: {LOG_NOTICE_EVENT}\ndata: {notice.model_dump_json()}\n\n" + # 写入器刚追加了通知:马上读,不等下一轮 + wake.clear() + next_poll = 0.0 finally: closed = True release() - if release_materials is not None: - release_materials() def create_runtime_events_router(service=None) -> APIRouter: @@ -238,17 +168,8 @@ async def events( fresh = cursor is None if fresh: # 必须在发送响应头之前固定水位,客户端 onopen 后的 REST 补读才能覆盖 - # “快照 → 订阅”之间的变化。纯执行面的 Host 没有 Workflow Authority。 + # “快照 → 订阅”之间的变化。纯执行面的 Host 没有 Workflow Authority,也就没有这条序列。 cursor = service.latest_event_sequence() if service is not None else 0 - # 物料账本基线同样在响应头之前固定:onopen 后的 REST 补读覆盖此前的物料变化。基线在共享轮询的 - # 线程上读,不占默认线程池;读不到时这条连接不订阅物料失效,工作流事件照常 - materials = material_notices() - material_cursor = 0 - if materials is not None: - try: - material_cursor = await asyncio.wrap_future(materials.baseline()) - except Exception: # noqa: BLE001 - 物料库读不到不影响工作流事件流 - materials = None return StreamingResponse( runtime_event_stream( request, @@ -256,11 +177,22 @@ async def events( cursor, watermark=fresh and service is not None, replay=bool(value) and cursor == 0, - materials=materials, - material_cursor=material_cursor, ), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) return router + + +__all__ = [ + "AUTHORING_CHANGED_EVENT", + "ERROR_HANDLING_CHANGED_EVENT", + "LOG_NOTICE_EVENT", + "MATERIAL_CHANGED_EVENT", + "RUNTIME_CHANGED_EVENT", + "STREAM_RESET_EVENT", + "create_runtime_events_router", + "runtime_event_stream", + "to_v1_event", +] diff --git a/unilabos/server/execution_composition.py b/unilabos/server/execution_composition.py index 10673c2be..d3edc76a9 100644 --- a/unilabos/server/execution_composition.py +++ b/unilabos/server/execution_composition.py @@ -193,6 +193,7 @@ def setup_local_scheduler( execution_backend.result_bridges.append(scheduler) scheduler.start(recover=True) _start_event_retention(service) + _start_frontend_notices(service) _start_source_monitor(service) _workflow_service = service _scheduler = scheduler @@ -230,6 +231,32 @@ def _stop_event_retention() -> None: _event_retention = None +_frontend_notices: Any = None + + +def _start_frontend_notices(service: Any) -> None: + """本机 Workflow Authority 把物料账本与日志的失效通知写进 frontend_event,与工作流事件同一序列。 + + 物料通知只在本进程持有物料权威时写;日志通知包括经控制面 WS 中继来的 Host 通知。 + """ + + global _frontend_notices + if _frontend_notices is not None: + return + from unilabos.server.services.runtime.workflow.frontend_notices import FrontendNoticeWriter + + writer = FrontendNoticeWriter(service, materials=_materials) + writer.start() + _frontend_notices = writer + + +def _stop_frontend_notices() -> None: + global _frontend_notices + if _frontend_notices is not None: + _frontend_notices.stop() + _frontend_notices = None + + _source_monitor: Any = None @@ -475,7 +502,7 @@ def setup_execution_backend( from unilabos.utils.log_notices import log_notices # 复用 runtime.v1 控制连接;旧后端的 legacy result bridge 不订阅此通知。 - # 不落 durable outbox,避免日志噪声占用四库和调度事件序号。 + # 不落 Host 的 durable outbox(不占 edge_change 序号);权威收到后合并、限速写进它的 frontend_event。 _release_log_notices = log_notices.subscribe( lambda notice: control_client._queue_message({ "action": "runtime_logs_changed", "data": notice.model_dump(), @@ -511,8 +538,9 @@ def shutdown_backend_services() -> None: _scheduler.stop() if _backend is not None and _scheduler in _backend.result_bridges: _backend.result_bridges.remove(_scheduler) - # 先等后台线程(源码监视、事件清理)结束当前事务,再关闭共享的 runtime.db 连接。 + # 先等后台线程(源码监视、通知写入、事件清理)结束当前事务,再关闭共享的 runtime.db 连接。 _stop_source_monitor() + _stop_frontend_notices() _stop_event_retention() if _workflow_service is not None: _workflow_service.set_task_submitter(None) diff --git a/unilabos/server/services/materials/ledger_watch.py b/unilabos/server/services/materials/ledger_watch.py index c0c8b7156..55c766a07 100644 --- a/unilabos/server/services/materials/ledger_watch.py +++ b/unilabos/server/services/materials/ledger_watch.py @@ -1,7 +1,7 @@ """物料账本的共享轮询:一个物料权威一条专用线程,所有 SSE 连接共用它的结果。 -``/api/v1/events``(``material.changed``)与 ``/api/v1/materials/events``(``materials.changed``)都要知道 -账本前进了什么。以前每个连接每秒各读一次账本(还占着默认线程池,与 runtime.v1 控制 socket 的出站泵、 +``/api/v1/events`` 的 ``material.changed``(由权威进程的前端通知写入器订阅,合并后写进 ``frontend_event``) +与 ``/api/v1/materials/events``(``materials.changed``,按连接订阅)都要知道账本前进了什么。以前每个连接每秒各读一次账本(还占着默认线程池,与 runtime.v1 控制 socket 的出站泵、 edge 代理抢同一个池),标签页一多、碰上长写入,发往 Host 的消息就被拖慢。现在: - 只有一条专用线程读账本:有订阅者时每秒读一次末尾,有新条目就读出这一段(每批最多 @@ -200,8 +200,8 @@ def read() -> int: return self.call(read) - def subscribe(self, after: int, deliver: Deliver) -> Callable[[], None]: - """从 ``after`` 之后开始收到每一批账本变化;返回取消订阅的函数。""" + def subscribe(self, after: Optional[int], deliver: Deliver) -> Callable[[], None]: + """从 ``after`` 之后开始收到每一批账本变化;``after`` 为 None 时从共享进度开始。返回取消订阅的函数。""" with self._lock: self._next_token += 1 @@ -210,7 +210,7 @@ def subscribe(self, after: int, deliver: Deliver) -> Callable[[], None]: def register() -> None: if self._latest is None: self._latest = self.latest() - self._catch_up(after, deliver) + self._catch_up(self._latest if after is None else after, deliver) with self._lock: self._subscribers[token] = deliver diff --git a/unilabos/server/services/runtime/workflow/frontend_notices.py b/unilabos/server/services/runtime/workflow/frontend_notices.py new file mode 100644 index 000000000..636b4f605 --- /dev/null +++ b/unilabos/server/services/runtime/workflow/frontend_notices.py @@ -0,0 +1,239 @@ +"""前端失效通知写入器:物料账本与日志的通知写进 ``frontend_event``,与工作流事件共用一个序列。 + +``/api/v1/events`` 因此每一帧(水位、工作流、物料、日志、重置)都带同一个序列的整数 id:断线续传 +(``Last-Event-ID``)、超前 / 过期游标的 ``stream.reset`` 与保留清理对它们一视同仁。写入器只在持有 +Workflow Authority 的进程里运行(默认拓扑的权威进程、``--role backend``;单进程模式下就是这个进程), +由 ``server/execution_composition.py`` 随本机调度权威启停。 + +- **物料**:订阅本进程物料权威的共享账本轮询(``server/services/materials/ledger_watch.py``,约每秒读一次), + 账本每前进一批就并进待写槽,写一行 ``material.changed``,``data`` 为 + ``{"sequence": <账本末尾>, "material_uuids": [...]}``。带 ``material_uuids``:恰好是这段账本里变了的物料 + (``[]`` 表示只动了批次 / 预留,没有物料要重读);不带:列不准(模板变化、库被重置,或超过 + :data:`MATERIAL_UUIDS_LIMIT` 个),客户端整体重读。物料权威不在本进程时不写物料通知。 +- **日志**:订阅进程内日志通知中心(``utils/log_notices.py``)。Host 子进程(以及 ``--address`` 接入的 Host) + 的通知经 runtime.v1 ``runtime_logs_changed`` 到达权威,由 ``EdgeControlService`` 发布到同一个通知中心; + Host 上下线时权威自己也发一条。合并后写一行 ``runtime.logs.changed``,``data`` 为 ``RuntimeLogNotice``。 +- **合并与限速**:两类各自每 :data:`NOTICE_INTERVAL_S` 秒至多写一行。空闲后的第一条立即写;间隔内到达的 + 全部并进下一行(物料取并集,任一批列不准就整体重读;日志合并来源)。一阵日志刷屏因此每秒最多一行。 +- **唤醒**:写完一行后唤醒本进程的 SSE 连接立即读(:data:`appended`),不等它们下一轮轮询。 +- **续写**:启动时从最新一条 ``material.changed`` 记下的账本序号之后续读,停机前没来得及写的那段账本也会补写; + 账本比记下的还短(库被重置)写一行整体重读。保留窗口里没有物料通知时从当前账本末尾开始。 +- 写失败只记日志(写入器线程的日志不触发日志通知),待写内容保留,约 1 秒后重试。 +""" + +from __future__ import annotations + +import logging +import threading +import time +from typing import Any, Callable, Dict, Optional + +from unilabos.protocol.runtime.logs import RuntimeLogNotice +from unilabos.server.services.materials.ledger_watch import LedgerBatch, LedgerWatch, ledger_watch +from unilabos.utils.log_notices import LOG_NOTICE_EVENT, NOTICE_WRITER_THREAD, log_notices, merge_notices + +logger = logging.getLogger(__name__) + +#: 物料账本前进的失效通知(V1 名) +MATERIAL_CHANGED_EVENT = "material.changed" +#: 物料 / 日志通知各自的最小写入间隔(秒) +NOTICE_INTERVAL_S = 1.0 +#: ``material_uuids`` 最多列这么多个;再多就省略这个键,客户端整体重读比逐个重读更省 +MATERIAL_UUIDS_LIMIT = 500 +_RETRY_S = 1.0 + + +def merge_material_batches(current: Optional[LedgerBatch], batch: LedgerBatch) -> LedgerBatch: + """把多批合成一批:区间取并、物料取并;任一批列不准或重置就整体重读。``current`` 在前。""" + + if current is None: + return batch + changed = ( + None + if current.reset or batch.reset or current.changed is None or batch.changed is None + else sorted(set(current.changed) | set(batch.changed)) + ) + return LedgerBatch(after=current.after, upto=batch.upto, changed=changed, reset=current.reset or batch.reset) + + +def material_notice_data(batch: LedgerBatch) -> Dict[str, Any]: + """一行 ``material.changed`` 的 ``data``;列不准、重置或列不下时省略 ``material_uuids``。""" + + data: Dict[str, Any] = {"sequence": batch.upto} + if not batch.reset and batch.changed is not None and len(batch.changed) <= MATERIAL_UUIDS_LIMIT: + data["material_uuids"] = list(batch.changed) + return data + + +class _Appended: + """写入器写完一行后通知本进程的 SSE 连接;回调在写入器线程上调用,必须很快返回。""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._listeners: set[Callable[[], None]] = set() + + def subscribe(self, listener: Callable[[], None]) -> Callable[[], None]: + with self._lock: + self._listeners.add(listener) + + def release() -> None: + with self._lock: + self._listeners.discard(listener) + + return release + + def notify(self) -> None: + with self._lock: + listeners = tuple(self._listeners) + for listener in listeners: + try: + listener() + except Exception: # noqa: BLE001 - 唤醒只是提前读,丢了下一轮轮询照样读到 + pass + + +#: 本进程写入器追加通知后的唤醒信号(``/api/v1/events`` 的连接订阅它) +appended = _Appended() + + +class FrontendNoticeWriter: + """把物料与日志通知合并、限速后写进 ``frontend_event``(见模块说明)。""" + + def __init__( + self, + store: Any, + *, + materials: Any = None, + hub: Any = log_notices, + interval: float = NOTICE_INTERVAL_S, + ) -> None: + self._store = store + # 物料权威服务(取它的共享账本轮询)或直接给一个 LedgerWatch;None 表示物料权威不在本进程 + self._materials = materials + self._hub = hub + self._interval = interval + self._lock = threading.Lock() + self._wake = threading.Event() + self._stop = threading.Event() + self._material: Optional[LedgerBatch] = None + self._log: Optional[RuntimeLogNotice] = None + self._next_material = 0.0 + self._next_log = 0.0 + self._failures = 0 + self._releases: list[Callable[[], None]] = [] + self._thread: Optional[threading.Thread] = None + + # ── 生命周期 ───────────────────────────────────────────────────── + + def start(self) -> None: + if self._thread is not None: + return + self._thread = threading.Thread(target=self._run, name=NOTICE_WRITER_THREAD, daemon=True) + self._thread.start() + self._releases.append(self._hub.subscribe(self._receive_log)) + if self._materials is not None: + watch = self._materials if isinstance(self._materials, LedgerWatch) else ledger_watch(self._materials) + self._releases.append(watch.subscribe(self._material_cursor(), self._receive_material)) + + def stop(self) -> None: + """停止订阅与写入线程;没写出去的物料区间下次启动按记下的账本序号补写。""" + + for release in self._releases: + release() + self._releases.clear() + self._stop.set() + self._wake.set() + if self._thread is not None: + self._thread.join(timeout=2) + self._thread = None + + def _material_cursor(self) -> Optional[int]: + """最新一条物料通知记下的账本序号;保留窗口里没有时返回 None(从当前账本末尾开始)。""" + + try: + data = self._store.latest_event_data(MATERIAL_CHANGED_EVENT) + except Exception as exc: # noqa: BLE001 - 读不到就从当前账本末尾开始,不挡权威启动 + logger.warning("读取上次的物料通知失败,从当前账本末尾开始:%s", exc) + return None + sequence = data.get("sequence") if isinstance(data, dict) else None + if isinstance(sequence, int) and not isinstance(sequence, bool) and sequence >= 0: + return sequence + return None + + # ── 收通知(在别的线程上调用,只并进待写槽) ─────────────────────── + + def _receive_material(self, batch: LedgerBatch) -> None: + with self._lock: + self._material = merge_material_batches(self._material, batch) + self._wake.set() + + def _receive_log(self, notice: RuntimeLogNotice) -> None: + with self._lock: + self._log = notice if self._log is None else merge_notices(self._log, notice) + self._wake.set() + + # ── 写入线程 ───────────────────────────────────────────────────── + + def _append(self, event: str, data: Dict[str, Any]) -> bool: + try: + self._store.append_frontend_event(event, data) + except Exception as exc: # noqa: BLE001 - 待写内容保留,稍后重试 + self._failures += 1 + if self._failures == 1 or self._failures % 60 == 0: + logger.warning("写前端通知 %s 失败(第 %s 次),稍后重试:%s", event, self._failures, exc) + return False + self._failures = 0 + return True + + def _run(self) -> None: + timeout: Optional[float] = None + while True: + self._wake.wait(timeout) + self._wake.clear() + if self._stop.is_set(): + return + now = time.monotonic() + with self._lock: + material = self._material if now >= self._next_material else None + if material is not None: + self._material = None + log = self._log if now >= self._next_log else None + if log is not None: + self._log = None + wrote = False + if material is not None: + if self._append(MATERIAL_CHANGED_EVENT, material_notice_data(material)): + self._next_material = now + self._interval + wrote = True + else: + with self._lock: + self._material = merge_material_batches(material, self._material) if self._material else material + self._next_material = now + _RETRY_S + if log is not None: + if self._append(LOG_NOTICE_EVENT, log.model_dump(mode="json")): + self._next_log = now + self._interval + wrote = True + else: + with self._lock: + self._log = log if self._log is None else merge_notices(log, self._log) + self._next_log = now + _RETRY_S + if wrote: + appended.notify() + with self._lock: + waits = [ + deadline - now + for pending, deadline in ((self._material, self._next_material), (self._log, self._next_log)) + if pending is not None + ] + timeout = max(0.0, min(waits)) if waits else None + + +__all__ = [ + "FrontendNoticeWriter", + "MATERIAL_CHANGED_EVENT", + "MATERIAL_UUIDS_LIMIT", + "NOTICE_INTERVAL_S", + "appended", + "material_notice_data", + "merge_material_batches", +] diff --git a/unilabos/server/services/runtime/workflow/store.py b/unilabos/server/services/runtime/workflow/store.py index b60fdeddf..a55c14627 100644 --- a/unilabos/server/services/runtime/workflow/store.py +++ b/unilabos/server/services/runtime/workflow/store.py @@ -3837,6 +3837,25 @@ def latest_event_sequence(self) -> int: ).fetchone() return int(row[0]) + def append_frontend_event(self, event: str, data: Dict[str, Any]) -> int: + """在独立事务里追加一条前端失效通知,返回它的序号。 + + 与工作流事件同一张表、同一个序列:``/api/v1/events`` 的每一帧都按这个序号续传、重置与清理。 + """ + + with self.transaction() as conn: + return self._append_event(conn, event=event, data=data, now=utc_now()) + + def latest_event_data(self, event: str) -> Optional[Dict[str, Any]]: + """某类通知最新一条的 ``data``;保留窗口里没有这类通知时返回 None。""" + + with self._lock: + row = self._conn.execute( + "SELECT payload FROM frontend_event WHERE type = ? ORDER BY sequence DESC LIMIT 1", + (event,), + ).fetchone() + return None if row is None else _load(row["payload"], {}) + @staticmethod def _append_event( conn: sqlite3.Connection, diff --git a/unilabos/utils/log_notices.py b/unilabos/utils/log_notices.py index c98d193fe..69cdcd61b 100644 --- a/unilabos/utils/log_notices.py +++ b/unilabos/utils/log_notices.py @@ -9,6 +9,10 @@ from unilabos.protocol.runtime.logs import RuntimeLogNotice LOG_NOTICE_EVENT = "runtime.logs.changed" +#: 权威进程把通知写进 frontend_event 的线程(``server/services/runtime/workflow/frontend_notices.py``) +NOTICE_WRITER_THREAD = "FrontendNotices" +#: 这些线程自己的日志不再触发通知,否则「通知 → 写失败日志 → 再通知」会形成自激循环 +_QUIET_THREADS = frozenset({"RuntimeLogNotices", NOTICE_WRITER_THREAD}) def merge_notices(left: RuntimeLogNotice, right: RuntimeLogNotice) -> RuntimeLogNotice: @@ -95,7 +99,7 @@ class LogAppendHandler(logging.Handler): """在 FileHandler 写完后标记本进程;通知/读取自身的传输日志不再触发通知。""" def emit(self, record: logging.LogRecord) -> None: - if _local_source is None or record.threadName == "RuntimeLogNotices": + if _local_source is None or record.threadName in _QUIET_THREADS: return if record.name.startswith(("uvicorn", "websockets", "httpx", "httpcore", "urllib3", "unilabos.comm")): return From 40d08a7ac104e8961ed9bf0910a4e05c12f16037 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:53:35 +0800 Subject: [PATCH 48/59] fix(monitor): /monitor/events resumes from Last-Event-ID without skipping A reconnect with Last-Event-ID continues after that sequence instead of replaying the last 40 events. A cursor ahead of the latest sequence or behind the retention window gets stream.reset with the new watermark. Each poll reads the retention bounds and one page of frontend_event rows in one SQL snapshot and advances the cursor only to the highest row it scanned, so rows committed during a scan and rows past a page are no longer skipped; a full page is followed by the next page at once. Rows outside the selected channels advance an id-only watermark frame, and a fresh connection gets one after the backlog. The stream ends when the server starts shutting down. --- tests/server/test_monitor_events_resume.py | 211 ++++++++++++++++++ tests/server/test_server_monotonic.py | 14 +- unilabos/server/api/runtime/scheduling_v1.py | 86 +++++-- .../services/runtime/workflow/timeline.py | 65 +++++- 4 files changed, 345 insertions(+), 31 deletions(-) create mode 100644 tests/server/test_monitor_events_resume.py diff --git a/tests/server/test_monitor_events_resume.py b/tests/server/test_monitor_events_resume.py new file mode 100644 index 000000000..2cf487ede --- /dev/null +++ b/tests/server/test_monitor_events_resume.py @@ -0,0 +1,211 @@ +"""/api/v1/monitor/events 的续传:Last-Event-ID、stream.reset、按页扫描,每一帧都带 id。 + +TestClient 会把流式响应缓冲到结束,这里直接驱动 ASGI 应用读取前几帧。 +""" + +from __future__ import annotations + +import asyncio +import json + +import pytest +from fastapi import FastAPI + +from unilabos.server.api.runtime.scheduling_v1 import create_scheduling_router +from unilabos.server.services.runtime.workflow.service import WorkflowService + +JOB_EVENT = "workflow.node_job.changed" # 投影到 action 通道 + + +def _app(store) -> FastAPI: + app = FastAPI() + app.include_router(create_scheduling_router(store, get_scheduler=lambda: None)) + return app + + +def _append(service: WorkflowService, count: int, event: str = JOB_EVENT) -> None: + for _ in range(count): + service.append_frontend_event(event, {"status": "running"}) + + +async def _read(app, headers: list[tuple[bytes, bytes]], steps, query: bytes = b"") -> str: + """依次等待 steps 中每个 (predicate, action):文本满足 predicate 后执行 action。""" + + chunks: list[str] = [] + changed = asyncio.Event() + disconnect = asyncio.Event() + + async def receive(): + await disconnect.wait() + return {"type": "http.disconnect"} + + async def send(message): + if message["type"] == "http.response.body": + chunks.append(message.get("body", b"").decode("utf-8")) + changed.set() + + scope = { + "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", + "scheme": "http", "path": "/api/v1/monitor/events", "raw_path": b"/api/v1/monitor/events", + "query_string": query, "root_path": "", "headers": headers, + "client": ("127.0.0.1", 1), "server": ("testserver", 80), + } + task = asyncio.create_task(app(scope, receive, send)) + try: + for predicate, action in steps: + while not predicate("".join(chunks)): + changed.clear() + await asyncio.wait_for(changed.wait(), 5.0) + if action is not None: + await asyncio.to_thread(action) + finally: + disconnect.set() + await asyncio.wait_for(task, 5.0) + return "".join(chunks) + + +def _ids(text: str) -> list[int]: + """事件帧的 id(不含只带 id 的水位帧)。""" + + return [int(block.split("\n", 1)[0][4:]) for block in text.split("\n\n") + if block.startswith("id: ") and "\nevent:" in block] + + +@pytest.fixture +def service(monkeypatch): + from unilabos.server.api.runtime import scheduling_v1 + + monkeypatch.setattr(scheduling_v1, "shutting_down", lambda: False) + workflow = WorkflowService(":memory:") + yield workflow + workflow.close() + + +def test_reconnect_resumes_after_last_event_id_without_replaying_the_backlog(service) -> None: + _append(service, 50) + app = _app(service) + first = asyncio.run(_read(app, [], [(lambda body: "id: 50\nevent:" in body, None)])) + assert _ids(first) == list(range(11, 51)) # 首连:最近 40 条 + _append(service, 3) + again = asyncio.run(_read(app, [(b"last-event-id", b"50")], [(lambda body: "id: 53\nevent:" in body, None)])) + assert _ids(again) == [51, 52, 53] # 不重放、不重复 + + +def test_more_than_one_page_is_delivered_in_full(service) -> None: + app = _app(service) + text = asyncio.run(_read(app, [], [ + (lambda body: "connected" in body, lambda: _append(service, 450)), + (lambda body: "id: 450\nevent:" in body, None), + ], query=b"backlog=0")) + assert _ids(text) == list(range(1, 451)) + + +def test_rows_outside_the_channels_still_advance_the_cursor(service) -> None: + _append(service, 1) + _append(service, 2, event="material.changed") + app = _app(service) + text = asyncio.run(_read(app, [(b"last-event-id", b"0")], [(lambda body: "id: 3\n\n" in body, None)])) + assert _ids(text) == [1] + # 扫过的其他通知只推进水位:客户端断线后从 3 之后续传,不再重扫 + assert text.index("id: 1\nevent:") < text.index("id: 3\n\n") + + +class _Rows: + def __init__(self, rows) -> None: + self._rows = rows + + def fetchall(self): + return self._rows + + def fetchone(self): + return self._rows[0] if self._rows else None + + +class _RacingStore: + """扫描读完之后、下一次读之前提交一行:模拟另一个事务恰好在扫描期间提交。""" + + def __init__(self, service: WorkflowService) -> None: + self.service = service + self.armed = False + self.fired = False + + @property + def write_lock(self): + return self.service.write_lock + + @property + def connection(self): + return self + + def execute(self, sql: str, params=()): + rows = self.service.connection.execute(sql, params).fetchall() + if self.armed and not self.fired and "sequence >" in sql: + self.fired = True + _append(self.service, 1) + return _Rows(rows) + + +def test_a_row_committed_during_a_scan_is_not_skipped(service) -> None: + _append(service, 1) + store = _RacingStore(service) + app = _app(store) + text = asyncio.run(_read(app, [], [ + (lambda body: "id: 1\nevent:" in body, lambda: setattr(store, "armed", True)), + (lambda body: "id: 2\nevent:" in body, None), + ])) + assert store.fired and _ids(text) == [1, 2] + + +def _reset(text: str) -> tuple[str, dict]: + block = next(item for item in text.split("\n\n") if "event: stream.reset" in item) + return block.split("\n", 1)[0], json.loads(block.split("data: ", 1)[1]) + + +def test_cursor_behind_retention_resets_as_expired(service) -> None: + _append(service, 5) + service.prune_frontend_events(before="0001-01-01T00:00:00.000000Z", max_count=2, batch_size=1000) + app = _app(service) + text = asyncio.run(_read(app, [(b"last-event-id", b"1")], [ + (lambda body: "event: stream.reset" in body, lambda: _append(service, 1)), + (lambda body: "id: 6\nevent:" in body, None), + ])) + assert _reset(text) == ("id: 5", {"reason": "cursor_expired"}) + assert _ids(text) == [5, 6] # 重置帧本身带新水位,之后照常推送,不回放 4、5 + + +def test_cursor_ahead_resets_to_the_latest(service) -> None: + _append(service, 3) + app = _app(service) + text = asyncio.run(_read(app, [(b"last-event-id", b"99")], [ + (lambda body: "event: stream.reset" in body, lambda: _append(service, 1)), + (lambda body: "id: 4\nevent:" in body, None), + ])) + assert _reset(text) == ("id: 3", {"reason": "cursor_ahead"}) + + +def test_cursor_at_the_window_edge_resumes_without_reset(service) -> None: + _append(service, 5) + service.prune_frontend_events(before="0001-01-01T00:00:00.000000Z", max_count=2, batch_size=1000) + app = _app(service) + text = asyncio.run(_read(app, [(b"last-event-id", b"3")], [(lambda body: "id: 5\nevent:" in body, None)])) + assert "stream.reset" not in text and _ids(text) == [4, 5] + + +def test_invalid_cursor_is_rejected() -> None: + from fastapi.testclient import TestClient + + workflow = WorkflowService(":memory:") + try: + with TestClient(_app(workflow)) as client: + response = client.get("/api/v1/monitor/events", headers={"Last-Event-ID": "abc"}) + assert response.status_code == 200 and response.json()["code"] == 1000 + finally: + workflow.close() + + +def test_fresh_connection_sets_a_watermark_past_the_backlog(service) -> None: + _append(service, 2) + _append(service, 1, event="material.changed") + app = _app(service) + text = asyncio.run(_read(app, [], [(lambda body: "id: 3\n\n" in body, None)])) + assert _ids(text) == [1, 2] diff --git a/tests/server/test_server_monotonic.py b/tests/server/test_server_monotonic.py index ce8a0d3f7..d72fcebf6 100644 --- a/tests/server/test_server_monotonic.py +++ b/tests/server/test_server_monotonic.py @@ -49,14 +49,13 @@ class _QuietTimeline: def __init__(self, _service) -> None: pass - def backlog(self, _channels, _count): - return [] + def monitor_backlog(self, _channels, _count): + return 0, [] - def latest_sequence(self) -> int: - return 0 + def monitor_window(self, *, after, channels): + from unilabos.server.services.runtime.workflow.timeline import MonitorWindow - def monitor_events(self, *, after, channels): - return [] + return MonitorWindow(oldest=0, latest=0, scanned=after) class _Request: @@ -70,7 +69,7 @@ def test_monitor_stream_keepalive_ignores_forward_wall_clock_jump(monkeypatch) - endpoint = next(route.endpoint for route in router.routes if route.path.endswith("/monitor/events")) async def next_chunk_after_jump(): - response = await endpoint(_Request(), channels="", backlog=0, follow=True) + response = await endpoint(_Request(), channels="", backlog=0, follow=True, last_event_id=None) stream = response.body_iterator async def next_chunk(): @@ -78,6 +77,7 @@ async def next_chunk(): try: assert (await next_chunk()).startswith("retry:") + assert await next_chunk() == "id: 0\n\n" # 首连的水位帧 pending = asyncio.get_running_loop().create_task(next_chunk()) # 先让事件流进入轮询循环、记下上次保活时间,再让墙钟前跳超过 15 s 的保活间隔; # 单调时钟此时才过去不到 2 s diff --git a/unilabos/server/api/runtime/scheduling_v1.py b/unilabos/server/api/runtime/scheduling_v1.py index 292407c8c..a56ed1aca 100644 --- a/unilabos/server/api/runtime/scheduling_v1.py +++ b/unilabos/server/api/runtime/scheduling_v1.py @@ -1,5 +1,6 @@ """V1 调度观测路由:``POST /reschedule``、``GET /timeline``、``GET /scheduler/time-plan``、 -``GET /monitor/events``(SSE)、``GET /monitor/snapshot``。口径见 ``services/runtime/workflow/timeline.py``。""" +``GET /monitor/events``(SSE,按 ``frontend_event`` 序号续传)、``GET /monitor/snapshot``。 +口径见 ``services/runtime/workflow/timeline.py``。""" from __future__ import annotations @@ -9,11 +10,13 @@ import time from typing import Any, Callable, Dict, Literal, Optional -from fastapi import APIRouter, Query, Request +from fastapi import APIRouter, Header, Query, Request from fastapi.responses import StreamingResponse from pydantic import BaseModel, ConfigDict, Field -from unilabos.server.api.envelope import GENERIC, SERVICE_UNAVAILABLE, ApiError, envelope_router +from unilabos.server.api.envelope import GENERIC, INVALID_PARAMETER, SERVICE_UNAVAILABLE, ApiError, envelope_router +from unilabos.server.api.runtime.events import STREAM_RESET_EVENT +from unilabos.server.lifecycle import shutting_down from unilabos.server.services.runtime.workflow.timeline import CHANNELS, ExecutionTimeline @@ -84,38 +87,91 @@ async def monitor_events( channels: str = Query(default=""), backlog: int = Query(default=40), follow: bool = Query(default=True), + last_event_id: Optional[str] = Header( + default=None, + alias="Last-Event-ID", + description="不填时先回放最近 backlog 条;填上次收到的 id 从其之后续传,不回放。", + ), ) -> StreamingResponse: - """``channels`` 逗号分隔过滤(缺省全部);先回放最近 ``backlog`` 条,再推新事件。""" + """``channels`` 逗号分隔过滤(缺省全部)。每一帧都带 ``frontend_event`` 的序号作 id。 + + - 首连(无 ``Last-Event-ID``):回放最近 ``backlog`` 条,跟随时再发一个只含 ``id`` 的水位帧 + (回放时的最新序号,与回放同一把锁内读出),之后推新事件; + - 重连带 ``Last-Event-ID``:从该序号之后续传,不回放、不重复;游标大于最新序号(``cursor_ahead``)或 + 早于保留窗口(``cursor_expired``)时发 ``stream.reset``(``id`` 为新水位,连接保持,客户端重读 + ``/monitor/snapshot``); + - 跟随时按页扫描(每页 ``MONITOR_PAGE`` 行,读满马上读下一页),游标只推进到实际扫过的最大序号: + 扫描期间提交的、超过一页的都不会跳过;扫过的其他通知只推进水位(只含 ``id`` 的帧)。 + """ + + from unilabos.server.api.runtime.workflow import _GO_WHITE_SPACE, _parse_non_negative_int64_decimal requested = {item.strip() for item in channels.split(",") if item.strip()} selected = tuple(sorted((requested & set(CHANNELS)) or CHANNELS)) - replay = timeline.backlog(selected, max(0, min(backlog, 200))) - cursor = timeline.latest_sequence() + value = (last_event_id if isinstance(last_event_id, str) else "").strip(_GO_WHITE_SPACE) + try: + resume = _parse_non_negative_int64_decimal(value) if value else None + except ValueError: + raise ApiError(INVALID_PARAMETER, "invalid Last-Event-ID") from None + replay: list[Dict[str, Any]] = [] + if resume is None: + # 在发送响应头之前固定回放与水位:客户端 onopen 后的快照补读覆盖此前的变化 + cursor, replay = await asyncio.to_thread(timeline.monitor_backlog, selected, max(0, min(backlog, 200))) + else: + cursor = resume def frame(event: Dict[str, Any]) -> str: payload = json.dumps(event, ensure_ascii=False, default=str) return f"id: {event['seq']}\nevent: {event['channel']}\ndata: {payload}\n\n" + def reset(reason: str) -> str: + return f"id: {cursor}\nevent: {STREAM_RESET_EVENT}\ndata: {json.dumps({'reason': reason})}\n\n" + async def stream(): nonlocal cursor yield f"retry: 3000\n: connected channels={','.join(selected)}\n\n" + # 客户端已持有的游标:续传时就是它;首连时回放完再补一个水位帧 + sent = cursor if resume is not None else None for event in replay: yield frame(event) - if not follow: - return + sent = event["seq"] + if resume is None: + if not follow: + return + if sent != cursor: + yield f"id: {cursor}\n\n" + sent = cursor last_beat = time.monotonic() - while not await request.is_disconnected(): - events = await asyncio.to_thread(timeline.monitor_events, after=cursor, channels=selected) - latest = await asyncio.to_thread(timeline.latest_sequence) - for event in events: + while not shutting_down() and not await request.is_disconnected(): + window = await asyncio.to_thread(timeline.monitor_window, after=cursor, channels=selected) + reason = None + if cursor > window.latest: + reason = "cursor_ahead" + elif cursor < window.oldest - 1: + reason = "cursor_expired" + if reason is not None: + # 无法续传:给出新水位,客户端重读快照 + cursor = sent = window.latest + yield reset(reason) + last_beat = time.monotonic() + continue + for event in window.events: yield frame(event) - cursor = max([cursor, latest, *[event["seq"] for event in events]]) - if events: + sent = event["seq"] + cursor = window.scanned + if sent != cursor: + yield f"id: {cursor}\n\n" + sent = cursor + last_beat = time.monotonic() + elif window.events: last_beat = time.monotonic() elif time.monotonic() - last_beat > 15: yield ": keepalive\n\n" last_beat = time.monotonic() - await asyncio.sleep(0.4) + if not window.more: + if not follow: + return + await asyncio.sleep(0.4) return StreamingResponse(stream(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) diff --git a/unilabos/server/services/runtime/workflow/timeline.py b/unilabos/server/services/runtime/workflow/timeline.py index bb4019f5c..17cb89aee 100644 --- a/unilabos/server/services/runtime/workflow/timeline.py +++ b/unilabos/server/services/runtime/workflow/timeline.py @@ -12,12 +12,15 @@ ``estimator`` 给出实测统计与兜底秒数。 - ``/monitor/*``:V1 进程内四通道总线(material / device / action / scheduler)在 dev 上以持久 前端通知(``frontend_event``)为唯一来源投影:作业变化 → action,任务 / 工站变化 → scheduler, - 资源占用变化 → device;物料变化在 materials.db 的独立事件流里,这里不复制(material 通道为空)。 + 资源占用变化 → device。``frontend_event`` 里的物料 / 日志失效通知(``material.changed`` / + ``runtime.logs.changed``)不是 V1 material 通道的库存领域事件,不投影(material 通道为空),只算扫过。 + 监控流按 ``frontend_event`` 的序号续传(:meth:`ExecutionTimeline.monitor_window`)。 """ from __future__ import annotations import time +from dataclasses import dataclass, field from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Sequence @@ -27,6 +30,19 @@ CHANNELS = ("material", "device", "action", "scheduler") NO_ENGINE_TIME_PLAN = {"enabled": False, "algorithm": "stable-ready-order"} _IN_FLIGHT = ("dispatched", "running", "cancel_requested") +#: 监控流一次扫描最多读的通知行数(任何通道都算);读满就马上读下一页 +MONITOR_PAGE = 200 + + +@dataclass(frozen=True) +class MonitorWindow: + """一次扫描:保留窗口边界、实际扫到的最大序号、其中属于所选通道的事件、后面是否还有。""" + + oldest: int + latest: int + scanned: int + events: List[Dict[str, Any]] = field(default_factory=list) + more: bool = False def _epoch(value: Optional[str]) -> Optional[float]: @@ -149,17 +165,48 @@ def monitor_event(row) -> Optional[Dict[str, Any]]: return {"seq": row["sequence"], "ts": _epoch(row["create_time"]) or 0.0, "channel": channel, "type": kind, "data": data} - def monitor_events(self, *, after: int = 0, channels: Optional[Iterable[str]] = None, - limit: int = 200) -> List[Dict[str, Any]]: + def monitor_window(self, *, after: int, channels: Optional[Iterable[str]] = None, + limit: int = MONITOR_PAGE) -> MonitorWindow: + """同一条 SQL 快照内读保留窗口边界与 ``after`` 之后的一页通知(按行数分页,不按事件数)。 + + ``scanned`` 是这一页实际扫到的最大序号(没有行时为 ``after``),游标只推进到它:扫描与“最新序号” + 不分两次读,扫描期间提交的通知留给下一页;页里不属于所选通道的通知也算扫过。 + """ + wanted = set(channels or CHANNELS) with self._store.write_lock: rows = self._store.connection.execute( - "SELECT sequence, type, payload, create_time FROM frontend_event WHERE sequence > ? " - "ORDER BY sequence LIMIT ?", - (after, max(1, limit) * 4), + """ + WITH bounds AS ( + SELECT + COALESCE((SELECT MIN(sequence) FROM frontend_event), 0) AS window_oldest, + COALESCE((SELECT MAX(sequence) FROM frontend_event), 0) AS window_latest + ), page AS ( + SELECT sequence, type, payload, create_time FROM frontend_event + WHERE sequence > ? ORDER BY sequence LIMIT ? + ) + SELECT bounds.window_oldest, bounds.window_latest, page.* + FROM bounds LEFT JOIN page ON 1 = 1 + ORDER BY page.sequence + """, + (after, max(1, limit)), ).fetchall() - events = [event for row in rows if (event := self.monitor_event(row)) and event["channel"] in wanted] - return events[:limit] + page = [row for row in rows if row["sequence"] is not None] + return MonitorWindow( + oldest=int(rows[0]["window_oldest"]), + latest=int(rows[0]["window_latest"]), + scanned=int(page[-1]["sequence"]) if page else after, + events=[event for row in page if (event := self.monitor_event(row)) and event["channel"] in wanted], + more=len(page) >= max(1, limit), + ) + + def monitor_backlog(self, channels: Sequence[str], count: int) -> tuple[int, List[Dict[str, Any]]]: + """首连:当前最新序号与最近 ``count`` 条事件,在同一把写锁内读出,两次读之间不会插进提交。""" + + with self._store.write_lock: + latest = int(self._store.connection.execute( + "SELECT COALESCE(MAX(sequence), 0) FROM frontend_event").fetchone()[0]) + return latest, self.backlog(channels, count) def recent(self, channel: str, count: int = 40) -> List[Dict[str, Any]]: with self._store.write_lock: @@ -230,4 +277,4 @@ def snapshot(self, *, reschedule_count: int = 0) -> Dict[str, Any]: } -__all__ = ["CHANNELS", "ExecutionTimeline", "NO_ENGINE_TIME_PLAN"] +__all__ = ["CHANNELS", "ExecutionTimeline", "MONITOR_PAGE", "MonitorWindow", "NO_ENGINE_TIME_PLAN"] From 019a421c9e1ab14022dfb3b5e116737a2db49666 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:55:23 +0800 Subject: [PATCH 49/59] fix(mcp): GET /mcp answers 405 instead of opening an id-less stream The stateless Streamable HTTP endpoint never pushes server-initiated messages, and its standalone SSE stream had no event ids and no event store, so a dropped connection lost whatever it would have carried. GET now returns 405 with Allow: POST, as the MCP transport allows; POST JSON responses are unchanged. --- tests/server/test_mcp.py | 50 +++++++++++++++++++++++++++++++++ unilabos/server/mcp/__init__.py | 10 ++++++- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/tests/server/test_mcp.py b/tests/server/test_mcp.py index ef3bb70dc..4781cb16e 100644 --- a/tests/server/test_mcp.py +++ b/tests/server/test_mcp.py @@ -137,6 +137,56 @@ def test_invalid_input_never_reaches_http(application): assert result["isError"], (name, result) +def test_get_opens_no_stream_and_answers_405(application): + """GET /mcp 不开 Streamable HTTP 的独立 SSE 流(那条流没有 id、也没有事件存储,断线即丢):回 405。 + + 直接驱动 ASGI:旧行为是一条不会结束的 SSE 流,TestClient 会一直缓冲下去;这里只看响应头。 + """ + + async def scenario(): + async with application.router.lifespan_context(application): + started: asyncio.Future = asyncio.get_running_loop().create_future() + disconnect = asyncio.Event() + + async def receive(): + await disconnect.wait() + return {"type": "http.disconnect"} + + async def send(message): + if message["type"] == "http.response.start" and not started.done(): + started.set_result(message) + + scope = { + "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", + "scheme": "http", "path": "/mcp", "raw_path": b"/mcp", "query_string": b"", "root_path": "", + "headers": [(b"host", b"127.0.0.1"), (b"accept", b"application/json, text/event-stream")], + "client": ("127.0.0.1", 50000), "server": ("127.0.0.1", 80), + } + task = asyncio.create_task(application(scope, receive, send)) + try: + return await asyncio.wait_for(started, 5.0) + finally: + disconnect.set() + try: + await asyncio.wait_for(task, 5.0) + except (TimeoutError, asyncio.CancelledError): + task.cancel() + + start = asyncio.run(scenario()) + headers = {key.decode().lower(): value.decode() for key, value in start["headers"]} + assert start["status"] == 405 + assert headers["allow"] == "POST" + assert not headers.get("content-type", "").startswith("text/event-stream") + + +def test_post_json_responses_are_unchanged(application): + with TestClient(application, base_url="http://127.0.0.1", client=("127.0.0.1", 50000)) as client: + response = client.post("/mcp", json={"jsonrpc": "2.0", "id": 7, "method": "tools/list"}, + headers={"Accept": "application/json, text/event-stream"}) + assert response.status_code == 200 and response.headers["content-type"].startswith("application/json") + assert response.json()["id"] == 7 and response.json()["result"]["tools"] + + @pytest.mark.parametrize("peer,headers,expected", [ ("192.0.2.10", {}, 403), ("127.0.0.1", {"Origin": "https://evil.invalid"}, 403), diff --git a/unilabos/server/mcp/__init__.py b/unilabos/server/mcp/__init__.py index 54aa32c09..50888104a 100644 --- a/unilabos/server/mcp/__init__.py +++ b/unilabos/server/mcp/__init__.py @@ -1,4 +1,4 @@ -"""本机 MCP 接入:Streamable HTTP /mcp,复用既有 protocol 与管理端口。""" +"""本机 MCP 接入:Streamable HTTP /mcp(无状态、POST 返回 JSON;GET 不开 SSE 流,回 405),复用既有 protocol 与管理端口。""" from __future__ import annotations @@ -21,6 +21,14 @@ def __init__(self, app: FastAPI) -> None: self.app = app async def __call__(self, scope, receive, send) -> None: + if scope.get("method") == "GET": + # 不提供 Streamable HTTP 的独立 SSE 流:无状态模式下服务端没有主动推送,那条流也没有 id 和事件存储, + # 断线即丢。按 MCP 规范回 405,客户端只用 POST(JSON 响应)。 + await error_response( + OPERATION_NOT_ALLOWED, "MCP 不提供 SSE 流,请用 POST", symbol="method_not_allowed", + http_status=405, headers={"Allow": "POST"}, + )(scope, receive, send) + return peer = (scope.get("client") or ("", 0))[0] try: address = ipaddress.ip_address(peer) From 6e76b6507b9c06e477171a5c6349a9442fee584c Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:56:40 +0800 Subject: [PATCH 50/59] refactor(workflow): every /api/v1/events frame advances the watch cursor Every frame on /api/v1/events now carries an id from one sequence, so the watch loop no longer distinguishes durable workflow frames from id-less notices: any frame with an id advances the cursor, a frame at or below the cursor is a replay and is skipped, and stream.reset adopts the new watermark. Non-integer ids are still ignored, and --after keeps resuming through Last-Event-ID. Tests drive the real event stream with material and log rows interleaved around the task notice and check that the watch ends on the task. --- tests/app/test_workflow_watch_sse.py | 77 ++++++++++++++++++++++++++++ unilabos/client/runtime/workflow.py | 24 ++++----- 2 files changed, 89 insertions(+), 12 deletions(-) diff --git a/tests/app/test_workflow_watch_sse.py b/tests/app/test_workflow_watch_sse.py index f6a34a501..f619b4791 100644 --- a/tests/app/test_workflow_watch_sse.py +++ b/tests/app/test_workflow_watch_sse.py @@ -183,6 +183,83 @@ def test_watch_cursor_follows_the_frame_id_not_the_material_ledger_sequence() -> ] +class _Connected: + async def is_disconnected(self) -> bool: + return False + + +def _server_frames(rows: list[tuple[str, dict]], last_id: int) -> list[dict[str, Any]]: + """把这些通知写进真实的 frontend_event,按 /api/v1/events 的输出(Last-Event-ID: 0)解析成 watch 的通知。""" + + import asyncio + + from unilabos.server.api.runtime import events + from unilabos.server.services.runtime.workflow.service import WorkflowService + + service = WorkflowService(":memory:") + + async def collect() -> str: + stream = events.runtime_event_stream(_Connected(), service, 0, replay=True) + chunks: list[str] = [] + try: + while not any(chunk.startswith(f"id: {last_id}\n") for chunk in chunks): + chunks.append(await asyncio.wait_for(anext(stream), 5)) + finally: + await stream.aclose() + return "".join(chunks) + + try: + for event, data in rows: + service.append_frontend_event(event, data) + raw = asyncio.run(collect()) + finally: + service.close() + return [json.loads(_sse_frame_notice(frame)) for frame in _parse_sse_lines(_iter_text_lines([raw]))] + + +def test_watch_ends_on_the_task_notice_between_material_and_log_frames(monkeypatch) -> None: + from unilabos.server.api.runtime import events + + monkeypatch.setattr(events, "shutting_down", lambda: False) + frames = _server_frames([ + ("material.changed", {"sequence": 5000, "material_uuids": ["m1"]}), + ("runtime.logs.changed", {"source_ids": ["host"], "sources_changed": False, "all_sources": False}), + ("workflow.task.changed", {"workflow_task_uuid": "task-1", "status": "succeeded"}), + ("material.changed", {"sequence": 5001}), + ], last_id=4) + # 每一帧都带同一序列的 id;物料通知的 data.sequence 是物料账本序号,不是游标 + assert [(frame["action"], frame["id"]) for frame in frames] == [ + ("material.changed", 1), ("runtime.logs.changed", 2), (RUNTIME_CHANGED_EVENT, 3), ("material.changed", 4), + ] + http = _Tasks(["running", "running", "succeeded"]) + notices = _Notices(frames) + client = HTTPWorkflowClient("http://edge:8002", http_client=http, notice_connector=lambda *_: notices) + events_seen = list(client.watch_task("task-1", timeout=1)) + + assert [(event["kind"], event["task"]["status"], event["cursor"]) for event in events_seen] == [ + ("task_snapshot", "running", 0), + ("task_changed", "succeeded", 3), + ] + assert json.loads(notices.recv())["id"] == 4 # 任务一到终态就结束,后面的物料帧没被读 + + +def test_every_frame_advances_the_watch_cursor_and_replays_are_skipped() -> None: + http = _Tasks(["running"]) + notices = [ + {"action": "workflow.runtime.changed", "id": 5, "data": {"kind": "task", "workflow_task_uuid": "task-1"}}, + {"action": "material.changed", "id": 6, "data": {"sequence": 9000, "material_uuids": []}}, + {"action": "runtime.logs.changed", "id": 7, "data": {"source_ids": ["host"]}}, + {"action": "workflow.runtime.changed", "id": 7, "data": {"kind": "task", "workflow_task_uuid": "task-1"}}, + ] + client = HTTPWorkflowClient("http://edge:8002", http_client=http, notice_connector=lambda *_: _Notices(notices)) + with pytest.raises(WorkflowClientError) as caught: + list(client.watch_task("task-1", after=5, timeout=0.5)) + assert caught.value.code == "watch_timeout" + # --after 5:续传边界上重放的 5 跳过;物料 / 日志帧照常推进;不大于游标的 7 是重复帧 + assert caught.value.details == {"cursor": 7} + assert http.reads == 2 # 首次快照 + 连接后补读;没有一帧触发重读 + + def test_schedule_addr_is_deprecated_and_not_used_for_watch() -> None: with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") diff --git a/unilabos/client/runtime/workflow.py b/unilabos/client/runtime/workflow.py index 7db6ea961..25ea25bfe 100644 --- a/unilabos/client/runtime/workflow.py +++ b/unilabos/client/runtime/workflow.py @@ -102,7 +102,7 @@ def _parse_sse_lines(lines: Iterable[str]) -> Iterator[dict[str, Any]]: """把 SSE 文本行解析成 ``{"event", "id", "data"}`` 帧。 注释行与 ``retry`` 忽略;只有 ``id`` 没有 ``data`` 的水位帧照常产出(``data`` 为 - ``None``)。``id`` 只取本帧自带的值,没有 id 的瞬时通知不会继承上一条的序号。 + ``None``)。``id`` 只取本帧自带的值,不继承上一条的序号(服务端每帧都带 id,这里不依赖它)。 """ event_name, event_id, data_lines = "", None, [] @@ -518,7 +518,8 @@ def watch_task( """订阅 SSE 失效通知,并在每次相关通知后经 HTTP 拉取任务与 Job 正文。 ``after`` 为 0 时从服务端当前水位开始,不回放历史通知;大于 0 时作为 - ``Last-Event-ID`` 从该序号之后续传。``stream.reset`` 表示游标失效,水位 + ``Last-Event-ID`` 从该序号之后续传。产出的 ``cursor`` 是收到的最后一帧的 id(任何帧都推进它, + 包括物料、日志通知),可作下一次的 ``after``。``stream.reset`` 表示游标失效,水位 可能回退,客户端重读 HTTP 校准。快照没有变化的通知不重复产出。 """ @@ -574,15 +575,15 @@ def watch_task( # 游标过期或超前:采用服务端给出的新水位(可能回退)并重读 HTTP。 if sequence is not None: cursor = sequence - elif not self._notice_matches_task(notice, task_uuid): - # 水位帧与其他任务的通知只推进游标,便于调用方用 after 续传;不带 id 的瞬时通知不动游标。 - if sequence is not None and sequence > cursor: + else: + if sequence is not None: + # 每一帧(水位、工作流、物料、日志)都带同一序列的 id,都推进游标,调用方用 after 续传; + # 不大于游标的是续传边界上的重复帧。 + if sequence <= cursor: + continue cursor = sequence - continue - elif sequence is not None: - if sequence <= cursor: + if not self._notice_matches_task(notice, task_uuid): continue - cursor = sequence # 通知内容只触发失效;任务事实固定从 HTTP 重新拉取。 refreshed = self.inspect_task(task_uuid) @@ -662,10 +663,9 @@ def _notice_matches_task( @staticmethod def _notice_sequence(notice: Mapping[str, Any]) -> Optional[int]: - """只有带 SSE id 的帧(工作流持久事件、水位帧、``stream.reset``)才有游标序号。 + """帧的 SSE id,即 ``/api/v1/events`` 那一个序列上的游标;不是非负整数时返回 None。 - ``material.changed``、``runtime.logs.changed`` 等瞬时通知不带 id,``data`` 里的 - ``sequence`` 属于别的账本(例如物料账本末尾),绝不能拿来推进工作流游标。 + 游标只取 SSE id:``material.changed`` 的 ``data.sequence`` 是物料账本的序号,不能拿来推进游标。 """ value = notice.get("id") From 5b192bfc3a3b16cf1b7924d821f7ed96350e21f8 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:59:44 +0800 Subject: [PATCH 51/59] docs: every SSE frame has an id; one sequence on /api/v1/events The realtime guide describes the single frontend_event sequence: who writes material.changed and runtime.logs.changed (the Workflow Authority process), how they are coalesced and rate-limited (one row per second per kind), what that means for retention, and what uni-lab-fe must do (material.changed has ids; a notice without material_uuids means reload all materials). It also documents /monitor/events resume and reset, and GET /mcp answering 405. The V1 route map, migration notes, API catalog, log UI notes and MCP pages follow. --- docs/developer_guide/api_v1_migration.md | 13 ++- docs/developer_guide/api_v1_route_map.md | 12 ++- docs/developer_guide/edge_ui_api.md | 3 +- .../developer_guide/interfaces/api-catalog.md | 7 +- .../interfaces/python-cli-mcp.md | 5 +- docs/developer_guide/interfaces/realtime.md | 92 +++++++++++++++---- docs/developer_guide/mcp.md | 4 +- docs/developer_guide/mcp_guide.md | 2 +- .../workflow_static_conditions.md | 2 +- 9 files changed, 105 insertions(+), 35 deletions(-) diff --git a/docs/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index e6186eab6..b6a03c433 100644 --- a/docs/developer_guide/api_v1_migration.md +++ b/docs/developer_guide/api_v1_migration.md @@ -149,10 +149,17 @@ dev 内部异常到业务码的映射集中在 `envelope.py`,不在各路由 (`workflow.task|node_run|node_job|manual_confirmation|resource.changed`)作为 `data.kind` (`task` / `node_run` / `node_job` / `manual_confirmation` / `resource`)放进 V1 事件,不再单独发事件名; 原载荷字段保留。换名在 API 层(`api/runtime/events.py:to_v1_event`)做,`frontend_event` 表仍存 dev 名。 - `runtime.logs.changed`(无 id 的日志通知)与物料的 `/api/v1/materials/events`(`materials.changed`)不在 - V1 合同里,暂保持原名。物料失效另以 V1 名 `material.changed`(无 id,`data.sequence` 为账本末尾, + `runtime.logs.changed`(日志通知)与物料的 `/api/v1/materials/events`(`materials.changed`)不在 + V1 合同里,暂保持原名。物料失效另以 V1 名 `material.changed`(`data.sequence` 为物料账本末尾, `data.material_uuids` 列出这段账本里变了的物料,Site 的变化归到所属物料、拓扑边归到两端;空列表表示没有物料变化, - 涉及模板或账本重置时省略这个键,表示整体重读)随 `/api/v1/events` 推送,前端每个工站只维持这一条事件流。CLI `workflow watch` 同步修改。 + 涉及模板、账本重置或超过 500 个物料时省略这个键,表示整体重读)随 `/api/v1/events` 推送,前端每个工站只维持这一条事件流。 + **单一序列**:物料与日志通知由权威进程合并、限速(各自每秒至多一行)后写进 `frontend_event`,与工作流事件同一个序列, + `/api/v1/events` 的每一帧都带整数 id,断线续传、`stream.reset` 与保留清理一视同仁(见 + [实时协议](interfaces/realtime.md))。uni-lab-fe 须知:`material.changed` 现在带 id;不带 `material_uuids` 的通知必须整体重读物料。 + CLI `workflow watch` 的游标随任何带 id 的帧前进。 +- **监控流**:`/api/v1/monitor/events` 按 `frontend_event` 序号续传:重连带 `Last-Event-ID` 不再回放最近 40 条, + 过期 / 超前游标发 `stream.reset`,按页扫描、游标只推进到实际扫过的最大序号,每帧都带 id。 +- **MCP**:`GET /mcp` 回 405(不开 Streamable HTTP 的独立 SSE 流);`POST /mcp` 的 JSON 响应不变。 ## 库存与工作区(p7-c 落地) diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index 06b2d775d..9491eae08 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -54,6 +54,14 @@ Database versions: on the 0.13 release line all four databases start at schema v > `/api/v1/edge/http-responses/*`, and unmatched routes (404 + 4001 / 405 + 1001 from an app-level handler). Only SSE > and file downloads stay raw. CORS exposes `Retry-After`, so a browser can read it on the 5001 "Host starting" > answers. +> +> **2026-11-25 (owner decision, single sequence):** every SSE frame carries an id. `/api/v1/events` serves workflow +> events, `material.changed` and `runtime.logs.changed` from one integer `frontend_event` sequence: the process that +> owns the Workflow Authority writes the material and log notices, coalesced, at most one row per second per kind, so +> `Last-Event-ID` resume, `stream.reset` and retention cleanup cover them like workflow events. `/api/v1/monitor/events` +> resumes from `Last-Event-ID` (no backlog replay), sends `stream.reset` for stale / ahead cursors and pages through +> `frontend_event` without skipping. `GET /mcp` answers 405 (no id-less standalone stream). `/api/v1/materials/events` +> keeps its `:` ids. These matter more than any single route. Each item gives evidence from both trees. @@ -234,7 +242,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | class | V1 route | V1 handler | DEV counterpart | note | |---|---|---|---|---| -| MISSING | `GET /api/v1/monitor/events` | unilabos/app/scheduler/api.py:265 | (partial) SSE /api/v1/events log notices; SSE /api/v1/materials/events | **Ported (p7-b): SSE {seq, ts, channel, type, data} projected from frontend_event (action / scheduler / device); material channel empty (materials events stay on /materials/events); follow=false for one-shot backlog.** V1 has 4 channels (material, device, action, scheduler) | +| MISSING | `GET /api/v1/monitor/events` | unilabos/app/scheduler/api.py:265 | (partial) SSE /api/v1/events log notices; SSE /api/v1/materials/events | **Ported (p7-b): SSE {seq, ts, channel, type, data} projected from frontend_event (action / scheduler / device); material channel empty (materials events stay on /materials/events); follow=false for one-shot backlog. 2026-11-25: every frame has the frontend_event sequence as id; Last-Event-ID resumes without replaying the backlog, stale / ahead cursors get stream.reset, the cursor advances only to the highest row scanned (page by page), filtered rows advance an id-only watermark.** V1 has 4 channels (material, device, action, scheduler) | | MISSING | `GET /api/v1/monitor/snapshot` | unilabos/app/scheduler/api.py:313 | (partial) GET /api/v1/scheduler/resources | **Ported (p7-b): devices (busy/idle from jobs), scheduler {workflow_states, inflight, reschedule_count}, recent per channel.** | | MISSING | `GET /api/v1/reagents/{reagent_uuid}/inventory-consumptions` | unilabos/app/workflow_api.py:1799 | - | **Ported (p7-d): content-reservation consumptions and settled physical aliquots of the substance (reagent uuid = substance uuid), newest first, readable after the reagent is deleted; invalid uuid 1000; no materials authority → []. Read model `services/materials/consumption.py`.** | | MISSING | `POST /api/v1/reschedule` | unilabos/app/scheduler/api.py:231 | - | **Ported (p7-b): re-runs resource reconcile + wakes active tasks; {dispatched: [job ids observed]}; no local scheduler → 5001.** Manual re-dispatch | @@ -255,7 +263,7 @@ Adopting V1's contract on any of these breaks something DEV already relies on. | MISSING | `GET /api/v1/workflow-tasks/{task_uuid}/inventory-consumptions` | unilabos/app/workflow_api.py:1781 | (partial) GET /api/v1/materials/reservations?task_uuid= | **Ported (p7-d): V1 consumption DTO over materials facts of every job of the task: settled lot reservations minus actual-quantity corrections (`inventory_type: lot`, dev extension), consumed content reservations (`reagent` / `current_substance`), settled physical aliquots (planned_quantity null); names from the task snapshot; manual reconciliation in `meta_data.reconciliation`. materials.db read-model indexes.** | | MISSING | `GET /api/v1/workflow-tasks/{task_uuid}/material-events` | unilabos/app/workflow_api.py:1787 | - | **Ported (p7-b): MaterialsService ledger changes whose job_uuid belongs to the task, annotated with node name and step path; empty when no materials authority.** Used by the V1 console | | MISSING | `GET /api/v1/workflow-tasks/{task_uuid}/step-state` | unilabos/app/workflow_api.py:1954 | (partial) GET /workflow-tasks/{uuid}/node-runs | **Ported (p7-b): candidates = pending node runs whose upstreams finished, only while paused with nothing in flight. No capability gate (DEV has no debug capability).** Used by the V1 console | -| DTO-DIFF | `GET /api/v1/events` | unilabos/app/workflow_api.py:2237 | GET /api/v1/events | **Names done by the foundation branch; p7-b adds station.error_handling.changed (data.station_id) from the station model.** Same cursor protocol (Last-Event-ID, stream.reset). Event names differ: V1 workflow.runtime.changed / workflow.authoring.changed; DEV workflow.task\|node_run\|node_job\|manual_confirmation\|resource.changed plus log-notice events. V1 clients miss every DEV runtime change | +| DTO-DIFF | `GET /api/v1/events` | unilabos/app/workflow_api.py:2237 | GET /api/v1/events | **Names done by the foundation branch; p7-b adds station.error_handling.changed (data.station_id) from the station model. 2026-11-25: material.changed and runtime.logs.changed are frontend_event rows written by the authority (coalesced, at most one per second per kind), so every frame has an integer id from one sequence.** Same cursor protocol (Last-Event-ID, stream.reset). Event names differ: V1 workflow.runtime.changed / workflow.authoring.changed; DEV workflow.task\|node_run\|node_job\|manual_confirmation\|resource.changed plus log-notice events. V1 clients miss every DEV runtime change | | DTO-DIFF | `GET /api/v1/workflow-node-jobs/{job_uuid}` | unilabos/app/workflow_api.py:2064 | GET /api/v1/workflow-node-jobs/{job_uuid} | **Ported (p7-b): same V1 job fields.** F04 | | DTO-DIFF | `GET /api/v1/workflow-tasks` | unilabos/app/workflow_api.py:1864 | GET /api/v1/workflow-tasks | **Ported (p7-b): execution_kind filter, has_more; items carry priority, inventory_bindings, execution_mode, dispatch_gate, wait_reason.** DEV has no execution_kind filter and strips output from list items. Task DTO diff UNVERIFIED | | DTO-DIFF | `POST /api/v1/workflow-tasks` | unilabos/app/workflow_api.py:1708 | POST /api/v1/workflow-tasks | **Ported (p7-b): priority (normal|high) and inventory_bindings (V1 shape) accepted and persisted on workflow_task (runtime.db); each binding is applied to the frozen plan: it selects the reagent / current substance the matching `kind="content"` requirement reserves (key = requirement `key`, or `/`; unit and quantity must equal the requirement); unmatched bindings are rejected with 1000, never dropped; ad-hoc tasks reject non-default values.** F03. DEV is strict, so priority and inventory_bindings fail with 1000 (envelope, HTTP 200), not 422. V1 also checks capabilities (debug for step) | diff --git a/docs/developer_guide/edge_ui_api.md b/docs/developer_guide/edge_ui_api.md index 3516db620..3c2624f4f 100644 --- a/docs/developer_guide/edge_ui_api.md +++ b/docs/developer_guide/edge_ui_api.md @@ -351,7 +351,8 @@ UI 的恢复基线来自四库 API,而不是进程内事件缓存: 未结束的短行等待下一次换行,保留多行 traceback 与中文 UTF-8 边界。 写日志后触发轻通知:Slave 经 HostLink `process.log.changed` 上报,Host 经既有控制 WS 的 `runtime_logs_changed` 中继;复用 `/api/v1/events` 的 `runtime.logs.changed`,不新增 SSE 连接。 -通知约 200 ms 合并,不写 SSE id/数据库。页面按来源拉增量,空闲无日志查询;恢复可见、暂停或 +通知约 200 ms 合并,权威再合并、限速(每秒至多一行)写进 `frontend_event`,与工作流事件同一个序列、带 SSE id, +断线期间的通知重连后补发。页面按来源拉增量,空闲无日志查询;恢复可见、暂停或 重连时读目录并用独立 cursor 补齐。SharedWorker 让两页共用通知连接;窗口限制 2000 行 / 512 Ki 字符。 日志仅用于可信网络内诊断,可能含设备参数/路径,不应把管理端口直接暴露到公网。 diff --git a/docs/developer_guide/interfaces/api-catalog.md b/docs/developer_guide/interfaces/api-catalog.md index a49feda24..99aa77780 100644 --- a/docs/developer_guide/interfaces/api-catalog.md +++ b/docs/developer_guide/interfaces/api-catalog.md @@ -416,13 +416,14 @@ inline 的 HTTP JSON 正文是 Base64,解码后最多 262144 字节;external | 方法 | 路径 | 输入 | 返回与使用约束 | | --- | --- | --- | --- | -| GET | `/api/v1/events` | H: Last-Event-ID? | text/event-stream;工作流持久事件和 runtime.logs.changed 轻通知,不是 WS | +| GET | `/api/v1/events` | H: Last-Event-ID? | text/event-stream;工作流事件、material.changed 与 runtime.logs.changed 通知同一个序列,每帧带整数 id,不是 WS | | GET | `/api/v1/hostlink/peers` | — | role、peers、client 及已协商的 Host 信息;设备列表与进程台账不同 | | GET | `/api/v1/hostlink/log-sources` | — | Host/Slave 日志源目录,选源后读取日志 | | GET | `/api/v1/hostlink/logs` | Q: source_id(必填,1..512 字符)、cursor=""、limit=300(1..1000) | 有界日志批次及游标;处理 reset/truncated/has_more,直到追平 | 非空日志 cursor 为 24 位小写十六进制、冒号、1..16 位十进制序号,不要自行拼接或与 SSE 事件 ID 混用。 -日志轻通知未必有持久事件 ID;重连后重新读源与快照,不能承诺日志无限历史可重放。 +日志通知在 `/api/v1/events` 上带 id(合并、每秒至多一条),断线期间的通知重连后补发;但通知按保留目标清理, +重连后仍重新读源与快照,不能承诺日志无限历史可重放。 ## 内部 HTTP 与非 HTTP 通道 @@ -439,7 +440,7 @@ inline 的 HTTP JSON 正文是 Base64,解码后最多 262144 字节;external 内部 HTTP 来源:[控制入口](https://github.com/deepmodeling/Uni-Lab-OS/blob/862ce87a38222ac2d51739f2f89e5daecd3cd907/unilabos/server/api/runtime/control.py)、 [设备下行中继](https://github.com/deepmodeling/Uni-Lab-OS/blob/862ce87a38222ac2d51739f2f89e5daecd3cd907/unilabos/server/api/host_relay.py)。 -另有 `/api/v1/ws/schedule` 控制 WebSocket、HostLink TCP RPC,以及 `/mcp` 的 Streamable HTTP/JSON-RPC。 +另有 `/api/v1/ws/schedule` 控制 WebSocket、HostLink TCP RPC,以及 `POST /mcp` 的 Streamable HTTP/JSON-RPC(GET 回 405)。 它们不是新增几条普通业务 CRUD;消息类型、握手和超时见 [实时协议](realtime.md), MCP 的会话、工具分类与权限见 [MCP 接入](python-cli-mcp.md)。 管理站还有 `/api/docs`、`/api/redoc`、`/api/openapi.json` 文档端点,不纳入上述业务数量。 diff --git a/docs/developer_guide/interfaces/python-cli-mcp.md b/docs/developer_guide/interfaces/python-cli-mcp.md index 3040bb996..20542d48b 100644 --- a/docs/developer_guide/interfaces/python-cli-mcp.md +++ b/docs/developer_guide/interfaces/python-cli-mcp.md @@ -225,8 +225,9 @@ session.py 负责本地会话/凭据/上下文,utils/envelope.py 负责响应 ## MCP:复用 HTTP 合同的本机工具 -服务启动后 MCP 地址为 `http://127.0.0.1:8003/mcp`,使用 Streamable HTTP, -GET/POST/DELETE;当前 stateless、JSON 响应模式。它独立于 SSE 观察端与设备 WS。 +服务启动后 MCP 地址为 `http://127.0.0.1:8003/mcp`,使用 Streamable HTTP 的 POST;当前 stateless、JSON 响应模式。 +GET 回 405(不开独立 SSE 流:无状态模式下服务端不主动推送,那条流也没有 id),DELETE 由 SDK 回 405(没有会话可终止)。 +它独立于 SSE 观察端与设备 WS。 仅 loopback 对端且无 Origin 请求可访问;浏览器/远端会得到 403,尚未就绪 503。 工具在进程内经 ASGI 调用管理 API(管理 API 不鉴权,见 HTTP 文档「认证与网络边界」)。 不要把本机开放工具等同于用户已授权执行硬件。 diff --git a/docs/developer_guide/interfaces/realtime.md b/docs/developer_guide/interfaces/realtime.md index 65255e5fb..1d3bd4362 100644 --- a/docs/developer_guide/interfaces/realtime.md +++ b/docs/developer_guide/interfaces/realtime.md @@ -4,11 +4,12 @@ | 使用者 | 通道 | 内容 | | --- | --- | --- | -| 浏览器(每个工站一条) | SSE `/api/v1/events` | 持久工作流变更 + 瞬时日志失效通知 + 瞬时物料失效通知(`material.changed`) | +| 浏览器(每个工站一条) | SSE `/api/v1/events` | 工作流变更 + 日志失效通知 + 物料失效通知(`material.changed`),同一个序列,每帧都带 id | | 需要按账本续传 / 精确失效的客户端 | SSE `/api/v1/materials/events` | 物料账本变更通知(`materials.changed`,带 sequence 游标) | +| V1 监控面板 | SSE `/api/v1/monitor/events` | 四通道监控事件(由 `frontend_event` 投影),按同一个序列续传 | | Host ↔ 微后端/上游 Backend | WS `/api/v1/ws/schedule` + HTTP | runtime.v1 控制、命令正文与事件回收 | | Host ↔ Slave | HostLink TCP,默认 7302 | 握手、路由、RPC、topic、物料投影、日志 | -| 本机 AI 客户端 | Streamable HTTP `/mcp` | 工具调用,不是上述浏览器事件流 | +| 本机 AI 客户端 | Streamable HTTP `POST /mcp` | 工具调用(JSON 响应);GET 回 405,没有事件流 | 管理 HTTP 示例端口为 8003;HostLink 端口独立,不能把 TCP 地址交给 WebSocket 客户端。 **浏览器不要连接 `/ws/schedule`**:本版 EdgeControlService 只有一个活动执行控制连接, @@ -23,32 +24,64 @@ | 项目 | `/api/v1/events` | `/api/v1/materials/events` | | --- | --- | --- | | 无 Last-Event-ID 首连 | 固定当前最新序号,先发只含 `id` 的水位帧,仅推之后变化 | 固定当前账本末尾,先发只含 `id` 的水位帧,仅推之后变化 | -| 持久 SSE id | 工作流事件 id | `:<账本纪元>`;账本为空时只有 `` | +| SSE id | `frontend_event` 序号(整数);工作流、物料、日志通知与重置帧都在这一个序列上,每帧都带 | `:<账本纪元>`;账本为空时只有 `` | | 恢复方式 | Last-Event-ID,从该 id 之后重放;显式 `0` 回放全部保留历史 | Last-Event-ID,从该 sequence 之后重放;旧格式的纯数字游标照常接受 | | 游标大于最新序号 | `stream.reset`(`reason: cursor_ahead`,`id` 为新水位),连接保持 | 同左 | | 游标来自另一个库 | 无 | `stream.reset`(`reason: epoch_changed`,`id` 为新水位),连接保持;纯数字游标不带纪元,无法判断 | | 游标早于保留窗口 | `stream.reset`(`reason: cursor_expired`,`id` 为新水位),连接保持 | 无(账本不清理) | | 非法游标 | Workflow code=1000,HTTP 200 JSON | code=1000,HTTP 200 JSON | -| 无事件时 | keepalive 注释;工作流检查约 1 秒,心跳约 15 秒 | keepalive 注释;约 1 秒检查账本 | +| 无事件时 | keepalive 注释;约 1 秒读一次,权威写入物料 / 日志通知时立即唤醒;心跳约 15 秒 | keepalive 注释;约 1 秒检查账本 | -三个游标相互独立:工作流 id、物料 sequence、日志 stream:offset。不能混用,也不能以最后日志通知替换工作流游标。 +三个游标相互独立:`/api/v1/events` 的 SSE id、物料账本 sequence、日志 stream:offset。不能混用。 +`material.changed` 的 `data.sequence` 是物料账本序号,不是 `/api/v1/events` 的游标。 -`/api/v1/events` 上的 `material.changed` 与日志通知一样**不带 id**:本进程持有物料权威时,账本前进就推 -`event: material.changed` + `data: {"sequence": <账本末尾>, "material_uuids": [<这段账本里变了的物料>]}`。 -`material_uuids` 的语义: +### `/api/v1/events`:一个序列,每帧都有 id + +`/api/v1/events` 的每一帧(水位帧、工作流事件、`material.changed`、`runtime.logs.changed`、`stream.reset`)都带 +`frontend_event` 这一个序列上的整数 id。物料与日志通知也是 `frontend_event` 的行,所以: + +- 断线期间的物料 / 日志通知在重连(浏览器自动带 `Last-Event-ID`)后补发,不靠 REST 补读兜底; +- 超前(`cursor_ahead`)/ 早于保留窗口(`cursor_expired`)的游标照常收到 `stream.reset`; +- 保留清理按同一套目标(见下面「工作流通知」)一并清理这些行。 + +**谁写、怎么合并。** 写入器(`server/services/runtime/workflow/frontend_notices.py`)只在持有 Workflow Authority +的进程里运行:默认拓扑的权威进程、`--role backend`;单进程模式(`--no-safe-restart`)下就是这个进程。 + +- 物料:写入器是物料权威共享账本轮询(`server/services/materials/ledger_watch.py`:一个物料权威一条专用线程, + 约每秒读一次账本末尾,每批最多 500 条,多了马上接着读)的常驻订阅者,账本每前进一次合并写**一行** + `material.changed`,`data: {"sequence": <账本末尾>, "material_uuids": [<这段账本里变了的物料>]}`。 + 物料权威不在本进程(Host 经 `--material_microbackend_addr` 用远端物料权威)时不写物料通知。 +- 日志:写入器订阅进程内日志通知中心。Host 子进程(及 `--address` 接入的 Host)的通知经 runtime.v1 + `runtime_logs_changed` 到达权威,由 `EdgeControlService` 发布到这个通知中心;Host 上下线时权威自己也发一条。 + 合并写一行 `runtime.logs.changed`,`data` 为 `RuntimeLogNotice`。 +- 限速:两类通知**各自每秒至多一行**(`NOTICE_INTERVAL_S = 1.0`)。空闲后的第一条立即写;一秒内后到的并进下一行 + (物料取并集,日志合并来源),所以一阵日志刷屏、一次大批量物料写入都只产生少量行。 +- 写完一行立即唤醒本进程的 SSE 连接去读,不等约 1 秒一轮的轮询。 +- 权威重启:写入器从最新一条 `material.changed` 记下的账本序号之后续读,停机前没来得及写的那段账本也补写一行; + 账本比记下的还短(库被重置)写一行不带 `material_uuids` 的整体重读。 + +`material_uuids` 的语义(与之前相同): - **带这个键**:恰好是这段账本里变了的物料(Site 的占用变化归到所属物料,拓扑边的增删改归到两端物料), 客户端只重读这些;**空列表 `[]` 表示没有物料变化**(这段账本只动了批次 / 预留),什么都不用重读; -- **不带这个键**:列不准(资源模板变化、库被重置),整体重读。 +- **不带这个键**:列不准(资源模板变化、库被重置,或一行里超过 500 个物料),**整体重读**。 -账本由进程内唯一的共享轮询读(`server/services/materials/ledger_watch.py`:一个物料权威一条专用线程,约每秒一次, -每批最多 500 条,多了下一轮接着读),所有连接(含下面的 `/api/v1/materials/events`)共用同一份结果,不按连接重复读, -也不占默认线程池(runtime.v1 控制 socket 的出站泵、edge 代理用它)。通知不回放、不占工作流游标;断线期间的物料变化 -由重连后的 REST 补读覆盖。浏览器因此每个工站只需维持 -`/api/v1/events` 一条长连接(HTTP/1.1 下每个源最多约 6 条连接,多开标签页时第二条流会挤占 REST)。 +浏览器因此每个工站只需维持 `/api/v1/events` 一条长连接(HTTP/1.1 下每个源最多约 6 条连接,多开标签页时第二条流会挤占 REST)。 后端内部检查账本不等于要求浏览器每秒 GET 全量数据;前端维持事件流,仅在失效时拉取。 -### 物料通知 +**前端须知(uni-lab-fe)。** + +- `material.changed` 现在带 id,与工作流事件同一个序列;EventSource 自动维护与回传,不用改连接代码。 + 不要把 `data.sequence` 当游标。 +- 收到**不带 `material_uuids`** 的 `material.changed` 必须整体重读物料(树、仓储与相关 Site),不能忽略; + `[]` 什么都不用重读。 +- 重连后会补发断线期间的物料 / 日志通知(以前要靠 `onopen` 的 REST 补读);`onopen` 的校准照常保留。 +- `stream.reset` 照常:整体重读。 + +OpenLabSite 物料走 `/api/v1/materials/events`,`/api/v1/events` 只订阅工作流、人工决策、日志通知与 `stream.reset`, +不读这条流的 id,不受影响。 + +### 物料账本流 `/api/v1/materials/events` ```text id: 42:3f9c0a1b7d2e4c55 @@ -58,7 +91,8 @@ data: {"sequence":42,"operation":"update_position","aggregate_type":"material"," ``` 通知只说明什么发生了变化,不带完整树、液体或模板正文。需要账本序号时读 `data.sequence`, -不要解析 SSE id。 +不要解析 SSE id。账本由上面那条共享轮询读(与 `material.changed` 的写入器共用),每个连接从自己的游标补读, +之后共用同一份结果,不按连接重复读,也不占默认线程池(runtime.v1 控制 socket 的出站泵、edge 代理用它)。 SSE id 冒号后的**账本纪元**是由这个库第一条账本记录派生的 16 位十六进制不透明标识:账本只追加, 同一个库的纪元不变;换了数据目录或全量重置后重建,纪元随之改变。重连时 Last-Event-ID 的纪元与当前库 @@ -126,6 +160,8 @@ function subscribeMaterials(baseUrl, render, reportError) { 通知按 `BasicConfig` 的保留目标定期清理(默认最近 24 小时、最多 10,000 条,每 60 秒检查, 每个事务最多删 1,000 条)。只删连续的旧前缀,始终保留最新一条作为水位;这些是清理目标, 不是每次插入后的硬上限。慢连接的游标被清理越过时收到 `cursor_expired`。 +物料、日志通知也计入条数:日志持续刷新时每秒最多一行,10,000 条约覆盖 2.8 小时;物料与日志同时持续变化时 +约 1.4 小时。需要更长的断线续传窗口时调大 `frontend_event_max_count`。 持久事件按 V1 事件名发送:任务、节点运行、节点作业、人工确认与资源区间 / 借还 / 托管的变化一律为 `workflow.runtime.changed`,`data.kind` 区分种类(`task` / `node_run` / `node_job` / @@ -137,6 +173,21 @@ data 为相应对象身份、状态等失效信息(库里存的 dev 载荷原 `kind:"node_job"`、workflow_node_job_uuid、workflow_node_run_uuid、attempt_no、status。未知事件名应安全忽略或触发相关 HTTP 校准,不能让整个流崩溃。 有 `event:` 名称的 SSE 必须用 addEventListener 注册;仅设置 onmessage 接不到这些命名事件。 +### 监控流 `/api/v1/monitor/events` + +V1 四通道监控面板(`material` / `device` / `action` / `scheduler`)的事件由 `frontend_event` 投影 +(作业 → action,任务 / 工站 → scheduler,资源占用 → device;物料 / 日志失效通知不投影,material 通道为空), +SSE id 就是 `frontend_event` 的序号,每帧都带。查询参数 `channels`(逗号分隔,缺省全部)、`backlog`(默认 40,最多 200)、 +`follow`(默认 true)。 + +- 首连(无 `Last-Event-ID`):回放最近 `backlog` 条,跟随时再发一个只含 `id` 的水位帧(回放时的最新序号); +- 重连带 `Last-Event-ID`:从该序号之后续传,**不再回放最近 40 条**,不重复也不漏; +- 游标大于最新序号(`cursor_ahead`)或早于保留窗口(`cursor_expired`):`stream.reset`,`id` 为新水位,连接保持, + 客户端重读 `/api/v1/monitor/snapshot`;非法游标回 code=1000(HTTP 200 JSON); +- 每轮按页扫描(每页 200 行,读满马上读下一页),游标只推进到实际扫过的最大序号:扫描期间提交的、超过一页的事件都不会跳过; + 扫过的其他通知(不属于所选通道)只推进水位,发一个只含 `id` 的帧; +- 无事件时约 0.4 秒读一次,15 秒心跳注释;服务端开始停机时结束流。 + ## Host / 本机和远端 Slave 日志 1. GET `/api/v1/hostlink/log-sources` → `RuntimeLogSources {sources:[...]}`。 @@ -157,11 +208,12 @@ limit 默认 300,范围 1–1000。offset 不是时间,也不能跨文件排 reset 表示文件轮转/进程重启等导致游标重新定位;truncated 表示历史缺口,应在界面提示,不能伪装日志连续。 无此源返回业务码 4001,暂不可用返回 5001(HTTP 200,可带 Retry-After)。 -日志通知**没有 SSE id、没有日志正文、不落持久工作流事件表**。 -突发追加会合并通知,所以通知数量不等于新增行数。日志读取不消费数据,两个页面应各自持有 cursor。 +日志通知**没有日志正文**。权威进程把它合并、限速后写进 `frontend_event`(每秒至多一行),在 `/api/v1/events` +上带 id 发出,断线期间的通知重连后补发。突发追加会合并通知,所以通知数量不等于新增行数。 +日志读取不消费数据,两个页面应各自持有 cursor。 -传递链路:Slave 文件追加 → `process.log.changed` 空通知 → Host → runtime.v1 -`runtime_logs_changed` → 权威 SSE `runtime.logs.changed` → 浏览器 HTTP 拉正文。 +传递链路:Slave 文件追加 → `process.log.changed` 空通知 → Host(约 200 ms 合并)→ runtime.v1 +`runtime_logs_changed` → 权威合并、限速写进 `frontend_event` → SSE `runtime.logs.changed`(带 id)→ 浏览器 HTTP 拉正文。 远端日志由 Host 经 `process.log.read` 读取;source_id 指定逻辑源,浏览器不能传任意文件路径。 控制台中 EdgeControl 的调度日志不能代替 Slave 的驱动日志。 diff --git a/docs/developer_guide/mcp.md b/docs/developer_guide/mcp.md index 687d1025f..add51edb8 100644 --- a/docs/developer_guide/mcp.md +++ b/docs/developer_guide/mcp.md @@ -1,7 +1,7 @@ # 本机 MCP 接入 -微后端在同一个管理端口提供 Streamable HTTP `POST /mcp`,实现位于 -`unilabos.server.mcp`。不需要额外运行一个 MCP 进程,也不需要 ROS 2。 +微后端在同一个管理端口提供 Streamable HTTP `POST /mcp`(无状态、JSON 响应;`GET /mcp` 回 405,不开独立 SSE 流), +实现位于 `unilabos.server.mcp`。不需要额外运行一个 MCP 进程,也不需要 ROS 2。 详细操作见 [MCP Guide](mcp_guide.md), 覆盖工具发现、工作流建图/执行、异常、物料、锁、日志与可复用 prompt。 diff --git a/docs/developer_guide/mcp_guide.md b/docs/developer_guide/mcp_guide.md index a01b9f53d..fb13f1593 100644 --- a/docs/developer_guide/mcp_guide.md +++ b/docs/developer_guide/mcp_guide.md @@ -6,7 +6,7 @@ ## 1. 连接与权限 -微后端在现有管理端口提供 Streamable HTTP `/mcp`,无需额外 MCP 进程。 +微后端在现有管理端口提供 Streamable HTTP `/mcp`(POST,JSON 响应;GET 回 405,没有独立 SSE 流),无需额外 MCP 进程。 默认双进程部署连接调度权威端口,不连接 HostLink TCP 端口,也不要求 Host 监听 HTTP。 例如微后端启动在 8003,则 MCP 地址为 `http://127.0.0.1:8003/mcp`。 diff --git a/docs/developer_guide/workflow_static_conditions.md b/docs/developer_guide/workflow_static_conditions.md index 7b8bc36ec..0d69482c5 100644 --- a/docs/developer_guide/workflow_static_conditions.md +++ b/docs/developer_guide/workflow_static_conditions.md @@ -309,7 +309,7 @@ node-runs 查询验证完整链路,同时运行原来的定次加样、等待 任务详情从 dev 的 NodeRun 读取全部 attempts,为每次执行补上逻辑节点的执行类型和拓扑序。每次执行的 ID、参数和返回值保持原值,循环中的成功及 skipped 记录都保留。进度仅使用各逻辑节点的当前 attempt;时间线注明第几次执行,设备 ID 来自任务冻结快照中的绑定。 -`/api/v1/events` 只用于失效通知,页面重读 REST 权威状态。支持 dev 的 task / node_run / node_job / manual_confirmation / authoring 事件及 stream.reset;节点事件缺少任务 ID 时做全局失效,连接建立和重连后补读快照。反馈读取 `/workflow-node-jobs/{uuid}/feedback-history`,按 sequence 续读。 +`/api/v1/events` 只用于失效通知,页面重读 REST 权威状态。支持 dev 的 task / node_run / node_job / manual_confirmation / authoring 事件及 stream.reset;节点事件缺少任务 ID 时做全局失效,连接建立和重连后补读快照。同一条流上的 `material.changed`、`runtime.logs.changed` 与工作流事件共用一个序列,每帧都带整数 id;工作流页面不处理它们,但它们的 id 同样推进续传游标。反馈读取 `/workflow-node-jobs/{uuid}/feedback-history`,按 sequence 续读。 当前运行入口不支持额外库存换绑或高优先级调度;适配器明确拒绝非空换绑和高优先级请求,提交体不发送未支持字段。后端任务创建 DTO 拒绝额外字段,避免调用方误以为配置已生效。后续若新增优先级或库存业务,应先定义 dev 合同再开放界面选项。 From 7be5578b3c40183bdf9c2b38c51b232321c7bd23 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:38:13 +0800 Subject: [PATCH 52/59] feat(registry): inject ActionContext by type, not by parameter name Any parameter annotated ActionContext, Optional[ActionContext] or ActionContext | None is injected by the framework whatever its name; the optional forms get None when there is no context (ROS 2), a required one always gets a context. One helper (bind_action_context) decides for the HostLink local runtime, host_node and cross-device calls, workstation sub-steps and the ROS 2 device node. The AST scan, the decorator, the contract parser and runtime signature inference exclude such parameters by type from the goal schema, required list, placeholder_keys, handles, material locks and goal_default. A parameter named action_context without the annotation is now a registration error pointing to Optional[ActionContext]. --- AGENTS.md | 2 +- docs/developer_guide/action_standard.md | 36 ++- docs/developer_guide/add_device.md | 2 +- docs/user_guide/virtual_devices.md | 3 +- tests/client/host/hostlink/test_host_node.py | 34 ++- .../runtime/test_action_context_injection.py | 101 ++++++++ tests/registry/test_action_context_by_type.py | 213 +++++++++++++++ tests/registry/test_backend_metadata.py | 4 +- .../client/host/hostlink/local_runtime.py | 6 +- unilabos/client/host/ros2/base_device_node.py | 10 +- unilabos/client/host/runtime/action.py | 31 +++ unilabos/registry/action_context.py | 243 ++++++++++++++++++ unilabos/registry/action_contract_schema.py | 12 +- unilabos/registry/action_options.py | 18 +- unilabos/registry/action_schema.py | 39 ++- unilabos/registry/ast_registry_scanner.py | 40 +-- unilabos/registry/decorators.py | 9 +- unilabos/registry/placeholder_keys.py | 9 +- unilabos/registry/typed_contract.py | 5 +- unilabos/utils/import_manager.py | 7 +- 20 files changed, 776 insertions(+), 48 deletions(-) create mode 100644 tests/client/host/runtime/test_action_context_injection.py create mode 100644 tests/registry/test_action_context_by_type.py create mode 100644 unilabos/registry/action_context.py diff --git a/AGENTS.md b/AGENTS.md index 46e61354d..f4635f868 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 and the removed `Placeholder` / `SiteSelector` annotations are rejected by both the decorator and the scan (`registry/action_options.py`). 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.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`. **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 04cec3b27..005668d2a 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -26,7 +26,7 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) - **没有默认值的参数就是必填**:缺了在调度端 / Host 调用前报「动作参数缺少必填字段:…」,不再被补成 0 / 空串。 `goal_default`(`@action(goal_default=...)`)只是编辑器里的初始参数值,叠加在签名默认值上,不改变参数是否必填。 -- 参数名之外的字段一律拒绝(`**kwargs` 除外);框架注入的 `sample_uuids`、`action_context` 不算参数。 +- 参数名之外的字段一律拒绝(`**kwargs` 除外);框架注入的 `sample_uuids` 与动作上下文(见下节)不算参数。 - 物料参数(`ResourceSlot`)接受框架的几种引用形态:`{"uuid": ...}`(可带 id / name)、只给名字的 `{"name": ...}`(派发前由调度器向物料权威解析出 uuid)、上游端口传来的扁平资源树(列表)、uuid 字符串; 能否解析出权威 uuid 由派发前的物料锁检查保证。不可空的物料参数给空值(`{}` / `""` / `[]`)报 @@ -45,6 +45,39 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) `unilabos_samples` 是 Host 剥离到结果外层的保留字段,不进返回 schema。`--test_mode` 下没声明 `run_in_test_mode = True` 的驱动不执行、由 Host 模拟返回值,模拟值不按返回注解校验。 +## 动作上下文:`ActionContext` + +动作需要发布反馈、检查取消或知道自己是哪一次执行时,加一个注解为 `ActionContext` 的参数,框架按**类型**注入, +参数名随意: + +```python +from typing import Optional +from unilabos.client.host.runtime.action import ActionContext + +@action(display_name="加热") +def heat(self, sample: ResourceSlot, seconds: float, ctx: Optional[ActionContext] = None) -> None: + for step in range(10): + if ctx is not None: + ctx.raise_if_cancelled() + ctx.publish_feedback({"progress": step * 10}) +``` + +| 注解 | 有上下文时 | 没有上下文时(ROS 2 执行、作者直接调用) | +| --- | --- | --- | +| `Optional[ActionContext]`、`ActionContext \| None`、`ActionContext = None` | 注入 | `None` | +| `ActionContext` | 注入 | 框架现建一个(`action_id` 随机,没有反馈回调,不会被取消) | + +- HostLink 执行(Host 派发、跨设备调用 `node.call_device_action[_async]`、工作站协议子步骤、`--test_mode` 下 + 真实执行的驱动)总有上下文;ROS 2 执行没有框架上下文。HostLink 本地执行、`host_node`、ROS 2 设备节点、 + 跨设备调用都经同一个判定(`client/host/runtime/action.py:bind_action_context`)。 +- 这些参数不属于动作接口:不进 goal schema、必填列表、`placeholder_keys`、生成的端口、物料锁参数与 `goal_default` + (AST 扫描、装饰器与运行时签名推断同一规则,`registry/action_context.py`)。goal 里同名的值被框架的上下文覆盖。 +- 字段含义:`action_id` 是**这一次 attempt** 的标识。调度派发的作业里它就是 attempt 的 job uuid(runtime.v1 + `job_uuid`,`/workflow-node-jobs/{job_uuid}`),每次重试都换一个新值;同一节点的节点运行 uuid(`node_run_uuid`) + 在重试之间不变,驱动拿不到它,需要跨重试稳定的身份时由调用方作为普通参数传入。没有调度作业的调用(跨设备调用、 + 直接调用)里 `action_id` 是随机值。`publish_feedback(data)` 发布动作反馈;`raise_if_cancelled()` / `is_cancelled` + 协作式检查取消(硬超时也会请求取消)。 + schema 的 `x-unilabos-action-contract` 扩展(第 2 版)记录参数与输出顺序、资源模板约束和资源语义,建任务时冻结进执行计划。 手写 YAML 注册表里的 JSON 动作要跑一次 `unilab --complete_registry`,才会按同一标准重新生成 schema; 没有这个扩展的 schema(ROS 动作类型,或还没补全的手写 YAML)不做上面的校验。 @@ -158,6 +191,7 @@ def confirm(self, timeout_seconds: int, assignee_user_ids: list[str]): ... | `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 扩展与以前相同 | | JSON 动作的 `@action(goal={...})` / `result={...}` 重命名 | 去掉:字段名就是参数名 / 返回 TypedDict 的字段名(要改名就改参数名) | +| 按名字注入的动作上下文:参数叫 `action_context` 但没有 `ActionContext` 注解 | 注解为 `Optional[ActionContext]`(`from unilabos.client.host.runtime.action import ActionContext`),名字随意;没有注解的 `action_context` 参数注册时报错(自动动作同样) | 行为上的变化: diff --git a/docs/developer_guide/add_device.md b/docs/developer_guide/add_device.md index f23ac49bb..a7495f3ac 100644 --- a/docs/developer_guide/add_device.md +++ b/docs/developer_guide/add_device.md @@ -907,7 +907,7 @@ async def long_operation(self, duration: float) -> Dict[str, Any]: # 使用通用 DeviceNode,驱动无需判断当前 backend await self._node.sleep(duration) - # ActionContext 可在 ROS 和 HostLink 中发送 feedback、接收取消 + # 需要发布反馈、检查取消时加一个 Optional[ActionContext] 参数(按类型注入,见 action_standard.md) self._status = "idle" return {"success": True, "duration": duration} diff --git a/docs/user_guide/virtual_devices.md b/docs/user_guide/virtual_devices.md index 8544c3ff0..b2d508f18 100644 --- a/docs/user_guide/virtual_devices.md +++ b/docs/user_guide/virtual_devices.md @@ -33,7 +33,8 @@ `{"config": {...}}`(编辑器按旧 `init_param_schema` 生成)内层同样生效。 - 状态用带 `@topic_config` 的属性暴露(`status`、`progress`、`remaining_time`、温度、转速等)。 - 长动作分步推进:每步检查取消、更新进度与剩余时间,并通过 `ActionContext` 发布动作反馈; - 停止类动作(如泵的 `auto-stop_operation`)请求取消正在进行的动作。ROS 2 不注入 `ActionContext`, + 停止类动作(如泵的 `auto-stop_operation`)请求取消正在进行的动作。`ActionContext` 按参数类型注入 + (见 [动作标准](../developer_guide/action_standard.md#动作上下文actioncontext));ROS 2 执行没有框架上下文,可空的参数得到 `None`, 此时动作照常执行,只是不发布这份反馈、不支持取消。 - 失败一律抛异常(参数越界、无法识别的命令等),作业进入失败决策,不会把 `success=False` 当成功返回。 成功时返回字典(`{"success": true, ...}`)。 diff --git a/tests/client/host/hostlink/test_host_node.py b/tests/client/host/hostlink/test_host_node.py index 15df65827..ab9df899c 100644 --- a/tests/client/host/hostlink/test_host_node.py +++ b/tests/client/host/hostlink/test_host_node.py @@ -4,7 +4,7 @@ import threading import time import uuid -from typing import Any +from typing import Any, Optional from unittest.mock import Mock import pytest @@ -73,13 +73,17 @@ def fail(self) -> None: self.calls += 1 raise CommunicationError("device offline") - def wait_until_cancelled(self, action_context: ActionContext) -> None: + def wait_until_cancelled(self, job: ActionContext) -> None: + # 参数名随意:框架按 ActionContext 类型注入,取消经它传到驱动 self.calls += 1 self.started.set() while True: - action_context.raise_if_cancelled() + job.raise_if_cancelled() time.sleep(0.01) + def observe(self, value: int, attempt: Optional[ActionContext] = None) -> dict[str, Any]: + return {"value": value, "action_id": attempt.action_id if attempt is not None else None} + def ignores_cancel(self) -> dict[str, bool]: """同步驱动、不检查取消:取消请求之后仍要跑完。""" self.calls += 1 @@ -143,6 +147,7 @@ def _runtime() -> tuple[HostLinkBackend, AdapterDriver]: "ignores_cancel", "samples", "overruns", + "observe", ), action_value_mappings={ "succeed": {"type": "NativeAction"}, @@ -176,6 +181,7 @@ def _runtime() -> tuple[HostLinkBackend, AdapterDriver]: "ignores_cancel": {"type": "NativeAction"}, "samples": {"type": "UniLabJsonCommand"}, "overruns": {"type": "NativeAction", "timeout": 0.1}, + "observe": {"type": "UniLabJsonCommand"}, }, ) node = local.add_driver(spec) @@ -594,6 +600,28 @@ def test_hostlink_operator_intervention_replaces_failure_result( assert bridge.statuses[-1][2]["raw_return_info"]["suc"] is False +def test_scheduled_job_injects_its_attempt_context_by_type(execution_stack) -> None: + """调度作业:可空的 ActionContext 参数(名字随意)拿到 action_id 就是这次 attempt 的 job uuid。""" + + _adapter, microbackend, _driver, bridge = execution_stack + item = _item("observe") + microbackend.dispatch( + { + "job_id": item.job_id, + "task_id": item.task_id, + "node_id": item.node_id, + "device_id": item.device_id, + "action": item.action_name, + "action_type": "UniLabJsonCommand", + "action_args": {"value": 3}, + } + ) + assert bridge.status_event.wait(2), bridge.statuses + job_id, status, _data, return_info = bridge.statuses[-1] + assert (job_id, status) == (item.job_id, "success") + assert return_info["return_value"] == {"value": 3, "action_id": item.job_id} + + def test_microbackend_cancels_running_hostlink_action(execution_stack) -> None: adapter, microbackend, driver, bridge = execution_stack item = _item("wait_until_cancelled") diff --git a/tests/client/host/runtime/test_action_context_injection.py b/tests/client/host/runtime/test_action_context_injection.py new file mode 100644 index 000000000..6a0233fc9 --- /dev/null +++ b/tests/client/host/runtime/test_action_context_injection.py @@ -0,0 +1,101 @@ +"""框架按类型注入 ``ActionContext``:HostLink 本地执行、跨设备调用与 ROS 2(没有框架上下文)同一个判定。 + +注解为 ``ActionContext`` / ``Optional[ActionContext]`` / ``ActionContext | None`` 的参数都注入,名字随意; +叫 ``action_context`` 却没有这个注解的参数不再特殊。 +""" + +from __future__ import annotations + +from typing import Any, Optional + +from unilabos.client.host.hostlink.local_runtime import HostLinkDriverSpec, HostLinkLocalRuntime +from unilabos.client.host.runtime.action import ActionContext, bind_action_context + + +class ContextDriver: + def __init__(self, device_id: Optional[str] = None, config: Optional[dict] = None) -> None: + self.node: Any = None + self.seen: dict[str, Any] = {} + + def post_init(self, node: Any) -> None: + self.node = node + + def required(self, value: int, job: ActionContext) -> int: + self.seen["required"] = job + return value + + def optional(self, value: int, feedback: Optional[ActionContext] = None) -> int: + self.seen["optional"] = feedback + return value + + async def union(self, value: int, handle: ActionContext | None = None) -> int: + self.seen["union"] = handle + return value + + def untyped(self, value: int, action_context: Any = "unset") -> int: + self.seen["untyped"] = action_context + return value + + def relay(self, target: str) -> int: + return self.node.call_device_action(target, "optional", {"value": 5}) + + +def _runtime() -> HostLinkLocalRuntime: + runtime = HostLinkLocalRuntime() + for device_id in ("caller", "target"): + runtime.add_driver(HostLinkDriverSpec(device_id, ContextDriver, {})) + return runtime + + +def test_hostlink_injects_every_annotated_context_whatever_its_name() -> None: + runtime = _runtime() + runtime.start() + try: + driver = runtime.devices["caller"].driver + context = ActionContext(action_id="job-1") + assert runtime.call_action("caller", "required", value=1, action_context=context) == 1 + assert runtime.call_action("caller", "optional", value=2, action_context=context) == 2 + assert runtime.call_action("caller", "union", value=3, action_context=context) == 3 + assert driver.seen["required"] is context + assert driver.seen["optional"] is context + assert driver.seen["union"] is context + # 调用方没给上下文:HostLink 执行仍有一个(取消、超时靠它),可空的参数同样拿到 + assert runtime.call_action("caller", "optional", value=4) == 4 + assert isinstance(driver.seen["optional"], ActionContext) + finally: + runtime.stop() + + +def test_untyped_action_context_name_is_no_longer_injected() -> None: + runtime = _runtime() + runtime.start() + try: + driver = runtime.devices["caller"].driver + assert runtime.call_action("caller", "untyped", value=1, action_context=ActionContext()) == 1 + assert driver.seen["untyped"] == "unset" + finally: + runtime.stop() + + +def test_cross_device_call_injects_the_target_context_by_type() -> None: + runtime = _runtime() + runtime.start() + try: + assert runtime.call_action("caller", "relay", target="target") == 5 + assert isinstance(runtime.devices["target"].driver.seen["optional"], ActionContext) + finally: + runtime.stop() + + +def test_without_a_framework_context_optional_gets_none_and_required_gets_a_new_one() -> None: + """ROS 2 执行没有框架上下文:可空的得到 None,不可空的总能拿到一个上下文。""" + + driver = ContextDriver() + optional = bind_action_context(driver.optional, {"value": 1}, None) + assert optional == {"value": 1, "feedback": None} + required = bind_action_context(driver.required, {"value": 1}, None) + assert isinstance(required["job"], ActionContext) + assert bind_action_context(driver.untyped, {"value": 1}, None) == {"value": 1} + # goal 里同名的值由框架的上下文覆盖 + context = ActionContext(action_id="job-2") + assert bind_action_context(driver.union, {"value": 1, "handle": "forged"}, context)["handle"] is context diff --git a/tests/registry/test_action_context_by_type.py b/tests/registry/test_action_context_by_type.py new file mode 100644 index 000000000..89fba7e2b --- /dev/null +++ b/tests/registry/test_action_context_by_type.py @@ -0,0 +1,213 @@ +"""框架按类型注入的动作上下文(``ActionContext``)不属于动作接口。 + +注解为 ``ActionContext`` / ``Optional[ActionContext]`` / ``ActionContext | None`` 的参数,不论叫什么名字,都不进 +goal schema、必填列表、``placeholder_keys``、生成的端口、物料锁参数与 ``goal_default``;AST 扫描、装饰器与运行时 +签名推断同一规则。参数叫 ``action_context`` 却没有这个注解(已删除的按名字写法)是注册错误。 +""" + +from __future__ import annotations + +import textwrap +from pathlib import Path +from typing import Any, Optional + +import pytest + +from unilabos.client.host.runtime.action import ActionContext +from unilabos.registry.action_contract_schema import parse_action_contract +from unilabos.registry.action_options import RemovedActionOptionError +from unilabos.registry.ast_registry_scanner import _parse_file +from unilabos.registry.decorators import action +from unilabos.registry.placeholder_type import ResourceSlot +from unilabos.registry.registry import Registry +from unilabos.utils.import_manager import default_manager + +_HEADER = ''' +from typing import Optional +from unilabos.client.host.runtime.action import ActionContext +from unilabos.registry.decorators import action, device +from unilabos.registry.placeholder_type import ResourceSlot +''' + + +def _driver(body: str, *, header: str = _HEADER) -> str: + return textwrap.dedent(header) + textwrap.dedent( + ''' + @device(id="ctx_driver", category=["test"]) + class Driver: + ''' + ) + textwrap.indent(textwrap.dedent(body), " ") + + +def _entry(tmp_path: Path, body: str, *, header: str = _HEADER) -> dict[str, Any]: + path = tmp_path / "ctx_driver.py" + path.write_text(_driver(body, header=header), encoding="utf-8") + devices, _resources, _workflows = _parse_file(path, tmp_path) + return Registry()._build_device_entry_from_ast("ctx_driver", devices[0])["class"]["action_value_mappings"] + + +_TYPED_ACTIONS = ''' +@action(goal_default={"speed": 2.0}) +def run(self, sample: ResourceSlot, speed: float, ctx: ActionContext) -> None: + pass + +@action() +def wait(self, sample: ResourceSlot, feedback: Optional[ActionContext], seconds: int = 1) -> None: + pass + +@action() +def cool(self, sample: ResourceSlot, handle: ActionContext | None = None) -> None: + pass + +def stir(self, sample: ResourceSlot, rpm: int, context: Optional[ActionContext] = None) -> None: + pass +''' + + +@pytest.mark.parametrize( + ("action_name", "context_name", "parameters"), + [ + ("run", "ctx", ["sample", "speed"]), + ("wait", "feedback", ["sample", "seconds"]), + ("cool", "handle", ["sample"]), + ("auto-stir", "context", ["sample", "rpm"]), + ], +) +def test_ast_scan_hides_action_context_parameters_by_type( + tmp_path: Path, action_name: str, context_name: str, parameters: list[str] +) -> None: + entry = _entry(tmp_path, _TYPED_ACTIONS)[action_name] + goal = entry["schema"]["properties"]["goal"] + assert list(goal["properties"]) == parameters + assert context_name not in goal["required"] + assert entry["schema"]["x-unilabos-action-contract"]["input_order"] == parameters + assert context_name not in entry["placeholder_keys"] + assert context_name not in entry["goal_default"] + assert entry["materials_need_lock"] == ["sample"] + handle_keys = {handle["handler_key"] for handle in entry["handles"].get("input", [])} + handle_keys |= {handle["handler_key"] for handle in entry["handles"].get("output", [])} + assert context_name not in handle_keys + assert "sample" in handle_keys + + +def test_ast_scan_metadata_params_skip_typed_context(tmp_path: Path) -> None: + path = tmp_path / "ctx_driver.py" + path.write_text(_driver(_TYPED_ACTIONS), encoding="utf-8") + devices, _resources, _workflows = _parse_file(path, tmp_path) + actions = devices[0]["actions"] + assert [param["name"] for param in actions["run"]["params"]] == ["sample", "speed"] + assert [param["name"] for param in actions["wait"]["params"]] == ["sample", "seconds"] + assert [param["name"] for param in devices[0]["auto_methods"]["stir"]["params"]] == ["sample", "rpm"] + + +def test_ast_scan_recognises_module_import_and_string_annotations(tmp_path: Path) -> None: + header = ''' + import typing + import unilabos.client.host.runtime.action as runtime_action + from unilabos.registry.decorators import action, device + from unilabos.registry.placeholder_type import ResourceSlot + ''' + entry = _entry( + tmp_path, + ''' + @action() + def run(self, sample: ResourceSlot, ctx: typing.Optional[runtime_action.ActionContext]) -> None: + pass + + @action() + def later(self, sample: ResourceSlot, ctx: "runtime_action.ActionContext") -> None: + pass + ''', + header=header, + ) + for name in ("run", "later"): + assert list(entry[name]["schema"]["properties"]["goal"]["properties"]) == ["sample"] + + +def test_parameter_named_action_context_without_the_type_is_a_registration_error(tmp_path: Path) -> None: + for body in ( + ''' + @action() + def run(self, sample: ResourceSlot, action_context=None) -> None: + pass + ''', + ''' + def stir(self, sample: ResourceSlot, action_context: dict = None) -> None: + pass + ''', + ): + path = tmp_path / "ctx_driver.py" + path.write_text(_driver(body), encoding="utf-8") + with pytest.raises(RemovedActionOptionError, match=r"action_context.*Optional\[ActionContext\]"): + _parse_file(path, tmp_path) + + +def test_typed_parameter_named_action_context_is_still_injected(tmp_path: Path) -> None: + entry = _entry( + tmp_path, + ''' + @action() + def run(self, sample: ResourceSlot, action_context: Optional[ActionContext] = None) -> None: + pass + ''', + ) + assert list(entry["run"]["schema"]["properties"]["goal"]["properties"]) == ["sample"] + + +def test_decorator_rejects_untyped_action_context_and_hides_typed_ones() -> None: + with pytest.raises(RemovedActionOptionError, match=r"Optional\[ActionContext\]"): + + @action() + def legacy(self, sample: ResourceSlot, action_context=None) -> None: + pass + + # 上下文参数不是动作参数:placeholder_keys 不能写它 + with pytest.raises(ValueError, match="ctx"): + + @action(placeholder_keys={"ctx": "unilabos_resources"}) + def bad(self, sample: ResourceSlot, ctx: Optional[ActionContext] = None) -> None: + pass + + @action() + def typed(self, sample: ResourceSlot, ctx: ActionContext | None = None) -> None: + pass + + assert typed._action_registry_meta["placeholder_keys"] == {} + + +def test_runtime_signature_inference_skips_typed_context() -> None: + class Driver: + def run(self, sample: ResourceSlot, speed: float, ctx: Optional[ActionContext] = None) -> None: + pass + + def legacy(self, speed: float, action_context=None) -> None: + pass + + assert [arg["name"] for arg in default_manager._analyze_method_signature(Driver().run)["args"]] == [ + "sample", + "speed", + ] + # 不带类型的同名参数不再特殊:当作普通参数(注册时会因上面的规则报错) + assert [arg["name"] for arg in default_manager._analyze_method_signature(Driver().legacy)["args"]] == [ + "speed", + "action_context", + ] + + +def test_action_contract_parser_skips_typed_context() -> None: + import ast + + source = textwrap.dedent( + ''' + from typing import Optional + from unilabos.client.host.runtime.action import ActionContext + + class Driver: + def run(self, speed: float, ctx: Optional[ActionContext] = None) -> dict: + return {} + ''' + ) + module = ast.parse(source) + function = module.body[2].body[0] + contract = parse_action_contract(module, function, module_name="ctx_contract_module") + assert [item["name"] for item in contract.to_dict()["input_contract"]["parameters"]] == ["speed"] diff --git a/tests/registry/test_backend_metadata.py b/tests/registry/test_backend_metadata.py index 544fff7e7..0cf294178 100644 --- a/tests/registry/test_backend_metadata.py +++ b/tests/registry/test_backend_metadata.py @@ -230,7 +230,7 @@ def test_registry_completion_publishes_backend_site_and_policy_defaults( def test_ast_scanner_skips_runtime_injected_parameters(tmp_path) -> None: - """``action_context`` / ``sample_uuids`` 由执行器注入,不得进入动作契约。""" + """``ActionContext`` 参数(按类型识别)/ ``sample_uuids`` 由执行器注入,不得进入动作契约。""" source = tmp_path / "ctx_driver.py" source.write_text( @@ -267,7 +267,7 @@ def test_ast_cache_rejects_previous_metadata_version(tmp_path) -> None: cache = load_scan_cache(cache_path) - assert _CACHE_VERSION == 25 + assert _CACHE_VERSION == 26 assert cache == {"version": _CACHE_VERSION, "files": {}} diff --git a/unilabos/client/host/hostlink/local_runtime.py b/unilabos/client/host/hostlink/local_runtime.py index acd6d8a2d..49bd83160 100644 --- a/unilabos/client/host/hostlink/local_runtime.py +++ b/unilabos/client/host/hostlink/local_runtime.py @@ -21,7 +21,7 @@ Type, ) -from unilabos.client.host.runtime.action import ActionContext +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 @@ -827,9 +827,9 @@ def _resolve_action( mapping = {} kwargs = self._map_action_arguments(signature, mapping, kwargs) kwargs = self._resolve_action_resources(signature, kwargs) + # HostLink 执行总有上下文(取消、超时、反馈都靠它):调用方没给就现建一个,按类型注入驱动 context = action_context or ActionContext() - if "action_context" in signature.parameters: - kwargs.setdefault("action_context", context) + kwargs = bind_action_context(action, kwargs, context) return action, context, kwargs, mapping @staticmethod diff --git a/unilabos/client/host/ros2/base_device_node.py b/unilabos/client/host/ros2/base_device_node.py index ae27e6bda..3f9fcb6aa 100644 --- a/unilabos/client/host/ros2/base_device_node.py +++ b/unilabos/client/host/ros2/base_device_node.py @@ -31,6 +31,7 @@ from rclpy.service import Service 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.async_utils import schedule_async_func from unilabos.registry.decorators import get_topic_config @@ -1285,6 +1286,9 @@ def ACTION(**kwargs): time_start = time.monotonic() time_overall = 100 future = None + if not error_skip and "sequence" not in action_value_mapping: + # ROS 2 执行没有框架上下文:驱动方法上可空的 ActionContext 参数得到 None,不可空的现建一个 + action_kwargs = bind_action_context(ACTION, action_kwargs, None) if not error_skip: # 将阻塞操作放入线程池执行 if inspect.iscoroutinefunction(ACTION): @@ -1579,7 +1583,8 @@ def _execute_driver_command(self, string: str): f"转换ResourceSlot列表参数 {arg_name} 失败: {e}\n{traceback.format_exc()}" ) raise JsonCommandInitError(f"ResourceSlot列表参数转换失败: {arg_name}") - return function(**function_args) + # ROS 2 执行没有框架上下文:可空的 ActionContext 参数得到 None,不可空的现建一个 + return function(**bind_action_context(function, function_args, None)) except KeyError as ex: raise JsonCommandInitError( f"执行动作时JSON缺少function_name或function_args: {ex}\n原JSON: {string}\n{traceback.format_exc()}" @@ -1758,7 +1763,8 @@ async def _execute_driver_command_async(self, string: str): ) raise JsonCommandInitError(f"ResourceSlot列表参数转换失败: {arg_name}") - return await function(**function_args) + # ROS 2 执行没有框架上下文:可空的 ActionContext 参数得到 None,不可空的现建一个 + return await function(**bind_action_context(function, function_args, None)) except KeyError as ex: raise JsonCommandInitError( f"执行动作时JSON缺少function_name或function_args: {ex}\n原JSON: {string}\n{traceback.format_exc()}" diff --git a/unilabos/client/host/runtime/action.py b/unilabos/client/host/runtime/action.py index 6bfdad67e..ad2b6a6ec 100644 --- a/unilabos/client/host/runtime/action.py +++ b/unilabos/client/host/runtime/action.py @@ -73,10 +73,41 @@ def raise_if_cancelled(self) -> None: raise ActionCancelled(f"action cancelled: {self.action_id}") +def bind_action_context( + function: Callable[..., Any], + kwargs: Dict[str, Any], + context: Optional[ActionContext], +) -> Dict[str, Any]: + """按类型给驱动动作注入 :class:`ActionContext`,返回补好参数的新字典(HostLink / ROS 2 / 跨设备调用共用)。 + + 注解为 ``ActionContext``、``Optional[ActionContext]`` 或 ``ActionContext | None`` 的参数都注入,与参数名无关; + goal 里同名的值被框架的上下文覆盖。``context`` 为 ``None`` 表示这次执行没有上下文(如 ROS 2 动作): + 可空的参数得到 ``None``,不可空的参数得到框架现建的上下文。 + """ + + from unilabos.registry.action_context import action_context_parameters + + parameters = action_context_parameters(function) + if not parameters: + return kwargs + bound = dict(kwargs) + created: Optional[ActionContext] = None + for name, optional in parameters.items(): + if context is not None: + bound[name] = context + elif optional: + bound[name] = None + else: + created = created or ActionContext() + bound[name] = created + return bound + + __all__ = [ "ActionCancelled", "ActionContext", "DeviceActionRouter", "FeedbackCallback", "LateResultCallback", + "bind_action_context", ] diff --git a/unilabos/registry/action_context.py b/unilabos/registry/action_context.py new file mode 100644 index 000000000..3eba7e1d6 --- /dev/null +++ b/unilabos/registry/action_context.py @@ -0,0 +1,243 @@ +"""框架注入的动作上下文参数:按类型识别 ``ActionContext``,不看参数名。 + +注解为 ``ActionContext``、``Optional[ActionContext]``、``ActionContext | None``(或 ``Union[ActionContext, None]``) +的参数由框架注入,名字随作者起: + +- 可空的(上面后两种写法,或默认值是 ``None``):没有上下文时(例如 ROS 2 执行、作者直接调用)注入 ``None``; +- 不可空的:总能拿到一个上下文,框架没有时现建一个。 + +这些参数不属于动作接口:注册表 AST 扫描与运行时签名推断按类型把它们排除在 goal schema、必填列表、 +``placeholder_keys``、生成的端口、物料锁参数与 ``goal_default`` 之外。 + +以前按名字注入的写法(参数叫 ``action_context`` 但没有这个类型注解)已删除:装饰器与 AST 扫描都报错, +要求作者注解为 ``Optional[ActionContext]``(见 :mod:`unilabos.registry.action_options`)。 + +本模块只依赖标准库:AST 扫描在线程池里逐文件调用它,不导入 ``ActionContext`` 所在的运行时包, +运行时按类的 ``模块:名字`` 身份比较。 +""" + +from __future__ import annotations + +import ast +import inspect +import types +import typing +from collections.abc import Callable, Mapping +from typing import Any, Optional + +#: ``ActionContext`` 的导入身份(``模块:名字``):定义处与运行时包的再导出。 +ACTION_CONTEXT_IDENTITIES = frozenset( + { + "unilabos.client.host.runtime.action:ActionContext", + "unilabos.client.host.runtime:ActionContext", + } +) +#: 已删除的按名字注入写法的参数名。 +LEGACY_ACTION_CONTEXT_NAME = "action_context" + +_OPTIONAL = frozenset({"typing:Optional", "typing_extensions:Optional"}) +_UNION = frozenset({"typing:Union", "typing_extensions:Union"}) + + +def _is_none(node: ast.AST) -> bool: + return isinstance(node, ast.Constant) and node.value is None + + +def ast_action_context_kind(node: Optional[ast.AST], identity: Callable[[ast.AST], str]) -> Optional[bool]: + """一个参数注解(AST)是不是动作上下文:不是返回 ``None``;``ActionContext`` 返回 ``False``;可空写法返回 ``True``。 + + ``identity`` 把 ``Name`` / ``Attribute`` 换成导入身份(``模块:名字``),由调用方按模块的导入表提供。 + 字符串前向引用(``"Optional[ActionContext]"``)先解析再判断。 + """ + + if node is None: + return None + if isinstance(node, ast.Constant) and isinstance(node.value, str): + try: + parsed = ast.parse(node.value, mode="eval").body + except SyntaxError: + return None + return ast_action_context_kind(parsed, identity) + if isinstance(node, (ast.Name, ast.Attribute)): + return False if identity(node) in ACTION_CONTEXT_IDENTITIES else None + if isinstance(node, ast.Subscript): + origin = identity(node.value) + members = list(node.slice.elts) if isinstance(node.slice, ast.Tuple) else [node.slice] + if origin in _OPTIONAL and len(members) == 1: + return True if ast_action_context_kind(members[0], identity) is not None else None + if origin in _UNION and len(members) == 2 and any(_is_none(member) for member in members): + other = next(member for member in members if not _is_none(member)) + return True if ast_action_context_kind(other, identity) is not None else None + return None + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr): + if _is_none(node.right): + return True if ast_action_context_kind(node.left, identity) is not None else None + if _is_none(node.left): + return True if ast_action_context_kind(node.right, identity) is not None else None + return None + + +def ast_action_context_parameters( + function: ast.FunctionDef | ast.AsyncFunctionDef, + identity: Callable[[ast.AST], str], +) -> dict[str, bool]: + """函数(AST)里由框架注入的上下文参数:``{参数名: 是否可空}``(默认值是 ``None`` 也算可空)。""" + + arguments = function.args + positional = [*arguments.posonlyargs, *arguments.args] + defaults: list[Optional[ast.expr]] = [None] * (len(positional) - len(arguments.defaults)) + list(arguments.defaults) + scheduled = [*zip(positional, defaults), *zip(arguments.kwonlyargs, arguments.kw_defaults)] + result: dict[str, bool] = {} + for argument, default in scheduled: + kind = ast_action_context_kind(argument.annotation, identity) + if kind is not None: + result[argument.arg] = kind or (default is not None and _is_none(default)) + return result + + +def ast_import_identity(imports: Mapping[str, str]) -> Callable[[ast.AST], str]: + """按导入表(``本地名 → 模块:名字`` 或 ``本地名 → 模块``)把 ``Name`` / ``a.b.Name`` 换成导入身份。""" + + def identity(node: ast.AST) -> str: + if isinstance(node, ast.Name): + return str(imports.get(node.id, "")) + if isinstance(node, ast.Attribute): + parts: list[str] = [] + current: ast.AST = node + while isinstance(current, ast.Attribute): + parts.append(current.attr) + current = current.value + if not isinstance(current, ast.Name): + return "" + base = imports.get(current.id) + if not base or ":" in base: + return "" + parts.reverse() + return f"{'.'.join([base, *parts[:-1]])}:{parts[-1]}" + return "" + + return identity + + +def untyped_action_context_message(definition: str) -> str: + """参数叫 ``action_context`` 却没有 ``ActionContext`` 注解时的报错(含新写法)。""" + + return ( + f"动作 {definition} 的参数 {LEGACY_ACTION_CONTEXT_NAME} 没有 ActionContext 类型注解:框架已改为按类型注入," + "不再认参数名。请注解为 Optional[ActionContext](from unilabos.client.host.runtime.action import ActionContext)," + "或换一个参数名" + ) + + +# --------------------------------------------------------------------------- +# 运行时(已导入的函数) +# --------------------------------------------------------------------------- + + +def _object_identity(value: Any) -> str: + module = getattr(value, "__module__", None) + name = getattr(value, "__qualname__", None) or getattr(value, "__name__", None) + return f"{module}:{name}" if isinstance(module, str) and isinstance(name, str) else "" + + +def _is_context_class(value: Any) -> bool: + if not isinstance(value, type): + return False + return any(_object_identity(cls) in ACTION_CONTEXT_IDENTITIES for cls in value.__mro__) + + +def _runtime_kind(annotation: Any) -> Optional[bool]: + if _is_context_class(annotation): + return False + origin = typing.get_origin(annotation) + if origin is typing.Union or origin is types.UnionType: + members = typing.get_args(annotation) + rest = [member for member in members if member is not type(None)] + if len(members) == 2 and len(rest) == 1 and _is_context_class(rest[0]): + return True + return None + + +def _textual_identity(globalns: Mapping[str, Any]) -> Callable[[ast.AST], str]: + """字符串注解求值失败(如只在 ``TYPE_CHECKING`` 下导入)时,按名字与模块全局变量猜身份。""" + + def identity(node: ast.AST) -> str: + name = node.id if isinstance(node, ast.Name) else node.attr if isinstance(node, ast.Attribute) else "" + bound = globalns.get(name) if isinstance(node, ast.Name) else None + if bound is not None: + if _is_context_class(bound): + return next(iter(sorted(ACTION_CONTEXT_IDENTITIES))) + if bound is typing.Optional: + return "typing:Optional" + if bound is typing.Union: + return "typing:Union" + return _object_identity(bound) + if name == "ActionContext": + return next(iter(sorted(ACTION_CONTEXT_IDENTITIES))) + if name in {"Optional", "Union"}: + return f"typing:{name}" + return "" + + return identity + + +def runtime_action_context_kind(annotation: Any, globalns: Mapping[str, Any]) -> Optional[bool]: + """运行时参数注解是不是动作上下文(返回值同 :func:`ast_action_context_kind`);字符串注解按函数的模块全局变量求值。""" + + if annotation is inspect.Parameter.empty: + return None + if isinstance(annotation, str): + try: + annotation = eval(annotation, dict(globalns), {}) # noqa: S307 - 只求值作者写的类型注解 + except Exception: # noqa: BLE001 - 求值不了(TYPE_CHECKING 导入等)退回按文本判断 + try: + parsed = ast.parse(annotation, mode="eval").body + except SyntaxError: + return None + return ast_action_context_kind(parsed, _textual_identity(globalns)) + return _runtime_kind(annotation) + + +def action_context_parameters(function: Callable[..., Any]) -> dict[str, bool]: + """已导入函数里由框架注入的上下文参数:``{参数名: 是否可空}``;签名读不到时返回空。""" + + try: + signature = inspect.signature(function) + except (TypeError, ValueError): + return {} + try: + target = inspect.unwrap(function) + except ValueError: + target = function + globalns = getattr(target, "__globals__", None) or {} + result: dict[str, bool] = {} + for name, parameter in signature.parameters.items(): + if parameter.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD): + continue + kind = runtime_action_context_kind(parameter.annotation, globalns) + if kind is not None: + result[name] = kind or parameter.default is None + return result + + +def untyped_action_context_parameter(function: Callable[..., Any]) -> bool: + """已导入函数是否还用已删除的按名字写法:有 ``action_context`` 参数,但它不是按类型识别的上下文参数。""" + + try: + parameters = inspect.signature(function).parameters + except (TypeError, ValueError): + return False + return LEGACY_ACTION_CONTEXT_NAME in parameters and LEGACY_ACTION_CONTEXT_NAME not in action_context_parameters(function) + + +__all__ = [ + "ACTION_CONTEXT_IDENTITIES", + "LEGACY_ACTION_CONTEXT_NAME", + "action_context_parameters", + "ast_action_context_kind", + "ast_action_context_parameters", + "ast_import_identity", + "runtime_action_context_kind", + "untyped_action_context_message", + "untyped_action_context_parameter", +] diff --git a/unilabos/registry/action_contract_schema.py b/unilabos/registry/action_contract_schema.py index d55027b8e..b413ebf2a 100644 --- a/unilabos/registry/action_contract_schema.py +++ b/unilabos/registry/action_contract_schema.py @@ -7,6 +7,7 @@ from dataclasses import dataclass from typing import Any, Never, Self +from unilabos.registry.action_context import ast_action_context_parameters, ast_import_identity from unilabos.registry.action_result_schema import ( ActionResultSchemaError, parse_action_result_declaration, @@ -34,7 +35,8 @@ _ERROR_MESSAGE = "Action 定义不符合 Workflow 版本 1 合同" _PARSED_ACTION_CONTRACT_TOKEN = object() -_FRAMEWORK_PARAMETERS = frozenset({"sample_uuids", "action_context"}) +#: 按名字识别、由框架注入的参数;动作上下文按类型(``ActionContext``)识别,见 ``_parse_parameters``。 +_FRAMEWORK_PARAMETERS = frozenset({"sample_uuids"}) _ANY = "typing:Any" _DICT = "typing:Dict" _JSON_VALUE = "unilabos.registry.annotations:JSONValue" @@ -518,7 +520,7 @@ def _fail( raise ActionContractError(code, path, message) -def _action_context( +def _is_class_method( module: ast.Module, action: ast.FunctionDef | ast.AsyncFunctionDef, ) -> bool: @@ -721,6 +723,8 @@ def _parse_parameters( material_lock_free: list[str] = [] seen_names: set[str] = set() first_positional = all_positional[0] if all_positional else None + # 框架注入的动作上下文按类型识别(ActionContext / Optional[ActionContext]),不进输入合同 + framework = _FRAMEWORK_PARAMETERS | set(ast_action_context_parameters(action, ast_import_identity(imports))) for argument, default in scheduled: name = getattr(argument, "arg", None) if type(name) is not str or not name: @@ -728,7 +732,7 @@ def _parse_parameters( is_receiver = ( is_method and argument is first_positional and name in {"self", "cls"} ) - if is_receiver or name in _FRAMEWORK_PARAMETERS: + if is_receiver or name in framework: continue parameter_index = len(descriptors) if name in seen_names: @@ -902,7 +906,7 @@ def parse_action_contract( except RecursionError: _fail("/module") - is_method = _action_context(module, action) + is_method = _is_class_method(module, action) ( input_contract, input_templates, diff --git a/unilabos/registry/action_options.py b/unilabos/registry/action_options.py index f32dce496..a7963274f 100644 --- a/unilabos/registry/action_options.py +++ b/unilabos/registry/action_options.py @@ -8,16 +8,20 @@ (ROS 动作类型的 ``goal`` / ``result`` 字段映射照旧); - 参数注解里的 ``Placeholder(...)``:前端选择器写在 ``@action(placeholder_keys={...})``; - 参数注解里的 ``SiteSelector(...)``:库位参数注解为 ``SiteSlot``,库位关系写成 - ``material=Material.site(...)``。 + ``material=Material.site(...)``; +- 按名字注入的动作上下文(参数叫 ``action_context`` 却没有 ``ActionContext`` 注解):框架按类型注入, + 注解为 ``Optional[ActionContext]``(见 :mod:`unilabos.registry.action_context`)。 本模块只依赖标准库:AST 扫描在线程池里逐文件调用它。 """ from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from typing import Any, Dict +from unilabos.registry.action_context import LEGACY_ACTION_CONTEXT_NAME, untyped_action_context_message + #: 任何动作都不再接受的选项 → 新写法。 REMOVED_ACTION_OPTIONS: Dict[str, str] = { "contract": "所有 JSON 动作统一按签名生成并校验 schema,去掉 contract= 即可", @@ -71,12 +75,22 @@ def check_action_options(options: Mapping[str, Any], *, json_action: bool, defin raise RemovedActionOptionError(f"@action 不再接受 {name}=({definition}):{hint}") +def check_action_context_parameter( + parameter_names: Iterable[str], context_parameters: Iterable[str], *, definition: str +) -> None: + """参数叫 ``action_context`` 却不是按类型识别的上下文参数(没有 ``ActionContext`` 注解):报错并给出新写法。""" + + if LEGACY_ACTION_CONTEXT_NAME in set(parameter_names) - set(context_parameters): + raise RemovedActionOptionError(untyped_action_context_message(definition)) + + __all__ = [ "REMOVED_ACTION_OPTIONS", "REMOVED_ANNOTATIONS", "REMOVED_ANNOTATION_IDENTITIES", "REMOVED_JSON_ACTION_OPTIONS", "RemovedActionOptionError", + "check_action_context_parameter", "check_action_options", "removed_annotation_message", ] diff --git a/unilabos/registry/action_schema.py b/unilabos/registry/action_schema.py index daa3dc328..be4a1e21a 100644 --- a/unilabos/registry/action_schema.py +++ b/unilabos/registry/action_schema.py @@ -12,6 +12,8 @@ - 严格解析器不认识的注解:该参数退回注册表原来的签名类型推断。本模块只放一个 ``x-unilabos-infer`` 占位(AST 扫描在线程池里运行,不导入作者模块),由注册表补全; - ``**kwargs``:goal 允许多传字段;``*args``:无法表示,忽略并按定义告警一次; +- 框架注入的参数不进 schema:``sample_uuids``,以及注解为 ``ActionContext`` / ``Optional[ActionContext]`` / + ``ActionContext | None`` 的参数(按类型识别,与名字无关;没有这个注解却叫 ``action_context`` 的是注册错误); - 没有默认值的参数必填,缺了在调度端 / Host 调用前报错,不再补 0 / 空串; - 返回注解:没写不校验(``{}``);``None`` 只接受空返回;``dict`` / ``Dict[str, Any]`` 接受任意对象; 同模块的 ``TypedDict`` / frozen ``dataclass``:具名输出(每个字段一个输出端口,逐字段严格解析, @@ -31,8 +33,13 @@ from collections.abc import Mapping from typing import Any, Dict, List, Optional, Tuple +from unilabos.registry.action_context import ast_action_context_parameters from unilabos.registry.action_contract_schema import _action_value_schema, _has_resource_slot -from unilabos.registry.action_options import REMOVED_ANNOTATION_IDENTITIES, removed_annotation_message +from unilabos.registry.action_options import ( + REMOVED_ANNOTATION_IDENTITIES, + check_action_context_parameter, + removed_annotation_message, +) from unilabos.registry.action_result_schema import ( ActionResultSchemaError, parse_action_result_declaration, @@ -53,8 +60,9 @@ #: 退回推断的字段占位:``{"x-unilabos-infer": {"annotation": "<注解源码>"}}``,注册表补全后移除。 INFER_KEY = "x-unilabos-infer" -#: 由框架注入、不属于动作合同的参数(与 AST 扫描的参数跳过名单一致)。 -FRAMEWORK_PARAMETERS = frozenset({"sample_uuids", "action_context"}) +#: 按名字识别、由框架注入的参数(与 AST 扫描的参数跳过名单一致)。动作上下文按类型识别,见 +#: :func:`framework_parameter_names`。 +FRAMEWORK_PARAMETERS = frozenset({"sample_uuids"}) #: 运行时由 Host 剥离到结果外层的保留返回字段。 RESERVED_RESULT_FIELDS = frozenset({"unilabos_samples"}) @@ -403,6 +411,27 @@ def _strict_field( return field, descriptor, symbols +def framework_parameter_names( + function: ast.FunctionDef | ast.AsyncFunctionDef, + bindings: ModuleBindings, + *, + definition: str, +) -> set[str]: + """不属于动作接口、由框架注入的参数名:``sample_uuids``,加上按类型识别的 ``ActionContext`` 参数。 + + 参数叫 ``action_context`` 却没有 ``ActionContext`` 注解(已删除的按名字注入写法)时报错并给出新写法。 + """ + + context = ast_action_context_parameters(function, bindings.identity) + arguments = function.args + check_action_context_parameter( + (argument.arg for argument in [*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs]), + context, + definition=definition, + ) + return set(FRAMEWORK_PARAMETERS) | set(context) + + def _parameters(function: ast.FunctionDef | ast.AsyncFunctionDef, is_method: bool): arguments = function.args positional = [*arguments.posonlyargs, *arguments.args] @@ -442,6 +471,7 @@ def build_action_schema_draft( definition = definition or action_name reject_removed_annotations(function, bindings, definition=definition) + framework = framework_parameter_names(function, bindings, definition=definition) titles, descriptions, doc_description = _docstring(function) goal: Dict[str, Any] = {} required: List[str] = [] @@ -454,7 +484,7 @@ def build_action_schema_draft( for argument, default_node in _parameters(function, is_method): name = argument.arg - if name in FRAMEWORK_PARAMETERS: + if name in framework: continue has_default = default_node is not NO_DEFAULT default_known, default_value = _literal(default_node) if has_default else (False, None) @@ -782,6 +812,7 @@ def _strip_reserved(schema: Dict[str, Any]) -> None: "ModuleBindings", "build_action_schema_draft", "finalize_action_schema", + "framework_parameter_names", "reject_removed_annotations", "warn_once", ] diff --git a/unilabos/registry/ast_registry_scanner.py b/unilabos/registry/ast_registry_scanner.py index 1b6951a4b..0ac099296 100644 --- a/unilabos/registry/ast_registry_scanner.py +++ b/unilabos/registry/ast_registry_scanner.py @@ -34,6 +34,7 @@ from unilabos.registry.action_schema import ( ModuleBindings, build_action_schema_draft, + framework_parameter_names, reject_removed_annotations, ) from unilabos.registry.material_roles import ( @@ -58,7 +59,7 @@ MAX_SCAN_DEPTH = 10 # 最大目录递归深度 MAX_SCAN_FILES = 1000 # 最大扫描文件数量 -_CACHE_VERSION = 25 # 25:unilabos.backend 与 unilabos.server.backend 拆进 unilabos.client.host / unilabos.server,扫描出的模块路径随之变化 +_CACHE_VERSION = 26 # 26:动作上下文参数按类型(ActionContext)排除,不再按名字 action_context # 允许点号分段(如 liquid_handler.prcxi),与内置 YAML 注册表的命名先例一致; # 点号只用于注册表模板名,设备实例 id(图节点)另有约束。 _DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$") @@ -1092,10 +1093,13 @@ def _extract_class_body( # 已删除的写法(contract= / resource_contract= / JSON 动作的 goal= 与 result=,以及注解里的 # Placeholder / SiteSelector)与装饰器同一套报错:整个文件记为扫描错误,错误信息指出新写法。 check_action_options(action_args, json_action=json_action, definition=definition) + # 框架注入的参数(sample_uuids、按类型识别的 ActionContext)不属于动作接口; + # 叫 action_context 却没有 ActionContext 注解的旧写法在这里报错 + framework = framework_parameter_names(item, bindings, definition=definition) # 手写的前端选择器:键必须是参数名,未知种类告警一次;注册表与类型推出的取并集(手写优先) action_args["placeholder_keys"] = check_placeholder_keys( action_args.get("placeholder_keys"), - parameter_names=_placeholder_parameter_names(item, action_args), + parameter_names=_placeholder_parameter_names(item, action_args, framework), definition=definition, ) canonical_schema = None @@ -1150,7 +1154,7 @@ def _extract_class_body( ) if ignored_lock_options: warn_ignored_material_lock_override(definition, ignored_lock_options) - method_params = _extract_method_params(item, import_map) + method_params = _extract_method_params(item, import_map, skip=framework) # 超时字段与装饰器同一套校验:硬超时必须是正数秒;软超时可以是秒或只引用 # 动作入参的四则运算表达式(归一化为规范字符串写入注册表)。 from unilabos.registry.action_timeout import ( @@ -1225,7 +1229,9 @@ def _extract_class_body( if method_name in ("post_init", "__str__", "__repr__"): continue - method_params = _extract_method_params(item, import_map) + definition = f"{module_name}.{cls_node.name}.{method_name}" + framework = framework_parameter_names(item, bindings, definition=definition) + method_params = _extract_method_params(item, import_map, skip=framework) return_type = _get_annotation_str(item.returns, import_map) is_async = isinstance(item, ast.AsyncFunctionDef) method_doc = ast.get_docstring(item) @@ -1238,7 +1244,6 @@ def _extract_class_body( } if _has_decorator(item, "always_free") and _is_registry_decorator("always_free", import_map): auto_entry["always_free"] = True - definition = f"{module_name}.{cls_node.name}.{method_name}" draft = build_action_schema_draft( item, bindings, action_name=f"auto-{method_name}", definition=definition ) @@ -1267,14 +1272,15 @@ def _store_schema_draft(entry: dict, schema: Optional[dict], draft: dict) -> Non def _placeholder_parameter_names( - item: Union[ast.FunctionDef, ast.AsyncFunctionDef], action_args: Dict[str, Any] + item: Union[ast.FunctionDef, ast.AsyncFunctionDef], action_args: Dict[str, Any], framework: Any = (), ) -> Optional[List[str]]: - """``placeholder_keys`` 可以写的键(规则见 ``placeholder_keys.placeholder_parameter_names``)。""" + """``placeholder_keys`` 可以写的键(规则见 ``placeholder_keys.placeholder_parameter_names``); + ``framework`` 是框架注入、不属于动作接口的参数名。""" arguments = item.args positional = [*arguments.posonlyargs, *arguments.args][1:] return placeholder_parameter_names( - [argument.arg for argument in [*positional, *arguments.kwonlyargs]], + [argument.arg for argument in [*positional, *arguments.kwonlyargs] if argument.arg not in framework], goal=action_args.get("goal"), ros_action=bool(action_args.get("action_type")), parent=bool(action_args.get("parent")), @@ -1300,20 +1306,23 @@ def _material_lock_free_parameters(item: Union[ast.FunctionDef, ast.AsyncFunctio return names -#: 由运行时注入、不属于动作契约的参数:``sample_uuids``(样品映射)与 -#: ``action_context``(反馈/取消上下文,HostLink 执行器按签名注入)。 -_PARAM_SKIP_NAMES = frozenset({"sample_uuids", "action_context"}) +#: 按名字识别、由运行时注入的参数:``sample_uuids``(样品映射)。反馈/取消上下文按类型 +#: (``ActionContext``)识别,由调用方经 ``skip`` 传入(见 ``action_schema.framework_parameter_names``)。 +_PARAM_SKIP_NAMES = frozenset({"sample_uuids"}) def _extract_method_params( func_node: Union[ast.FunctionDef, ast.AsyncFunctionDef], import_map: Optional[Dict[str, str]] = None, + *, + skip: Any = (), ) -> List[dict]: """ Extract parameters from a class method definition. - Automatically skips the first positional argument (self / cls) and any - domain-specific names listed in ``_PARAM_SKIP_NAMES``. + Automatically skips the first positional argument (self / cls), any + domain-specific names listed in ``_PARAM_SKIP_NAMES`` and the names in ``skip`` + (framework-injected ``ActionContext`` parameters, recognised by type). Returns: [{"name": "position", "type": "str", "default": None, "required": True}, ...] @@ -1333,9 +1342,10 @@ def _extract_method_params( num_defaults = len(args.defaults) first_default_idx = num_args - num_defaults + skipped = _PARAM_SKIP_NAMES | set(skip) for i, arg in enumerate(positional_args, start=1): name = arg.arg - if name in _PARAM_SKIP_NAMES: + if name in skipped: continue param_info: dict = {"name": name} @@ -1361,7 +1371,7 @@ def _extract_method_params( # Keyword-only arguments (self/cls never appear here) for i, arg in enumerate(args.kwonlyargs): name = arg.arg - if name in _PARAM_SKIP_NAMES: + if name in skipped: continue param_info: dict = {"name": name} diff --git a/unilabos/registry/decorators.py b/unilabos/registry/decorators.py index 888d433fd..f5c337d66 100644 --- a/unilabos/registry/decorators.py +++ b/unilabos/registry/decorators.py @@ -531,6 +531,13 @@ def wrapper(*args, **kwargs): "parent": parent, } signature_parameters = _inspect.signature(func).parameters + # 框架按类型注入动作上下文(ActionContext / Optional[ActionContext]):这些参数不属于动作接口; + # 叫 action_context 却没有这个注解的旧写法直接报错 + from unilabos.registry.action_context import action_context_parameters + from unilabos.registry.action_options import check_action_context_parameter + + context_parameters = action_context_parameters(func) + check_action_context_parameter(signature_parameters, context_parameters, definition=definition) if resource_contract or site_selectors: from unilabos.registry.material_roles import ( MaterialRoleError, @@ -559,7 +566,7 @@ def wrapper(*args, **kwargs): [ name for name, parameter in signature_parameters.items() - if name not in {"self", "cls"} + if name not in {"self", "cls"} and name not in context_parameters and parameter.kind not in (_inspect.Parameter.VAR_POSITIONAL, _inspect.Parameter.VAR_KEYWORD) ], goal=goal, diff --git a/unilabos/registry/placeholder_keys.py b/unilabos/registry/placeholder_keys.py index f98007cfc..53d39b0aa 100644 --- a/unilabos/registry/placeholder_keys.py +++ b/unilabos/registry/placeholder_keys.py @@ -36,8 +36,9 @@ #: ``PLACEHOLDER_*`` 常量所在模块。 PLACEHOLDER_MODULE = "unilabos.registry.placeholder_type" -#: 由框架注入、不属于动作参数的名字(与 ``action_schema.FRAMEWORK_PARAMETERS`` 一致)。 -_FRAMEWORK_PARAMETERS = frozenset({"sample_uuids", "action_context"}) +#: 按名字识别、由框架注入、不属于动作参数的名字(与 ``action_schema.FRAMEWORK_PARAMETERS`` 一致); +#: 按类型识别的 ``ActionContext`` 参数由调用方先从 ``parameter_names`` 里去掉。 +_FRAMEWORK_PARAMETERS = frozenset({"sample_uuids"}) _warned: set[tuple[str, str]] = set() _warned_lock = threading.Lock() @@ -94,8 +95,8 @@ def placeholder_parameter_names( ) -> Optional[list[str]]: """``placeholder_keys`` 可以写的键(装饰器与 AST 扫描同一规则)。 - ``parameter_names`` 是方法的具名参数(不含 ``self`` / ``cls`` 与 ``*args`` / ``**kwargs``);框架注入的 - ``sample_uuids`` / ``action_context`` 不算。ROS 动作另加 ``goal=`` 映射的字段名。签名未知时返回 None、 + ``parameter_names`` 是方法的具名参数(不含 ``self`` / ``cls`` 与 ``*args`` / ``**kwargs``,也不含按类型识别、 + 框架注入的 ``ActionContext`` 参数);``sample_uuids`` 不算。ROS 动作另加 ``goal=`` 映射的字段名。签名未知时返回 None、 不核对:``parent=True`` 借父类签名,协议动作(``is_protocol=True``)按 ROS 消息字段。 """ diff --git a/unilabos/registry/typed_contract.py b/unilabos/registry/typed_contract.py index 435a73c4b..d1b7f8b77 100644 --- a/unilabos/registry/typed_contract.py +++ b/unilabos/registry/typed_contract.py @@ -13,8 +13,9 @@ from jsonschema import Draft202012Validator, FormatChecker -#: 由框架注入、不属于动作合同的参数:出现在参数里也不算多传字段。 -_FRAMEWORK_PARAMETERS = frozenset({"sample_uuids", "action_context"}) +#: 由框架注入、不属于动作合同的参数:出现在参数里也不算多传字段。``ActionContext`` 参数按类型识别、 +#: 只在 Host 调用驱动时注入,不出现在调度端的参数里。 +_FRAMEWORK_PARAMETERS = frozenset({"sample_uuids"}) #: Host 剥离到结果外层的保留返回字段。 _RESERVED_RESULT_FIELDS = frozenset({"unilabos_samples"}) diff --git a/unilabos/utils/import_manager.py b/unilabos/utils/import_manager.py index 3b76b82ce..d7bc08f18 100644 --- a/unilabos/utils/import_manager.py +++ b/unilabos/utils/import_manager.py @@ -24,6 +24,7 @@ "get_enhanced_class_info", ] +from unilabos.registry.action_context import action_context_parameters from unilabos.resources.resource_tracker import PARAM_SAMPLE_UUIDS from unilabos.utils import logger @@ -294,6 +295,8 @@ def _analyze_method_signature(self, method, skip_unilabos_params: bool = True) - signature = inspect.signature(method) args = [] num_required = 0 + # 框架注入的动作上下文按类型识别(ActionContext / Optional[ActionContext]),与参数名无关 + context_parameters = action_context_parameters(method) if skip_unilabos_params else {} for param_name, param in signature.parameters.items(): # 跳过self参数 @@ -306,8 +309,8 @@ def _analyze_method_signature(self, method, skip_unilabos_params: bool = True) - if param.kind == param.VAR_KEYWORD: # **kwargs continue - # 跳过系统注入参数(sample_uuids / action_context),registry 补全时跳过 - if skip_unilabos_params and param_name in (PARAM_SAMPLE_UUIDS, "action_context"): + # 跳过系统注入参数(sample_uuids、按类型识别的动作上下文),registry 补全时跳过 + if skip_unilabos_params and (param_name == PARAM_SAMPLE_UUIDS or param_name in context_parameters): continue is_required = param.default == inspect.Parameter.empty From c7b6ffe44b3d82f948d8d88974992f8f51a7b99c Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:48:48 +0800 Subject: [PATCH 53/59] feat(workflow): a material parameter can be bound by the Site it occupies A ResourceSlot (or list[ResourceSlot] item) may be given as {"site_uuid": ...} in workflow inputs, node params and ad-hoc action params. Task creation and run preflight share one resolution path: one read of Site facts from the materials authority (POST /inventory/site-admission), then the reference becomes the occupant's {"uuid"}, checked against the parameter's AllowedResourceTemplates, and is frozen into the plan, the attempt params and the task input (material_site_bindings records it). An unknown Site, an empty Site or a wrong template is a preflight error: material_site_invalid on task creation and invalid_material_site in the preflight report, with reason, parameter and Site in the details. --- docs/developer_guide/action_standard.md | 11 +- docs/developer_guide/api_v1_route_map.md | 4 + .../scheduling_and_execution.md | 4 +- tests/server/test_material_site_binding.py | 265 ++++++++++++++++++ unilabos/client/materials/core.py | 12 + unilabos/client/runtime/workflow.py | 7 +- unilabos/protocol/runtime/site_references.py | 35 +++ unilabos/server/api/envelope.py | 3 + unilabos/server/api/materials/inventory.py | 15 + unilabos/server/api/runtime/workflow.py | 12 +- unilabos/server/services/materials/core.py | 7 + .../services/materials/site_admission.py | 81 ++++++ .../runtime/workflow/material_sites.py | 199 +++++++++++++ .../runtime/workflow/run_preflight.py | 16 ++ .../services/runtime/workflow/service.py | 53 +++- .../services/runtime/workflow/value_schema.py | 8 + 16 files changed, 725 insertions(+), 7 deletions(-) create mode 100644 tests/server/test_material_site_binding.py create mode 100644 unilabos/protocol/runtime/site_references.py create mode 100644 unilabos/server/services/materials/site_admission.py create mode 100644 unilabos/server/services/runtime/workflow/material_sites.py diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index 005668d2a..d4dd95e38 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -15,7 +15,7 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) | `Optional[X]`、`X \| None` | 可空 | 严格 | | `x: X = None`(默认值是 `None`) | 同 `Optional[X]` | 严格 | | `Annotated[X, Field(ge=, le=, min_length=, max_length=, title=, description=)]` | 带范围与说明 | 严格 | -| `ResourceSlot` / `list[ResourceSlot]` | 物料引用 `{"uuid": ...}`,加物料锁 | 严格;Host 解析成物料实例 | +| `ResourceSlot` / `list[ResourceSlot]` | 物料引用 `{"uuid": ...}`(或按库位绑定的 `{"site_uuid": ...}`,准入时解析),加物料锁 | 严格;Host 解析成物料实例 | | `DeviceSlot` / `SiteSlot` | 设备 ID / 库位 UUID 字符串 | 严格 | | `SiteSlot` 且写了 `material=Material.site("site", owner=...)` | 库位 UUID,带库位关系(`x-unilabos-site-selector`) | 严格;预检与派发前核对库位归属与占用 | | `dict`、`Dict[str, Any]`、`Mapping` | 任意 JSON 对象 | 只校验是对象 | @@ -31,6 +31,15 @@ ROS 动作类型(`@action(action_type=SendCmd, goal={...}, result={...})`) `{"name": ...}`(派发前由调度器向物料权威解析出 uuid)、上游端口传来的扁平资源树(列表)、uuid 字符串; 能否解析出权威 uuid 由派发前的物料锁检查保证。不可空的物料参数给空值(`{}` / `""` / `[]`)报 「物料参数 … 没有给物料」;可空的物料参数留空等于没给。 +- 物料参数还可以**按库位绑定**:`{"site_uuid": "<库位 uuid>"}`(`list[ResourceSlot]` 的每一项也可以),表示「此刻占着这个 + 库位的物料」。工作流入口参数、节点静态参数、单点动作参数都可以这样写。建任务与运行预检走同一条解析路径 + (`server/services/runtime/workflow/material_sites.py`,物料权威只读事实 `POST /api/v1/inventory/site-admission`): + 换成占用物料的 `{"uuid": ...}`,参数写了 `AllowedResourceTemplates(...)` 时核对占用物料的模板,结果冻结进任务 + (计划节点参数、attempt 参数、任务输入;计划的 `material_site_bindings` 记录哪个参数按哪个库位绑到了哪件物料), + 之后物料被挪走也不改变任务用的物料;从此它就是普通物料参数(默认共享物料锁、派发前核对照旧)。库位不存在、库位为空、 + 物料模板不符都是预检错误:建任务返回 `error.code=material_site_invalid`(1000),`error.details` 带 `reason` + (`site_not_found` / `site_empty` / `template_mismatch`)、`parameter`、`site_uuid`、`node_uuid`;运行预检给 + `invalid_material_site` 检查,细节相同。 - 不认识的写法只会让该参数退回推断,**不会让动作注册失败**。 | 返回注解 | schema | 校验 | diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index 9491eae08..d6049341c 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -307,6 +307,10 @@ Adopting V1's contract on any of these breaks something DEV already relies on. > registered, deleted, its lifecycle, site, the job holding it in an unsettled physical action and the reservations > claiming it; plus the job's reservation with the current lot / content state of each allocation. Read-only, no verdict > (the scheduler classifies; see `scheduling_and_execution.md`). +> Dev-only (2026-11-25): `POST /api/v1/inventory/site-admission` (`{"site_uuids": [...]}`) is the one read the workflow +> service makes at task creation / run preflight to bind material parameters given as `{"site_uuid": ...}`: per Site +> whether it exists, its label and owner, and the occupying material with its template (`module_name`, category). +> Read-only, no verdict (see `action_standard.md`). | class | V1 route | V1 handler | DEV counterpart | note | status (p7-c) | |---|---|---|---|---|---| diff --git a/docs/developer_guide/scheduling_and_execution.md b/docs/developer_guide/scheduling_and_execution.md index 94d516428..b3222a2d5 100644 --- a/docs/developer_guide/scheduling_and_execution.md +++ b/docs/developer_guide/scheduling_and_execution.md @@ -61,7 +61,9 @@ Authority,再创建执行层,因此不存在执行器先于库存权威工 默认 Host 通过本机 Workflow API(edge UI 的写入口)接收定义和 Graph: 1. `PUT /api/v1/workflows/{uuid}/graph` 保存节点和边。 -2. `POST /api/v1/workflow-tasks` 固化 `workflow_snapshot` 和 `execution_plan`。 +2. `POST /api/v1/workflow-tasks` 固化 `workflow_snapshot` 和 `execution_plan`。按库位绑定的物料参数 + (`{"site_uuid": ...}`,见 [动作标准](action_standard.md))在这里换成此刻占着该库位的物料并一起冻结;运行预检 + (`/run-preflight`)走同一条解析路径。 3. `WorkflowService` 调用已绑定的 `BackendScheduler.submit(task_uuid)`。 4. Scheduler 从持久化 Task/节点运行构建 `TaskDag`,恢复已完成节点后开始走图。 diff --git a/tests/server/test_material_site_binding.py b/tests/server/test_material_site_binding.py new file mode 100644 index 000000000..bb18ab676 --- /dev/null +++ b/tests/server/test_material_site_binding.py @@ -0,0 +1,265 @@ +"""物料参数按库位绑定:``{"site_uuid": ...}`` 在建任务 / 运行预检时解析成占着该库位的物料并冻结。 + +节点参数、工作流入口参数(ResourceSlot)与单点动作参数都可以这样写;参数写了 ``AllowedResourceTemplates`` 时核对 +占用物料的模板。库位不存在、库位为空、模板不符是预检错误(``material_site_invalid``,``reason`` 分别为 +``site_not_found`` / ``site_empty`` / ``template_mismatch``)。解析结果冻结进任务:之后物料被挪走,任务仍用同一件 +物料;之后它就是普通物料参数(默认共享物料锁)。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +import pytest +from fastapi.testclient import TestClient + +from tests.server.test_scheduler_inventory_authority import _material, _mutation +from tests.server.test_workflow_inventory_recovery import Stack +from tests.server.test_workflow_parallel_execution import Executor, wait_for +from unilabos.protocol.materials import ( + MaterialIdentityWrite, + MaterialMove, + MaterialNodeCreate, + MaterialTreeCreate, + ResourceTemplateWrite, + SiteCreate, +) +from unilabos.protocol.runtime.site_references import material_at_site +from unilabos.registry.workflows import upsert_workflow +from unilabos.server.api.runtime.workflow import create_workflow_app +from unilabos.server.scheduler.service import BackendScheduler +from unilabos.server.services.runtime.workflow.service import WorkflowError + +SAMPLE_SYMBOL = "lab.samples:Tube" +_LOCK = {"type": "object", "properties": {"uuid": {"type": "string", "format": "uuid"}}, "required": ["uuid"], + "x-unilabos-material-lock": True} + + +def _schema(*, symbols: tuple[str, ...] = ()) -> dict: + return { + "x-unilabos-action-contract": { + "version": 2, "resource_template_symbols": {"goal": {"sample": list(symbols)} if symbols else {}}}, + "properties": { + "goal": { + "type": "object", + "properties": { + "sample": _LOCK, + "batch": {"type": ["array", "null"], "items": _LOCK, "default": None}, + }, + "required": ["sample"], + }, + "result": {}, + }, + } + + +def _template(stack: Stack, name: str, module_name: str | None = None) -> None: + stack.materials.put_template(_mutation("put_template"), ResourceTemplateWrite( + template_uuid=f"{name}-template", name=name, display_name=name, resource_type="container", + class_name="Container", module_name=module_name)) + + +def _rack(stack: Stack) -> tuple[str, dict[str, str]]: + """一个三位样品架:A、B 位各有一支管,C 位空着。""" + + _template(stack, "rack") + _template(stack, "tube", SAMPLE_SYMBOL) + + 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="rack", identity=identity("rack", "rack"), sites=[ + SiteCreate(template_name="slot", site_index=0, label="A", occupied_client_ref="tube-a"), + SiteCreate(template_name="slot", site_index=1, label="B", occupied_client_ref="tube-b"), + SiteCreate(template_name="slot", site_index=2, label="C")]), + MaterialNodeCreate(client_ref="tube-a", parent_client_ref="rack", identity=identity("tube-a", "tube")), + MaterialNodeCreate(client_ref="tube-b", parent_client_ref="rack", identity=identity("tube-b", "tube")), + ])).data + rack = tree.client_ref_map["rack"] + sites = {site.label: site.site_uuid for site in stack.materials.get_material(rack).sites} + return rack, {**sites, "tube-a": tree.client_ref_map["tube-a"], "tube-b": tree.client_ref_map["tube-b"]} + + +def _node(param: dict) -> dict: + return {"uuid": str(uuid4()), "name": "处理样品", "type": "device_action", "material_uuid": str(uuid4()), + "action_name": "process", "meta_data": {"target_device_id": "processor"}, "param": param} + + +def _workflow(stack: Stack, nodes: list[dict], *, io: dict | None = None, schema: dict | None = None) -> dict: + stack.workflow.configure_preflight(materials=stack.client, endpoints=lambda: [], + action_schema_resolver=lambda *_: schema or _schema()) + payload = {"workflow_uuid": str(uuid4()), "name": "按库位取样", "description": "", "tags": [], "edges": [], + "nodes": nodes} + if io is not None: + payload["io"] = io + return upsert_workflow(stack.workflow, payload) + + +def _create(stack: Stack, record: dict, input_value: dict | None = None) -> dict: + return stack.workflow.create_workflow_task(workflow_uuid=record["uuid"], run_mode="normal", target_node_uuid=None, + input_value=input_value or {}, description=None, meta_data={}) + + +def test_node_param_bound_by_site_is_frozen_to_the_occupant_and_locked(tmp_path) -> None: + stack, executor = Stack(tmp_path), Executor() + scheduler = None + try: + _rack_uuid, refs = _rack(stack) + node = _node({"sample": material_at_site(refs["A"]), "batch": [{"site_uuid": refs["B"]}]}) + record = _workflow(stack, [node]) + task = _create(stack, record) + [planned] = task["execution_plan"]["nodes"] + assert planned["param"]["sample"] == {"uuid": refs["tube-a"]} + assert planned["param"]["batch"] == [{"uuid": refs["tube-b"]}] + assert {(item["parameter"], item["site_uuid"], item["material_uuid"]) + for item in task["execution_plan"]["material_site_bindings"]} == { + ("sample", refs["A"], refs["tube-a"]), ("batch", refs["B"], refs["tube-b"])} + [job] = stack.workflow.list_workflow_node_jobs(task["uuid"]) + assert job["param"]["sample"] == {"uuid": refs["tube-a"]} + + # 建任务之后管子被挪走、另一支管子放进 A 位:任务仍用冻结的那一支 + stack.materials.move_material(_mutation("move_material"), + MaterialMove(material_uuid=refs["tube-a"], destination_site_uuid=refs["C"])) + stack.materials.move_material(_mutation("move_material"), + MaterialMove(material_uuid=refs["tube-b"], destination_site_uuid=refs["A"])) + scheduler = BackendScheduler(stack.workflow, executor, materials_gateway=stack.client, + materials_need_lock_resolver=lambda *_: ["sample", "batch"]) + stack.workflow.set_task_submitter(scheduler.submit) + scheduler.submit(task["uuid"]) + wait_for(lambda: len(executor.dispatched) == 1) + payload = executor.dispatched[0] + assert payload["action_args"]["sample"] == {"uuid": refs["tube-a"]} + # 之后就是普通物料参数:默认共享物料锁锁住冻结的物料 + held = [request for request in scheduler.resource_snapshot().requests if request.owner_uuid == payload["job_id"]] + assert held and refs["tube-a"] in str(held[0].identifiers) + executor.finish(0, {}) + wait_for(lambda: stack.workflow.get_workflow_task(task["uuid"])["status"] == "succeeded") + finally: + if scheduler is not None: + scheduler.stop() + stack.close() + + +def test_resource_slot_workflow_input_bound_by_site_freezes_the_task_input(tmp_path) -> None: + stack = Stack(tmp_path) + try: + _rack_uuid, refs = _rack(stack) + node = _node({"sample": {"kind": "workflow_input", "parameter": "sample"}}) + io = {"input_contract": {"version": 1, "parameters": [ + {"name": "sample", "schema": {"$slot": "ResourceSlot"}, "required": True}]}, + "output_contract": {"version": 1, "outputs": [ + {"name": "sample", "schema": {"$slot": "ResourceSlot"}, "implicit": True}]}, + "output_bindings": {"sample": {"kind": "workflow_input", "parameter": "sample"}}} + record = _workflow(stack, [node], io=io, schema=_schema(symbols=(SAMPLE_SYMBOL,))) + task = _create(stack, record, {"sample": {"site_uuid": refs["B"]}}) + assert task["input"] == {"sample": {"uuid": refs["tube-b"]}} + [planned] = task["execution_plan"]["nodes"] + assert planned["param"]["sample"] == {"uuid": refs["tube-b"]} + # 暂停改参会按 entry_param_template 重新代入:模板里仍是入口参数引用,代入的是冻结的输入 + assert planned["entry_param_template"]["sample"] == {"kind": "workflow_input", "parameter": "sample"} + finally: + stack.close() + + +@pytest.mark.parametrize("case", ["unknown", "empty", "template"]) +def test_unknown_empty_or_wrong_type_site_is_a_preflight_error(tmp_path, case: str) -> None: + stack = Stack(tmp_path) + try: + _rack_uuid, refs = _rack(stack) + site = {"unknown": str(uuid4()), "empty": refs["C"], "template": refs["A"]}[case] + symbols = ("lab.samples:Vial",) if case == "template" else () + record = _workflow(stack, [_node({"sample": {"site_uuid": site}})], schema=_schema(symbols=symbols)) + reason = {"unknown": "site_not_found", "empty": "site_empty", "template": "template_mismatch"}[case] + + with pytest.raises(WorkflowError) as caught: + _create(stack, record) + assert caught.value.code == "material_site_invalid" + assert caught.value.details["reason"] == reason + assert caught.value.details["parameter"] == "sample" and caught.value.details["site_uuid"] == site + assert site in caught.value.message and "sample" 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"]}).json() + assert response["code"] == 1000 and response["error"]["code"] == "material_site_invalid" + assert response["error"]["details"]["reason"] == reason + # 运行预检走同一条解析路径 + report = client.post(f"/api/v1/workflows/{record['uuid']}/run-preflight", json={}).json()["data"] + assert report["status"] == "invalid" + [blocked] = [item for item in report["checks"] if item["blocking"]] + assert blocked["code"] == "invalid_material_site" and blocked["details"]["reason"] == reason + finally: + stack.close() + + +def test_preflight_reports_the_bound_material_without_writes(tmp_path) -> None: + stack = Stack(tmp_path) + try: + _rack_uuid, refs = _rack(stack) + record = _workflow(stack, [_node({"sample": {"site_uuid": refs["A"]}})], schema=_schema(symbols=(SAMPLE_SYMBOL,))) + report = stack.workflow.preflight_workflow(workflow_uuid=record["uuid"], run_mode="normal", + target_node_uuid=None, input_value={}) + [bound] = [item for item in report["checks"] if item["code"] == "material_sites_bound"] + assert bound["details"]["bindings"][0]["material_uuid"] == refs["tube-a"] + assert not any(item["code"] == "invalid_action_parameters" for item in report["checks"]) + assert stack.workflow.list_tasks(page=1, page_size=10)["items"] == [] + finally: + stack.close() + + +def test_ad_hoc_device_action_param_bound_by_site(tmp_path) -> None: + stack = Stack(tmp_path) + try: + _rack_uuid, refs = _rack(stack) + stack.workflow.configure_preflight(materials=stack.client, action_schema_resolver=lambda *_: _schema()) + task = stack.workflow.create_ad_hoc_device_action_task( + device_id="processor", action_name="process", param={"sample": {"site_uuid": refs["A"]}}, + description=None, meta_data={}) + [job] = stack.workflow.list_workflow_node_jobs(task["uuid"]) + assert job["param"]["sample"] == {"uuid": refs["tube-a"]} + with pytest.raises(WorkflowError) as caught: + stack.workflow.create_ad_hoc_device_action_task( + device_id="processor", action_name="process", param={"sample": {"site_uuid": refs["C"]}}, + description=None, meta_data={}) + assert caught.value.details["reason"] == "site_empty" + finally: + stack.close() + + +def test_http_materials_gateway_reads_the_same_site_facts(tmp_path, monkeypatch) -> None: + """调度权威与物料权威分开部署时经 ``POST /inventory/site-admission`` 读同一份库位事实。""" + + from fastapi import FastAPI + + from tests.server.test_v1_inventory_api import _TestClientOpener + from unilabos.client.materials import HTTPMaterialsClient + from unilabos.server.api.materials import install_materials_api + + stack = Stack(tmp_path) + try: + _rack_uuid, refs = _rack(stack) + app = FastAPI() + install_materials_api(app, stack.materials) + with TestClient(app) as client: + monkeypatch.setattr("unilabos.client.materials.core.urlopen", _TestClientOpener(client)) + gateway = HTTPMaterialsClient("http://testserver") + payload = {"site_uuids": [refs["A"], refs["C"], "missing"]} + facts = gateway.site_admission_facts(payload) + assert facts == stack.client.site_admission_facts(payload) + assert facts["sites"][refs["A"]]["occupant"]["material_uuid"] == refs["tube-a"] + assert facts["sites"][refs["A"]]["occupant"]["module_name"] == SAMPLE_SYMBOL + assert facts["sites"][refs["C"]]["occupant"] is None + assert facts["sites"]["missing"] == {"site_uuid": "missing", "exists": False} + finally: + stack.close() + + +def test_resource_slot_input_schema_accepts_the_site_form() -> None: + from unilabos.server.services.runtime.workflow.value_schema import WorkflowValueSchemaError, validate_value + + site = str(uuid4()) + assert validate_value({"$slot": "ResourceSlot"}, {"site_uuid": site.upper()}) == {"site_uuid": site} + with pytest.raises(WorkflowValueSchemaError): + validate_value({"$slot": "ResourceSlot"}, {"site_uuid": "A1"}) diff --git a/unilabos/client/materials/core.py b/unilabos/client/materials/core.py index 1696b3f27..2a3bc4785 100644 --- a/unilabos/client/materials/core.py +++ b/unilabos/client/materials/core.py @@ -134,6 +134,11 @@ def material_sanity_facts(self, payload: dict[str, Any]) -> dict[str, Any]: return self.service.material_sanity_facts( list(payload.get("material_uuids") or []), reservation_uuid=payload.get("reservation_uuid")) + def site_admission_facts(self, payload: dict[str, Any]) -> dict[str, Any]: + """任务准入时的只读库位事实:``{"site_uuids": [...]}``(物料参数按库位绑定引用的库位)。""" + + return self.service.site_admission_facts(site_uuids=list(payload.get("site_uuids") or [])) + def validate_material_execution(self, value): return self.service.executions.validate(value) @@ -544,6 +549,13 @@ def material_sanity_facts(self, payload: dict[str, Any]) -> dict[str, Any]: "reservation_uuid": payload.get("reservation_uuid"), }, root=True) + def site_admission_facts(self, payload: dict[str, Any]) -> dict[str, Any]: + """任务准入时的只读库位事实(``POST /inventory/site-admission``,不写库)。""" + + return self._request("POST", "/inventory/site-admission", { + "site_uuids": list(payload.get("site_uuids") or []), + }, root=True) + def _command(self, mutation: InventoryMutation, value: Any, *, target_uuid: Optional[str] = None) -> Any: """``materials.v1`` 变更经统一命令入口;拒绝结果按业务码还原成 HTTP 语义的异常。""" diff --git a/unilabos/client/runtime/workflow.py b/unilabos/client/runtime/workflow.py index 25ea25bfe..7dea6feb2 100644 --- a/unilabos/client/runtime/workflow.py +++ b/unilabos/client/runtime/workflow.py @@ -372,7 +372,12 @@ def create_task( input_value: Optional[Mapping[str, Any]] = None, operation_id: Optional[str] = None, ) -> dict[str, Any]: - """创建整图任务;``input_value`` 是工作流入口参数(按 input_contract 校验,未声明合同只接受 ``{}``)。""" + """创建整图任务;``input_value`` 是工作流入口参数(按 input_contract 校验,未声明合同只接受 ``{}``)。 + + 物料参数(``ResourceSlot``)可以按库位绑定:给 ``{"site_uuid": 库位 uuid}`` + (``unilabos.protocol.runtime.site_references.material_at_site``),表示此刻占着该库位的物料, + 服务端建任务时解析并冻结。 + """ operation_id = operation_id or str(uuid4()) return self._http.post( diff --git a/unilabos/protocol/runtime/site_references.py b/unilabos/protocol/runtime/site_references.py new file mode 100644 index 000000000..ded0cc1f4 --- /dev/null +++ b/unilabos/protocol/runtime/site_references.py @@ -0,0 +1,35 @@ +"""按库位给参数值的线上形态(服务端识别、客户端构造共用)。 + +- 物料参数(``ResourceSlot`` / ``list[ResourceSlot]``)按库位绑定:``{"site_uuid": "<库位 uuid>"}``, + 表示「此刻占着这个库位的物料」。建任务 / 运行预检时解析成占用物料的 ``{"uuid": ...}`` 并冻结进任务, + 之后物料被挪走也不改变任务用的是哪件物料。 + +只认恰好一个键的对象:带 ``uuid`` 的照旧是普通物料引用。 +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, Optional + +from unilabos.protocol.runtime.workflow import validate_uuid + +#: 物料参数按库位绑定的键 +SITE_UUID_KEY = "site_uuid" + + +def material_at_site(site_uuid: str) -> dict[str, str]: + """构造「占着这个库位的物料」引用(物料参数的值)。""" + + return {SITE_UUID_KEY: validate_uuid(site_uuid)} + + +def site_reference(value: Any) -> Optional[str]: + """``{"site_uuid": ...}`` 返回库位 uuid(原样,未规范化),否则 ``None``。""" + + if isinstance(value, Mapping) and len(value) == 1 and isinstance(value.get(SITE_UUID_KEY), str): + return value[SITE_UUID_KEY] + return None + + +__all__ = ["SITE_UUID_KEY", "material_at_site", "site_reference"] diff --git a/unilabos/server/api/envelope.py b/unilabos/server/api/envelope.py index b43bcf88a..a8b4e0a7e 100644 --- a/unilabos/server/api/envelope.py +++ b/unilabos/server/api/envelope.py @@ -287,6 +287,7 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "invalid_material_source", "material_flow_fan_out", "material_template_mismatch", + "material_site_invalid", }) _WORKFLOW_NOT_FOUND = frozenset({"not_found", "workflow_not_found", "workflow_template_not_found"}) _WORKFLOW_CONFLICT = frozenset({ @@ -324,6 +325,8 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "debug_task_conflict", "device_action_not_allowed", "preflight_failed", + # 物料参数按库位绑定失败(库位不存在 / 为空 / 模板不符,细节在 error.details) + "material_site_invalid", }) diff --git a/unilabos/server/api/materials/inventory.py b/unilabos/server/api/materials/inventory.py index 51012d300..b2f1dda38 100644 --- a/unilabos/server/api/materials/inventory.py +++ b/unilabos/server/api/materials/inventory.py @@ -11,6 +11,7 @@ - ``POST /inventory/material-io/check`` 是工作流人工装入 / 取走 / 补量步骤确认前的试运行(不写库);确认后的写入 走统一命令入口的 ``material.io`` 类型化命令。 - ``POST /inventory/material-sanity`` 是调度器派发前物料健全性检查的一次只读事实(不写库,不做判定)。 +- ``POST /inventory/site-admission`` 是建任务 / 运行预检时按库位绑定物料参数的一次只读库位事实(不写库,不做判定)。 """ from __future__ import annotations @@ -69,6 +70,13 @@ class MaterialSanityRequest(BaseModel): reservation_uuid: Optional[str] = None +class SiteAdmissionRequest(BaseModel): + """任务准入时要读的库位:物料参数按库位绑定(``{"site_uuid"}``)引用的库位。""" + + model_config = ConfigDict(extra="forbid") + site_uuids: List[str] = Field(default_factory=list, max_length=2000) + + def _code_of(exc: BaseException) -> int: api_error = to_api_error(exc, RESOURCE) return api_error.code if api_error is not None else INTERNAL_ERROR @@ -148,6 +156,13 @@ def material_sanity(body: MaterialSanityRequest) -> Any: return service.material_sanity_facts(body.material_uuids, reservation_uuid=body.reservation_uuid) + @router.post("/site-admission") + def site_admission(body: SiteAdmissionRequest) -> Any: + """建任务 / 运行预检时读一次:物料参数按库位绑定(``{"site_uuid"}``)引用的库位是否存在、此刻被哪件物料 + 占着(模板、``module_name``、类别)。只读不写;绑定成功与否由工作流服务判定。""" + + return service.site_admission_facts(site_uuids=body.site_uuids) + @router.get("/commands/processed") def processed_commands(limit: int = Query(default=200, ge=1, le=500)) -> Any: return {"commands": commands.processed(limit=limit)} diff --git a/unilabos/server/api/runtime/workflow.py b/unilabos/server/api/runtime/workflow.py index 1aef8da56..05c635b3d 100644 --- a/unilabos/server/api/runtime/workflow.py +++ b/unilabos/server/api/runtime/workflow.py @@ -298,12 +298,16 @@ class WorkflowTaskCreateRequest(_StrictModel): device_id: str = "" action_name: str = "" action_type: str = "" - param: Dict[str, Any] = Field(default_factory=dict) + param: Dict[str, Any] = Field(default_factory=dict, description=( + "单点设备动作的参数。物料参数可以给 {\"site_uuid\": 库位 uuid}(此刻占着该库位的物料),建任务时解析并冻结")) execution_policy: Dict[str, Any] = Field(default_factory=dict) execution_timeout_seconds: int = 0 idempotency_key: Optional[str] = None #: 整图任务的入口参数(工作流 input_contract);未声明合同的工作流只接受 {}。 - input: Dict[str, Any] = Field(default_factory=dict) + input: Dict[str, Any] = Field(default_factory=dict, description=( + "整图任务的入口参数(工作流 input_contract)。物料参数(ResourceSlot)可以给 {\"site_uuid\": 库位 uuid}," + "表示此刻占着该库位的物料:建任务时解析成占用物料的 {\"uuid\"} 并冻结进任务;库位不存在、为空或物料模板不符时" + "拒绝(error.code=material_site_invalid,error.details.reason 为 site_not_found / site_empty / template_mismatch)")) #: V1 任务优先级:normal 普通任务,high 高优先级任务(随任务持久化,排序由调度器负责) priority: Literal["normal", "high"] = "normal" #: V1 库存绑定:建任务时落到冻结计划里对应的库存需求,决定预留哪份试剂 / 当前内容物 @@ -343,7 +347,9 @@ class WorkflowPreflightRequest(_BackendModel): run_mode: str = "normal" target_node_uuid: Optional[str] = None - input: Dict[str, Any] = Field(default_factory=dict) + input: Dict[str, Any] = Field(default_factory=dict, description=( + "候选入口参数;物料参数按库位绑定({\"site_uuid\"})与建任务同一条解析路径," + "解析失败报 invalid_material_site 检查(details.reason 同建任务)")) inventory_bindings: List[WorkflowInventoryBindingRequest] = Field(default_factory=list) #: dev 扩展:工作流修订乐观锁(V1 无此字段) expected_revision: Optional[int] = Field(default=None, ge=1, strict=True) diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index 29c69fda2..a23954f6e 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -1389,6 +1389,13 @@ def material_sanity_facts( return material_sanity_facts(self, material_uuids, reservation_uuid=reservation_uuid) + def site_admission_facts(self, *, site_uuids: Sequence[str] = ()) -> dict[str, Any]: + """任务准入时按库位绑定物料要的只读库位事实(不写库、不判定),见 ``materials/site_admission.py``。""" + + from .site_admission import site_admission_facts + + return site_admission_facts(self, site_uuids=site_uuids) + def _candidate_inventory_lots( self, requirement: InventoryRequirement, diff --git a/unilabos/server/services/materials/site_admission.py b/unilabos/server/services/materials/site_admission.py new file mode 100644 index 000000000..15ed458ca --- /dev/null +++ b/unilabos/server/services/materials/site_admission.py @@ -0,0 +1,81 @@ +"""任务准入时读的库位事实(调度权威的工作流服务消费,只读不写、不做判定)。 + +物料参数按库位绑定(``{"site_uuid": ...}``)在建任务 / 运行预检时解析:这里读库位此刻的占用物料及其模板 +(模板名、``module_name``、类别),由工作流服务换成 ``{"uuid": 占用物料}`` 并冻结进任务。 +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any, Optional + + +def _template_facts(service: Any, template_uuid: str) -> dict[str, Any]: + try: + template = service.get_template(template_uuid) + except Exception: # noqa: BLE001 - 模板读不到时只给身份,由调用方按「模板不符」处理 + return {"template_uuid": template_uuid, "module_name": None, "category": []} + return { + "template_uuid": template.template_uuid, + "module_name": template.module_name, + "category": list(template.category or []), + } + + +def _material_facts(service: Any, material_uuid: str) -> Optional[dict[str, Any]]: + from .store import MaterialsRepository + + record = MaterialsRepository.get_material(service, material_uuid) + if record is None or record.deleted_at_ms is not None: + return None + return { + "material_uuid": record.material_uuid, + "display_name": record.display_name, + "template_name": record.template_name, + "lifecycle_status": record.lifecycle_status, + **_template_facts(service, record.template_uuid), + } + + +def site_admission_facts(service: Any, *, site_uuids: Iterable[str] = ()) -> dict[str, Any]: + """一次读出按库位绑定要的事实:``{"sites": {site_uuid: {...}}}``。 + + 不存在(或已删除)的库位 ``exists=False``;存在的给 ``label``、所属物料、占用物料 ``occupant`` + (``material_uuid`` / ``template_uuid`` / ``template_name`` / ``module_name`` / ``category`` / + ``lifecycle_status``;空库位为 ``None``)。 + """ + + from .store import MaterialsRepository + + identities = sorted({str(item).strip() for item in site_uuids if str(item or "").strip()}) + with service._write_lock: + conn = service.connection + # 同一个读事务:库位占用与占用物料是同一时刻的事实 + nested = conn.in_transaction + if not nested: + conn.execute("BEGIN") + try: + sites: dict[str, Any] = {} + for identity in identities: + site = MaterialsRepository.get_site(service, identity) + if site is None: + sites[identity] = {"site_uuid": identity, "exists": False} + continue + occupant = ( + _material_facts(service, site.occupied_material_uuid) if site.occupied_material_uuid else None + ) + sites[identity] = { + "site_uuid": identity, + "exists": True, + "label": site.label, + "owner_material_uuid": site.owner_material_uuid, + "occupied_material_uuid": site.occupied_material_uuid, + "occupant": occupant, + } + return {"sites": sites} + finally: + if not nested: + conn.rollback() + + +__all__ = ["site_admission_facts"] diff --git a/unilabos/server/services/runtime/workflow/material_sites.py b/unilabos/server/services/runtime/workflow/material_sites.py new file mode 100644 index 000000000..6ae4dae3e --- /dev/null +++ b/unilabos/server/services/runtime/workflow/material_sites.py @@ -0,0 +1,199 @@ +"""物料参数按库位绑定:``{"site_uuid": ...}`` 在准入时解析成占着该库位的物料并冻结进任务。 + +物料参数(``ResourceSlot`` / ``list[ResourceSlot]``)可以给 ``{"site_uuid": "<库位 uuid>"}``,表示「此刻占着这个 +库位的物料」:工作流入口参数、节点静态参数、单点动作参数都可以这样写。建任务与运行预检走同一条路径: + +1. :func:`site_references` 收集要读的库位(入口参数与图里节点参数的顶层值、列表元素); +2. 一次向物料权威读库位事实(``materials.site_admission_facts``,只读); +3. :func:`bind_material_sites` 把计划节点参数(含暂停改参时重新代入用的 ``entry_param_template``)与任务输入里的 + ``{"site_uuid"}`` 换成占用物料的 ``{"uuid": ...}``。参数写了 ``AllowedResourceTemplates(...)`` 时核对占用物料的模板。 + +之后它就是普通物料参数:默认共享物料锁、派发前的物料核对照旧。库位不存在、库位是空的、占用物料不是参数允许的模板 +都是预检错误(:class:`MaterialSiteError`,``reason`` 分别为 ``site_not_found`` / ``site_empty`` / +``template_mismatch``),消息里写明库位与参数。 +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import Any, Optional + +from unilabos.protocol.runtime.site_references import site_reference + +#: 预检 / 建任务错误的 ``reason`` +SITE_NOT_FOUND = "site_not_found" +SITE_EMPTY = "site_empty" +TEMPLATE_MISMATCH = "template_mismatch" + + +class MaterialSiteError(ValueError): + """按库位绑定的物料参数解析不出来(预检错误):``reason`` 见模块说明,``details`` 带库位与参数。""" + + def __init__( + self, reason: str, message: str, *, parameter: str, site_uuid: str, node_uuid: Optional[str] = None, + ) -> None: + super().__init__(message) + self.reason = reason + self.message = message + self.details: dict[str, Any] = {"reason": reason, "parameter": parameter, "site_uuid": site_uuid} + if node_uuid is not None: + self.details["node_uuid"] = node_uuid + + +def _values(value: Any) -> Iterable[Any]: + """参数值本身及其列表元素(``list[ResourceSlot]`` 的每一项都可以按库位绑定)。""" + + yield value + if isinstance(value, list): + yield from value + + +def site_references(params: Iterable[Mapping[str, Any]]) -> set[str]: + """一组参数(节点参数 / 任务输入)里按库位绑定的库位 uuid。""" + + found: set[str] = set() + for param in params: + for value in (param or {}).values(): + for item in _values(value): + identity = site_reference(item) + if identity is not None: + found.add(identity) + return found + + +def graph_site_references(graph: Mapping[str, Any], input_value: Mapping[str, Any]) -> set[str]: + """建任务前要读的库位:任务输入与图中各节点静态参数里的 ``{"site_uuid"}``。""" + + return site_references([input_value, *((node.get("param") or {}) for node in graph.get("nodes") or [])]) + + +def read_site_facts(materials: Any, site_uuids: Iterable[str]) -> dict[str, dict[str, Any]]: + """向物料权威读一次库位事实;没有物料权威时报错(按库位绑定必须在准入时解析)。""" + + identities = sorted(set(site_uuids)) + if not identities: + return {} + reader = getattr(materials, "site_admission_facts", None) + if not callable(reader): + raise RuntimeError("物料权威尚未接入,不能按库位绑定物料") + facts = reader({"site_uuids": identities}) + return dict((facts or {}).get("sites") or {}) + + +def _template_symbols(schema: Any, parameter: str) -> list[str]: + contract = (schema or {}).get("x-unilabos-action-contract") if isinstance(schema, Mapping) else None + symbols = ((contract or {}).get("resource_template_symbols") or {}).get("goal") or {} + return list(symbols.get(parameter) or []) + + +def resolve_site_material( + facts: Mapping[str, Any], site_uuid: str, *, parameter: str, node_uuid: Optional[str] = None, + template_symbols: Iterable[str] = (), +) -> dict[str, str]: + """一个 ``{"site_uuid"}`` → 占用物料的 ``{"uuid"}``;库位不存在 / 为空 / 模板不符时抛 :class:`MaterialSiteError`。""" + + fact = facts.get(site_uuid) + where = f"参数 {parameter}" + (f"(节点 {node_uuid})" if node_uuid else "") + if fact is None: + # 建任务前读事实之后图又改了:读到的库位集合里没有它 + raise MaterialSiteError(SITE_NOT_FOUND, f"{where} 按库位 {site_uuid} 绑定物料:库位事实未读取,请重试", + parameter=parameter, site_uuid=site_uuid, node_uuid=node_uuid) + if not fact.get("exists"): + raise MaterialSiteError(SITE_NOT_FOUND, f"{where} 按库位 {site_uuid} 绑定物料:库位不存在", + parameter=parameter, site_uuid=site_uuid, node_uuid=node_uuid) + label = f"{fact.get('label') or site_uuid}({site_uuid})" + occupant = fact.get("occupant") + if not occupant: + raise MaterialSiteError(SITE_EMPTY, f"{where} 按库位 {label} 绑定物料:库位上没有物料", + parameter=parameter, site_uuid=site_uuid, node_uuid=node_uuid) + symbols = list(template_symbols) + if symbols and occupant.get("module_name") not in symbols: + raise MaterialSiteError( + TEMPLATE_MISMATCH, + f"{where} 按库位 {label} 绑定物料:库位上的物料 {occupant.get('material_uuid')}" + f"(模板 {occupant.get('template_name')})不是参数允许的资源模板({'、'.join(symbols)})", + 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]], +) -> None: + for name, value in list(param.items()): + symbols = _template_symbols(schema, name) + + 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) + record = {"parameter": name, "site_uuid": site, "material_uuid": material["uuid"]} + if node_uuid is not None: + record["node_uuid"] = node_uuid + bindings.append(record) + return material + + if isinstance(value, list): + param[name] = [bind(item) for item in value] + else: + param[name] = bind(value) + + +def bind_param_sites( + param: dict[str, Any], facts: Mapping[str, Any], *, schema: Any = None, node_uuid: Optional[str] = None, +) -> list[dict[str, Any]]: + """就地绑定一组动作参数(如单点设备动作的参数);``schema`` 是动作 schema,用于模板核对。""" + + bindings: list[dict[str, Any]] = [] + _bind_param(param, facts, node_uuid=node_uuid, schema=schema, bindings=bindings) + return bindings + + +def bind_material_sites( + plan: Optional[dict[str, Any]], input_value: Optional[dict[str, Any]], facts: Mapping[str, Any], +) -> list[dict[str, Any]]: + """就地把计划与任务输入里的 ``{"site_uuid"}`` 换成占用物料 ``{"uuid"}``,返回绑定记录。 + + 计划节点的 ``param`` 与 ``entry_param_template``(暂停改参时按它重新代入)一起换;任务输入里的同形值也换, + 改参后重新代入的仍是冻结的物料。绑定记录写进计划的 ``material_site_bindings``(追溯用)。 + """ + + bindings: list[dict[str, Any]] = [] + for node in (plan or {}).get("nodes") or []: + schema = node.get("param_schema") + _bind_param(node.setdefault("param", {}), facts, node_uuid=node["uuid"], schema=schema, bindings=bindings) + template = node.get("entry_param_template") + 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) + if plan is not None and bindings: + plan["material_site_bindings"] = bindings + return bindings + + +def bind_jobs(plan: Mapping[str, Any], jobs: Iterable[dict[str, Any]]) -> None: + """计划节点参数已经冻结:同步到各节点运行的首个 attempt。""" + + params = {node["uuid"]: node.get("param") for node in plan.get("nodes") or []} + for job in jobs: + if job.get("workflow_node_uuid") in params: + job["param"] = dict(params[job["workflow_node_uuid"]] or {}) + + +__all__ = [ + "MaterialSiteError", + "SITE_EMPTY", + "SITE_NOT_FOUND", + "TEMPLATE_MISMATCH", + "bind_jobs", + "bind_material_sites", + "bind_param_sites", + "graph_site_references", + "read_site_facts", + "resolve_site_material", + "site_references", +] diff --git a/unilabos/server/services/runtime/workflow/run_preflight.py b/unilabos/server/services/runtime/workflow/run_preflight.py index 5e5a71e53..a6e413744 100644 --- a/unilabos/server/services/runtime/workflow/run_preflight.py +++ b/unilabos/server/services/runtime/workflow/run_preflight.py @@ -104,6 +104,22 @@ def check(kind: str, status: str, code: str, message: str, *, node=None, details return finalize(report) check("inventory", "passed", "inventory_bindings_applied", "库存绑定已对应到计划中的库存需求", details={"bindings": bindings}) + # 按库位绑定的物料参数({"site_uuid"}):与建任务同一条解析路径,换成此刻占着库位的物料 + from .material_sites import MaterialSiteError, bind_material_sites, 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)) + 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) + return finalize(report) + except (RuntimeError, OSError) as error: + check("resources", "blocked", "material_site_unavailable", f"无法读取按库位绑定的库位:{error}") + return finalize(report) + check("resources", "passed", "material_sites_bound", "按库位绑定的物料参数已解析为库位上的物料", + details={"bindings": site_bindings}) endpoints = None if service._preflight_endpoints is not None: try: diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 0bab6525e..14c482592 100644 --- a/unilabos/server/services/runtime/workflow/service.py +++ b/unilabos/server/services/runtime/workflow/service.py @@ -155,6 +155,7 @@ "工作流模板的角色未能绑定到设备,请在 bindings 中指定", ), "site_binding_invalid": (422, "工作流 Site 绑定未完成"), + "material_site_invalid": (422, "物料参数按库位绑定失败"), "invalid_composite_child_type": (400, "只有实验操作可以作为子工作流被引用"), "invalid_composite_child_status": (409, "被引用的实验操作当前修订尚未发布"), "local_task_authority_forbidden": ( @@ -367,7 +368,7 @@ class WorkflowError(RuntimeError): ``detail`` 追加在稳定文案之后(如具体哪个模板角色没绑到设备),错误码不变。 """ - def __init__(self, code: str, *, detail: str = ""): + def __init__(self, code: str, *, detail: str = "", details: Optional[Dict[str, Any]] = None): status, message = _ERRORS[code] if detail: message = f"{message}:{detail}" @@ -375,6 +376,8 @@ def __init__(self, code: str, *, detail: str = ""): self.status = status self.code = code self.message = message + #: 结构化细节(失败信封的 ``error.details``),如按库位绑定失败的库位与参数 + self.details = details class WorkflowConflict(WorkflowError): @@ -1502,6 +1505,8 @@ def create_workflow_task( raise WorkflowConflict("conflict") return existing resolved: Dict[str, Dict[str, Any]] = {} + # 按库位绑定的物料参数({"site_uuid"})同样在事务外读库位事实,事务内换成占用物料并冻结 + site_facts = self._material_site_facts(self.get_graph(workflow_uuid), input_value) # 绑定指向的库存实例在建任务事务外读取(物料库是另一个权威,不在 runtime 写锁内访问); # 事务内按冻结计划把绑定落到对应需求,不匹配即拒绝建任务。 binding_sources: Optional[Dict[str, Dict[str, Any]]] = {} @@ -1521,6 +1526,8 @@ def build_plan(graph: Dict[str, Any]) -> Any: target_node_uuid=target_node_uuid, entry_input=resolved["input"], ) + # 按库位绑定的物料参数解析成占用物料,计划、attempt 参数与任务输入一起冻结 + self._bind_material_sites(plan, jobs, resolved["input"], site_facts) try: bind_plan_inventory(plan, bindings, binding_sources) except (ValueError, InventoryBindingUnavailable) as exc: @@ -1568,6 +1575,36 @@ def build_input(graph: Dict[str, Any]) -> Dict[str, Any]: self._task_submitter(task["uuid"]) return task + def _material_site_facts( + self, graph: Optional[Dict[str, Any]], *params: Dict[str, Any], + ) -> Dict[str, Dict[str, Any]]: + """按库位绑定要的库位事实(事务外读一次);没有 ``{"site_uuid"}`` 时不读。""" + + from .material_sites import graph_site_references, read_site_facts, site_references + + references = site_references(params) + if graph is not None: + references |= graph_site_references(graph, {}) + if not references: + return {} + try: + return read_site_facts(self._preflight_materials, references) + 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]], + ) -> None: + from .material_sites import MaterialSiteError, bind_jobs, bind_material_sites + + try: + if bind_material_sites(plan, input_value, facts): + bind_jobs(plan, jobs) + except MaterialSiteError as exc: + raise WorkflowError("material_site_invalid", detail=exc.message, details=exc.details) from None + def create_ad_hoc_device_action_task( self, *, @@ -1624,6 +1661,20 @@ def create_ad_hoc_device_action_task( if existing.get("request_fingerprint", "") not in {"", fingerprint}: raise WorkflowConflict("conflict") return existing + # 按库位绑定的物料参数:建任务时解析成占用物料并冻结(指纹按提交的原参数,重放仍命中同一任务) + site_facts = self._material_site_facts(None, param) + if site_facts: + from copy import deepcopy + + from .material_sites import MaterialSiteError, bind_param_sites + + schema = (self._action_schema_resolver(device_id, action_name) + if self._action_schema_resolver is not None else None) + param = deepcopy(param) + try: + bind_param_sites(param, site_facts, schema=schema) + except MaterialSiteError as exc: + raise WorkflowError("material_site_invalid", detail=exc.message, details=exc.details) from None try: task = self.create_ad_hoc_task_with_job( task_uuid=str(uuid4()), diff --git a/unilabos/server/services/runtime/workflow/value_schema.py b/unilabos/server/services/runtime/workflow/value_schema.py index 81bd4df68..db65ebda2 100644 --- a/unilabos/server/services/runtime/workflow/value_schema.py +++ b/unilabos/server/services/runtime/workflow/value_schema.py @@ -12,6 +12,7 @@ from typing import Any from unilabos.server.services.runtime.workflow.handle_projection import resource_slot_schema +from unilabos.protocol.runtime.site_references import SITE_UUID_KEY, site_reference from unilabos.protocol.runtime.workflow import validate_uuid @@ -141,6 +142,13 @@ def validate_value( ): raise WorkflowValueSchemaError("workflow_value_invalid", path) if normalized.get("$slot") == "ResourceSlot": + site = site_reference(value) + if site is not None: + # 按库位绑定(占着这个库位的物料):建任务 / 预检时解析成占用物料并冻结 + try: + return {SITE_UUID_KEY: validate_uuid(site)} + except (TypeError, ValueError): + raise WorkflowValueSchemaError("workflow_value_invalid", path) from None if not isinstance(value, Mapping) or not isinstance(value.get("uuid"), str): raise WorkflowValueSchemaError("workflow_value_invalid", path) try: From 08743f2aa9549099b18f7e53ab6036f8a2d1a85f Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:05:54 +0800 Subject: [PATCH 54/59] feat(scheduler): a SiteSlot can be chosen by its owner at task admission A SiteSlot parameter with a Material.site relation (and a SiteSlot workflow input) may be given as {"owner_uuid": ...}. At task admission the scheduler reserves, through the existing ingress reservation, the first free Site under that owner (by ordinal) whose acceptor (template whitelist and allowed categories) takes the occupant material, then freezes the Site uuid into the plan, the attempt params and the task input (site_selections). An input used by several nodes is selected once. No acceptable Site fails the task before start (plan_not_executable, reason no_acceptable_site); all acceptable Sites taken keeps it pending with wait_reason site_group_unavailable until one frees. Forms that can never work are rejected at task creation (site_selection_invalid). The run preflight reads the candidates without reserving. The reservation turns in_transit when the action using the Site is dispatched; an in_transit carrier placed straight into its reserved Site completes it, and the task end closes what is left (ingress-reservations/finish-task). Exact Site uuids are unchanged. --- docs/developer_guide/action_standard.md | 24 +- docs/developer_guide/api_v1_migration.md | 6 +- docs/developer_guide/api_v1_route_map.md | 9 +- docs/developer_guide/interfaces/materials.md | 3 +- .../scheduling_and_execution.md | 3 +- tests/server/test_site_selection_by_owner.py | 427 ++++++++++++++++++ unilabos/client/materials/core.py | 39 +- unilabos/client/runtime/workflow.py | 3 +- unilabos/protocol/runtime/site_references.py | 30 +- unilabos/server/api/envelope.py | 3 + unilabos/server/api/materials/inventory.py | 44 +- unilabos/server/api/runtime/workflow.py | 7 +- unilabos/server/scheduler/service.py | 161 ++++++- unilabos/server/services/materials/core.py | 30 +- unilabos/server/services/materials/ingress.py | 63 ++- .../services/materials/site_admission.py | 107 ++++- .../runtime/workflow/run_preflight.py | 29 +- .../services/runtime/workflow/service.py | 13 + .../runtime/workflow/site_selections.py | 275 +++++++++++ .../server/services/runtime/workflow/store.py | 38 ++ .../services/runtime/workflow/value_schema.py | 9 +- 21 files changed, 1283 insertions(+), 40 deletions(-) create mode 100644 tests/server/test_site_selection_by_owner.py create mode 100644 unilabos/server/services/runtime/workflow/site_selections.py diff --git a/docs/developer_guide/action_standard.md b/docs/developer_guide/action_standard.md index d4dd95e38..72b0193bc 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 字符串 | 严格 | -| `SiteSlot` 且写了 `material=Material.site("site", owner=...)` | 库位 UUID,带库位关系(`x-unilabos-site-selector`) | 严格;预检与派发前核对库位归属与占用 | +| `SiteSlot` 且写了 `material=Material.site("site", owner=...)` | 库位 UUID(或按所属物料选择的 `{"owner_uuid": ...}`,准入时选定),带库位关系(`x-unilabos-site-selector`) | 严格;预检与派发前核对库位归属与占用 | | `dict`、`Dict[str, Any]`、`Mapping` | 任意 JSON 对象 | 只校验是对象 | | 没写注解、`Any`、`object` | 任意 JSON 值(`{}`) | 不限值 | | 严格解析器不认识的注解(`Union[int, str]`、`List[Optional[float]]`、枚举、PLR / pydantic 类型……) | 退回注册表原来的签名类型推断 | 按推断结果;推断不出的部分接受任意值 | @@ -146,6 +146,28 @@ def place(self, carrier: ResourceSlot, sample: ResourceSlot, site: SiteSlot = No 运行预检与派发前核对所选库位属于 `owner`,且(不允许占用时)没有被 `occupant` 以外的物料占着。 - 只写 `SiteSlot`、不写 `Material.site` 的参数照旧是库位选择器,只是没有这层关系的核对。 +#### 按所属物料选库位:`{"owner_uuid": ...}` + +带 `Material.site` 关系的库位参数(以及工作流入口参数里的 `SiteSlot`)可以不给库位 uuid,而给 +`{"owner_uuid": "<所属物料 uuid>"}`,由调度器在**任务准入**时挑一个库位: + +- 候选是所属物料下(可见的)库位里,接收规则接受放入物料(`Material.site` 的 `occupant` 参数;它按库位绑定时先解析)的: + 库位模板白名单(`extra.allowed_resource_template_uuids`,6008 那一条)与 `allowed_resource_categories`(放入物料模板的 + `category` 要与它相交)都满足,空列表表示不限。按库位序号选第一个空着、没有活动入口预留、没有未结算物理动作占着的。 +- 选中后用物料权威的入口预留占住(`POST /api/v1/inventory/ingress-reservations` 的 `owner_material_uuid` 写法, + `backend_task_uuid` 为任务 uuid),再把库位 uuid 冻结进计划节点参数、attempt 参数与任务输入;计划的 `site_selections` + 记录所属物料、放入物料、选中的库位与预留。同一个工作流入口参数用在多个节点里只选一次。 +- 用到这个库位的动作派发时预留转 `in_transit`:放入物料被直接放进这个库位等同接收(预留置为 `received`),其他物料仍被挡; + 任务结束时收尾(`POST /api/v1/inventory/ingress-reservations/finish-task`:物料已在库位上记 `received`,否则取消)。 +- 所属物料下没有接受放入物料的库位是预检错误:任务在准入时失败,`error_info[0]` 为 `plan_not_executable` + (`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`)。 +- 给精确的库位 uuid 照旧,不经过选择与预留。 + ## 前端选择器:`placeholder_keys` `placeholder_keys` 只决定前端用哪种选择器填写一个参数(`unilabos.registry.placeholder_type` 的 `PLACEHOLDER_*`)。 diff --git a/docs/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index b6a03c433..727533a60 100644 --- a/docs/developer_guide/api_v1_migration.md +++ b/docs/developer_guide/api_v1_migration.md @@ -174,7 +174,11 @@ dev 内部异常到业务码的映射集中在 `envelope.py`,不在各路由 - 工站入站预留(`/inventory/ingress-reservations`)保护它的库位:`reserved`(未过期)或 `in_transit` 期间, 人工移动(`move_material` 命令、V1 `site_placement`)、transfer 和工作流搬运派发前的预检都以 `MaterialConflictError(conflict="site_ingress_reserved")` 拒绝(HTTP 6011,库存命令 `error_code` - `conflict:site_ingress_reserved`),载体本身也只能经 `receive` 落位;同一载体同时至多一个活动预留(再预留 3003)。 + `conflict:site_ingress_reserved`),载体本身也只能经 `receive` 落位——例外是 `in_transit` 的载体被直接放进自己预留的库位, + 等同接收(同一事务里预留置为 `received`);同一载体同时至多一个活动预留(再预留 3003)。预留可以给 + `owner_material_uuid` 代替 `candidate_site_uuids`:候选是该物料下接受载体的库位(模板白名单与允许的资源类别,按库位序号), + 一个都不接受 6008,都被占着 6007;工作流按所属物料选库位用这种写法,任务结束经 `POST .../ingress-reservations/finish-task` + 收尾(dev 扩展)。 `site_ingress_reserved` 是临时资源条件:预留接收、取消或过期后自然解除,调度侧应等待而不是判任务失败 (常量 `services.materials.SITE_INGRESS_RESERVED`)。与 V1 的差别:只锁库位,不锁库位所属设备与载体设备上的 普通作业;设备快照(`apply_snapshot`)是现场事实,不受预留拦截。 diff --git a/docs/developer_guide/api_v1_route_map.md b/docs/developer_guide/api_v1_route_map.md index d6049341c..a9c75a58a 100644 --- a/docs/developer_guide/api_v1_route_map.md +++ b/docs/developer_guide/api_v1_route_map.md @@ -310,7 +310,14 @@ Adopting V1's contract on any of these breaks something DEV already relies on. > Dev-only (2026-11-25): `POST /api/v1/inventory/site-admission` (`{"site_uuids": [...]}`) is the one read the workflow > service makes at task creation / run preflight to bind material parameters given as `{"site_uuid": ...}`: per Site > whether it exists, its label and owner, and the occupying material with its template (`module_name`, category). -> Read-only, no verdict (see `action_standard.md`). +> Read-only, no verdict (see `action_standard.md`). With `owners` (`[{"owner_material_uuid", "occupant_material_uuid"}]`) +> it also lists, per owner, the Sites whose acceptor (template whitelist, allowed categories) takes the occupant, by +> ordinal, and which of them are free now; the run preflight uses it for SiteSlot parameters given as `{"owner_uuid": ...}`. +> Dev extension (2026-11-25): `POST /api/v1/inventory/ingress-reservations` takes `owner_material_uuid` instead of +> `candidate_site_uuids` (candidates = the owner's Sites that accept the carrier; none: 6008, all taken: 6007), an +> `in_transit` carrier placed straight into its reserved Site completes the reservation (`received`), and +> `POST /api/v1/inventory/ingress-reservations/finish-task` (`{"backend_task_uuid", "reason"}`) closes a workflow task's +> active reservations (received when the carrier sits in the Site, canceled otherwise). | class | V1 route | V1 handler | DEV counterpart | note | status (p7-c) | |---|---|---|---|---|---| diff --git a/docs/developer_guide/interfaces/materials.md b/docs/developer_guide/interfaces/materials.md index d035d3a97..31eed2be7 100644 --- a/docs/developer_guide/interfaces/materials.md +++ b/docs/developer_guide/interfaces/materials.md @@ -204,7 +204,8 @@ transfer payload:source_device_id、target_device_id、items。 move、transfer 与工作流搬运派发前的预检共用同一组放入检查:目标 Site 有活动的工站入站预留 (`/api/v1/inventory/ingress-reservations`,`reserved` 未过期或 `in_transit`)时拒绝,冲突类别 -`site_ingress_reserved`(6011),连预留的载体本身也只能经该预留的 receive 落位。这是临时条件, +`site_ingress_reserved`(6011),连预留的载体本身也只能经该预留的 receive 落位;唯一例外是 `in_transit` 的载体 +被直接放进自己预留的库位,等同接收(预留在同一事务里置为 `received`,工作流按所属物料选库位时用到)。这是临时条件, 预留接收、取消或过期后同一请求可以重试。 执行顺序: diff --git a/docs/developer_guide/scheduling_and_execution.md b/docs/developer_guide/scheduling_and_execution.md index b3222a2d5..d1fa7c357 100644 --- a/docs/developer_guide/scheduling_and_execution.md +++ b/docs/developer_guide/scheduling_and_execution.md @@ -63,7 +63,8 @@ Authority,再创建执行层,因此不存在执行器先于库存权威工 1. `PUT /api/v1/workflows/{uuid}/graph` 保存节点和边。 2. `POST /api/v1/workflow-tasks` 固化 `workflow_snapshot` 和 `execution_plan`。按库位绑定的物料参数 (`{"site_uuid": ...}`,见 [动作标准](action_standard.md))在这里换成此刻占着该库位的物料并一起冻结;运行预检 - (`/run-preflight`)走同一条解析路径。 + (`/run-preflight`)走同一条解析路径。按所属物料选择的库位参数(`{"owner_uuid": ...}`)在调度器准入任务时 + (`_admit_fresh_task`,先于整任务库存预留)选定、经入口预留占住并冻结;接受的库位都被占着时任务保持 `pending` 排队。 3. `WorkflowService` 调用已绑定的 `BackendScheduler.submit(task_uuid)`。 4. Scheduler 从持久化 Task/节点运行构建 `TaskDag`,恢复已完成节点后开始走图。 diff --git a/tests/server/test_site_selection_by_owner.py b/tests/server/test_site_selection_by_owner.py new file mode 100644 index 000000000..9eeb7a168 --- /dev/null +++ b/tests/server/test_site_selection_by_owner.py @@ -0,0 +1,427 @@ +"""库位参数按所属物料选择:``{"owner_uuid": ...}`` 在任务准入时选定、经入口预留占住并冻结进任务。 + +候选是所属物料下接受放入物料(``Material.site`` 的 occupant)的库位(模板白名单 / 允许的资源类别),按库位序号选第一个 +空着且没被预留的;没有接受的库位是预检错误(``reason=no_acceptable_site``),接受的都被占着时任务排队 +(``wait_reason.code=site_group_unavailable``)。精确库位 uuid 照旧。 +""" + +from __future__ import annotations + +from uuid import uuid4 + +import pytest +from fastapi.testclient import TestClient + +from tests.server.test_scheduler_inventory_authority import _mutation +from tests.server.test_workflow_inventory_recovery import Stack +from tests.server.test_workflow_parallel_execution import Executor, wait_for +from unilabos.protocol.materials import ( + MaterialIdentityWrite, + MaterialMove, + MaterialNodeCreate, + MaterialTreeCreate, + ResourceTemplateWrite, + SiteCreate, +) +from unilabos.protocol.runtime.site_references import site_under_owner +from unilabos.registry.workflows import upsert_workflow +from unilabos.server.api.runtime.workflow import create_workflow_app +from unilabos.server.scheduler.service import BackendScheduler +from unilabos.server.services.runtime.workflow.service import WorkflowError + +_LOCK = {"type": "object", "properties": {"uuid": {"type": "string", "format": "uuid"}}, "required": ["uuid"], + "x-unilabos-material-lock": True} +_SELECTOR = {"version": 1, "owner": "heater", "occupant": "sample", "show_occupied": True, "allow_occupied": False} + + +def _schema(selector: dict | None = _SELECTOR) -> dict: + site = {"type": "string", "format": "uuid"} + if selector is not None: + site["x-unilabos-site-selector"] = dict(selector) + return { + "x-unilabos-action-contract": {"version": 2}, + "properties": { + "goal": {"type": "object", "properties": {"heater": _LOCK, "sample": _LOCK, "site": site}, + "required": ["heater", "sample", "site"]}, + "result": {}, + }, + } + + +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") + + +def _seed(stack: Stack, *, categories: tuple[str, ...] = ("other", "heating", "heating", "heating"), + occupied: tuple[int, ...] = (1,), samples: int = 2) -> dict: + """一个加热台:按序号排的工位(每个工位只接受一种类别),``occupied`` 序号的工位上已有一个样品;外加几个待放的样品。""" + + from unilabos.server.services.materials.core import MaterialNoChangeError + + for name, category in (("heater", []), ("sample", ["heating"])): + try: + stack.materials.put_template(_mutation("put_template"), ResourceTemplateWrite( + template_uuid=f"{name}-template", name=name, display_name=name, resource_type="container", + class_name="Container", category=category)) + except MaterialNoChangeError: + pass + nodes = [MaterialNodeCreate(client_ref="heater", identity=_identity("heater", "heater"), sites=[ + SiteCreate(template_name="slot", site_index=index, label=f"S{index}", allowed_resource_categories=[category], + occupied_client_ref=f"blocker-{index}" if index in occupied else None) + for index, category in enumerate(categories)])] + nodes += [MaterialNodeCreate(client_ref=f"blocker-{index}", parent_client_ref="heater", + identity=_identity("blocker", "sample")) for index in occupied] + tree = stack.materials.create_tree(_mutation("create_material_tree"), MaterialTreeCreate(nodes=nodes)).data + heater = tree.client_ref_map["heater"] + sites = {site.label: site.site_uuid for site in stack.materials.get_material(heater).sites} + return {"heater": heater, "sites": sites, "samples": [_sample(stack) for _ in range(samples)]} + + +def _sample(stack: Stack) -> str: + tree = stack.materials.create_tree(_mutation("create_material_tree"), MaterialTreeCreate(nodes=[ + MaterialNodeCreate(client_ref="sample", identity=_identity("sample", "sample"))])).data + return tree.client_ref_map["sample"] + + +def _node(param: dict, **extra) -> dict: + return {"uuid": str(uuid4()), "name": "放到加热台", "type": "device_action", "material_uuid": str(uuid4()), + "action_name": "place", "meta_data": {"target_device_id": "robot"}, "param": param, **extra} + + +def _workflow(stack: Stack, nodes: list[dict], *, schema: dict | None = None, io: dict | None = None) -> dict: + stack.workflow.configure_preflight(materials=stack.client, endpoints=lambda: [], + action_schema_resolver=lambda *_: schema or _schema()) + payload = {"workflow_uuid": str(uuid4()), "name": "按所属物料选库位", "description": "", "tags": [], "edges": [], + "nodes": nodes} + if io is not None: + payload["io"] = io + return upsert_workflow(stack.workflow, payload) + + +def _create(stack: Stack, record: dict, input_value: dict | None = None) -> dict: + return stack.workflow.create_workflow_task(workflow_uuid=record["uuid"], run_mode="normal", target_node_uuid=None, + input_value=input_value or {}, description=None, meta_data={}) + + +def _scheduler(stack: Stack, executor: Executor) -> BackendScheduler: + scheduler = BackendScheduler(stack.workflow, executor, materials_gateway=stack.client) + stack.workflow.set_task_submitter(scheduler.submit) + return scheduler + + +def _reservations(stack: Stack, task_uuid: str) -> list[dict]: + from unilabos.server.services.materials.ingress import IngressReservations + + return [item for item in IngressReservations(stack.materials).list() if item["backend_task_uuid"] == task_uuid] + + +def _status(stack: Stack, task_uuid: str) -> str: + return stack.workflow.get_workflow_task(task_uuid)["status"] + + +def test_admission_picks_the_first_acceptable_free_site_reserves_and_freezes_it(tmp_path) -> None: + stack, executor = Stack(tmp_path), Executor() + scheduler = _scheduler(stack, executor) + try: + seed = _seed(stack) + sample = seed["samples"][0] + record = _workflow(stack, [_node({"heater": {"uuid": seed["heater"]}, "sample": {"uuid": sample}, + "site": site_under_owner(seed["heater"])})]) + task = _create(stack, record) + assert task["execution_plan"]["nodes"][0]["param"]["site"] == {"owner_uuid": seed["heater"]} + wait_for(lambda: len(executor.dispatched) == 1) + # S0 只接受别的类别、S1 已被占:按库位序号选 S2 + chosen = seed["sites"]["S2"] + assert executor.dispatched[0]["action_args"]["site"] == chosen + frozen = stack.workflow.get_workflow_task(task["uuid"]) + [selection] = frozen["execution_plan"]["site_selections"] + assert selection["site_uuid"] == chosen and selection["owner_uuid"] == seed["heater"] + assert selection["occupant_uuid"] == sample + assert frozen["execution_plan"]["nodes"][0]["param"]["site"] == chosen + [run] = stack.workflow.list_workflow_node_runs(task["uuid"]) + assert run["param"]["site"] == chosen + [reservation] = _reservations(stack, task["uuid"]) + assert reservation["site_uuid"] == chosen and reservation["carrier_material_uuid"] == sample + # 派发用到它的动作时转 in_transit:放入物料直接放进预留的库位等同接收,别的物料照旧被挡 + assert reservation["state"] == "in_transit" + stack.materials.move_material(_mutation("move_material"), + MaterialMove(material_uuid=sample, destination_site_uuid=chosen)) + assert _reservations(stack, task["uuid"])[0]["state"] == "received" + executor.finish(0, {}) + wait_for(lambda: _status(stack, task["uuid"]) == "succeeded") + finally: + scheduler.stop() + stack.close() + + +def test_two_tasks_get_different_sites_under_the_same_owner(tmp_path) -> None: + stack, executor = Stack(tmp_path), Executor() + scheduler = _scheduler(stack, executor) + try: + seed = _seed(stack, occupied=()) + record = _workflow(stack, [_node({"heater": {"uuid": seed["heater"]}, "sample": {"kind": "workflow_input", + "parameter": "sample"}, + "site": site_under_owner(seed["heater"])})], + io={"input_contract": {"version": 1, "parameters": [ + {"name": "sample", "schema": {"$slot": "ResourceSlot"}, "required": True}]}, + "output_contract": {"version": 1, "outputs": [ + {"name": "sample", "schema": {"$slot": "ResourceSlot"}, "implicit": True}]}, + "output_bindings": {"sample": {"kind": "workflow_input", "parameter": "sample"}}}) + tasks = [_create(stack, record, {"sample": {"uuid": sample}}) for sample in seed["samples"]] + wait_for(lambda: all(stack.workflow.get_workflow_task(task["uuid"])["execution_plan"].get("site_selections") + for task in tasks)) + chosen = [stack.workflow.get_workflow_task(task["uuid"])["execution_plan"]["site_selections"][0]["site_uuid"] + for task in tasks] + # 同一所属物料下各自预留:不会选到同一个库位,按准入先后取序号靠前的 + assert sorted(chosen) == sorted([seed["sites"]["S1"], seed["sites"]["S2"]]) + assert {item["site_uuid"] for task in tasks for item in _reservations(stack, task["uuid"])} == set(chosen) + # 同一台设备的动作锁让两个任务先后派发,各用各的库位 + wait_for(lambda: len(executor.dispatched) == 1) + executor.finish(0, {}) + wait_for(lambda: len(executor.dispatched) == 2) + assert {payload["action_args"]["site"] for payload in executor.dispatched} == set(chosen) + finally: + scheduler.stop() + stack.close() + + +def test_all_acceptable_sites_taken_waits_until_one_frees(tmp_path) -> None: + stack, executor = Stack(tmp_path), Executor() + scheduler = _scheduler(stack, executor) + try: + # 只有 S1 接受样品 + seed = _seed(stack, categories=("other", "heating"), occupied=()) + first, second = seed["samples"] + record_for = {sample: _workflow(stack, [_node({"heater": {"uuid": seed["heater"]}, "sample": {"uuid": sample}, + "site": site_under_owner(seed["heater"])})]) + for sample in (first, second)} + task_a = _create(stack, record_for[first]) + wait_for(lambda: len(executor.dispatched) == 1) + task_b = _create(stack, record_for[second]) + [job_b] = stack.workflow.list_workflow_node_jobs(task_b["uuid"]) + wait_for(lambda: (stack.workflow.get_workflow_node_job(job_b["uuid"])["control_data"].get("wait_reason") or {}) + .get("code") == "site_group_unavailable") + assert _status(stack, task_b["uuid"]) == "pending" + assert _reservations(stack, task_b["uuid"]) == [] + assert len(executor.dispatched) == 1 + # 任务 A 结束:它的预留收尾(样品没放进去 → 取消),B 按排队先后重试并取得 S1 + executor.finish(0, {}) + wait_for(lambda: _status(stack, task_a["uuid"]) == "succeeded") + assert _reservations(stack, task_a["uuid"])[0]["state"] == "canceled" + wait_for(lambda: len(executor.dispatched) == 2) + assert executor.dispatched[1]["action_args"]["site"] == seed["sites"]["S1"] + assert "wait_reason" not in stack.workflow.get_workflow_node_job(job_b["uuid"])["control_data"] + executor.finish(1, {}) + wait_for(lambda: _status(stack, task_b["uuid"]) == "succeeded") + finally: + scheduler.stop() + stack.close() + + +def test_no_acceptable_site_under_the_owner_is_a_preflight_error(tmp_path) -> None: + stack, executor = Stack(tmp_path), Executor() + scheduler = _scheduler(stack, executor) + try: + seed = _seed(stack, categories=("other", "other"), occupied=()) + record = _workflow(stack, [_node({"heater": {"uuid": seed["heater"]}, "sample": {"uuid": seed["samples"][0]}, + "site": site_under_owner(seed["heater"])})]) + report = TestClient(create_workflow_app(stack.workflow)).post( + f"/api/v1/workflows/{record['uuid']}/run-preflight", json={}).json()["data"] + assert report["status"] == "invalid" + [blocked] = [item for item in report["checks"] if item["blocking"]] + assert blocked["code"] == "invalid_site_selection" and blocked["details"]["reason"] == "no_acceptable_site" + + task = _create(stack, record) + wait_for(lambda: _status(stack, task["uuid"]) == "failed") + [error] = stack.workflow.get_workflow_task(task["uuid"])["error_info"] + assert error["code"] == "plan_not_executable" and error["stage"] == "preflight" + assert error["reason"] == "no_acceptable_site" and error["details"]["parameter"] == "site" + assert executor.dispatched == [] and _reservations(stack, task["uuid"]) == [] + finally: + scheduler.stop() + stack.close() + + +def test_preflight_reports_free_and_taken_candidates_without_reserving(tmp_path) -> None: + stack = Stack(tmp_path) + try: + seed = _seed(stack, categories=("heating", "heating"), occupied=(0,)) + record = _workflow(stack, [_node({"heater": {"uuid": seed["heater"]}, "sample": {"uuid": seed["samples"][0]}, + "site": site_under_owner(seed["heater"])})]) + report = stack.workflow.preflight_workflow(workflow_uuid=record["uuid"], run_mode="normal", + target_node_uuid=None, input_value={}) + [ready] = [item for item in report["checks"] if item["code"] == "site_selection_ready"] + assert ready["details"]["available"] == [seed["sites"]["S1"]] + assert not any(item["code"] == "invalid_action_parameters" for item in report["checks"]) + stack.materials.move_material(_mutation("move_material"), MaterialMove( + material_uuid=seed["samples"][1], destination_site_uuid=seed["sites"]["S1"])) + report = stack.workflow.preflight_workflow(workflow_uuid=record["uuid"], run_mode="normal", + target_node_uuid=None, input_value={}) + assert report["status"] == "temporarily_unavailable" + # 设备在线快照这里是空的(device_action_unavailable):只看库位这一项 + assert "site_selection_unavailable" in [item["code"] for item in report["checks"] if item["blocking"]] + from unilabos.server.services.materials.ingress import IngressReservations + + assert IngressReservations(stack.materials).list() == [] + finally: + stack.close() + + +def test_exact_site_uuid_still_works_without_a_reservation(tmp_path) -> None: + stack, executor = Stack(tmp_path), Executor() + scheduler = _scheduler(stack, executor) + try: + seed = _seed(stack) + record = _workflow(stack, [_node({"heater": {"uuid": seed["heater"]}, "sample": {"uuid": seed["samples"][0]}, + "site": seed["sites"]["S3"]})]) + task = _create(stack, record) + wait_for(lambda: len(executor.dispatched) == 1) + assert executor.dispatched[0]["action_args"]["site"] == seed["sites"]["S3"] + assert "site_selections" not in stack.workflow.get_workflow_task(task["uuid"])["execution_plan"] + assert _reservations(stack, task["uuid"]) == [] + executor.finish(0, {}) + wait_for(lambda: _status(stack, task["uuid"]) == "succeeded") + finally: + scheduler.stop() + stack.close() + + +def test_site_slot_workflow_input_by_owner_is_selected_once_and_frozen(tmp_path) -> None: + stack, executor = Stack(tmp_path), Executor() + scheduler = _scheduler(stack, executor) + try: + seed = _seed(stack) + sample = seed["samples"][0] + site_ref = {"kind": "workflow_input", "parameter": "site"} + place = _node({"heater": {"uuid": seed["heater"]}, "sample": {"uuid": sample}, "site": site_ref}) + heat = _node({"heater": {"uuid": seed["heater"]}, "sample": {"uuid": sample}, "site": site_ref}, + execution_policy={"depends_on": [place["uuid"]]}) + io = {"input_contract": {"version": 1, "parameters": [ + {"name": "site", "schema": {"$slot": "SiteSlot"}, "required": True}]}, + "output_contract": {"version": 1, "outputs": []}, "output_bindings": {}} + record = _workflow(stack, [place, heat], io=io) + task = _create(stack, record, {"site": {"owner_uuid": seed["heater"].upper()}}) + assert task["input"] == {"site": {"owner_uuid": seed["heater"]}} + wait_for(lambda: len(executor.dispatched) == 1) + frozen = stack.workflow.get_workflow_task(task["uuid"]) + chosen = seed["sites"]["S2"] + assert frozen["input"] == {"site": chosen} + [selection] = frozen["execution_plan"]["site_selections"] + assert selection["input"] == "site" and len(selection["targets"]) == 2 + assert {node["param"]["site"] for node in frozen["execution_plan"]["nodes"]} == {chosen} + assert len(_reservations(stack, task["uuid"])) == 1 + executor.finish(0, {}) + wait_for(lambda: len(executor.dispatched) == 2) + assert executor.dispatched[1]["action_args"]["site"] == chosen + executor.finish(1, {}) + wait_for(lambda: _status(stack, task["uuid"]) == "succeeded") + finally: + scheduler.stop() + stack.close() + + +def test_occupant_bound_by_site_feeds_the_owner_selection(tmp_path) -> None: + """物料参数按库位绑定(B)先解析,按所属物料选库位(C)用解析出的放入物料核对接收规则。""" + + stack, executor = Stack(tmp_path), Executor() + scheduler = _scheduler(stack, executor) + try: + seed = _seed(stack, categories=("heating", "heating", "heating"), occupied=(0,)) + source_site = seed["sites"]["S0"] + blocker = stack.materials.get_site(source_site).occupied_material_uuid + record = _workflow(stack, [_node({"heater": {"uuid": seed["heater"]}, "sample": {"site_uuid": source_site}, + "site": site_under_owner(seed["heater"])})]) + task = _create(stack, record) + wait_for(lambda: len(executor.dispatched) == 1) + assert executor.dispatched[0]["action_args"]["sample"] == {"uuid": blocker} + assert executor.dispatched[0]["action_args"]["site"] == seed["sites"]["S1"] + assert _reservations(stack, task["uuid"])[0]["carrier_material_uuid"] == blocker + finally: + scheduler.stop() + stack.close() + + +@pytest.mark.parametrize("case", ["no_site_relation", "occupant_undeclared", "owner_mismatch"]) +def test_selection_that_can_never_work_is_rejected_when_the_task_is_created(tmp_path, case: str) -> None: + stack = Stack(tmp_path) + try: + seed = _seed(stack) + selector = None if case == "no_site_relation" else { + **_SELECTOR, **({"occupant": None} if case == "occupant_undeclared" else {})} + heater = {"uuid": seed["samples"][1]} if case == "owner_mismatch" else {"uuid": seed["heater"]} + record = _workflow(stack, [_node({"heater": heater, "sample": {"uuid": seed["samples"][0]}, + "site": site_under_owner(seed["heater"])})], schema=_schema(selector)) + with pytest.raises(WorkflowError) as caught: + _create(stack, record) + assert caught.value.code == "site_selection_invalid" and caught.value.details["reason"] == case + assert caught.value.details["parameter"] == "site" + finally: + stack.close() + + +def test_ingress_reservation_by_owner_through_the_materials_api(tmp_path, monkeypatch) -> None: + """物料权威:按所属物料预留(6008 没有接受的库位 / 6007 都被占),in_transit 的载体放进来等同接收,任务结束收尾。""" + + from fastapi import FastAPI + + from tests.server.test_v1_inventory_api import _TestClientOpener + from unilabos.client.materials import HTTPMaterialsClient + from unilabos.client.materials.core import MaterialsHTTPError + from unilabos.server.api.materials import install_materials_api + + stack = Stack(tmp_path) + try: + seed = _seed(stack, categories=("other", "heating"), occupied=(), samples=3) + app = FastAPI() + install_materials_api(app, stack.materials) + with TestClient(app) as client: + monkeypatch.setattr("unilabos.client.materials.core.urlopen", _TestClientOpener(client)) + gateway = HTTPMaterialsClient("http://testserver") + first, second, third = seed["samples"] + body = {"carrier_material_uuid": first, "owner_material_uuid": seed["heater"], "ttl_seconds": 600, + "backend_task_uuid": "task-a", "idempotency_key": "k-1"} + reservation = gateway.reserve_ingress(body) + assert reservation["site_uuid"] == seed["sites"]["S1"] and reservation["state"] == "reserved" + assert gateway.reserve_ingress(body)["uuid"] == reservation["uuid"] + with pytest.raises(MaterialsHTTPError) as taken: + gateway.reserve_ingress({**body, "carrier_material_uuid": second, "idempotency_key": "k-2"}) + assert taken.value.business_code == 6007 + with pytest.raises(MaterialsHTTPError) as none: + gateway.reserve_ingress({**body, "carrier_material_uuid": third, "idempotency_key": "k-3", + "owner_material_uuid": first}) + assert none.value.business_code in {4001, 6000, 6008} + facts = gateway.site_admission_facts({"owners": [ + {"owner_material_uuid": seed["heater"], "occupant_material_uuid": second}]}) + assert [item["site_uuid"] for item in facts["owners"][0]["acceptable"]] == [seed["sites"]["S1"]] + assert facts["owners"][0]["available"] == [] + + # reserved 期间载体自己也放不进来(入口预留的原有语义);转 in_transit 后放进来等同接收 + with pytest.raises(Exception): + stack.client.move_material(_mutation("move_material"), MaterialMove( + material_uuid=first, destination_site_uuid=seed["sites"]["S1"])) + assert gateway.mark_ingress_in_transit(reservation["uuid"])["state"] == "in_transit" + with pytest.raises(Exception): + stack.client.move_material(_mutation("move_material"), MaterialMove( + material_uuid=second, destination_site_uuid=seed["sites"]["S1"])) + stack.client.move_material(_mutation("move_material"), MaterialMove( + material_uuid=first, destination_site_uuid=seed["sites"]["S1"])) + assert gateway.finish_task_ingress("task-a", reason="任务结束") == [] + from unilabos.server.services.materials.ingress import IngressReservations + + assert IngressReservations(stack.materials).get(reservation["uuid"])["state"] == "received" + + # 没有接受的库位:6008(合同错误) + other = _seed(stack, categories=("other",), occupied=(), samples=1) + with pytest.raises(MaterialsHTTPError) as rejected: + gateway.reserve_ingress({**body, "carrier_material_uuid": other["samples"][0], + "owner_material_uuid": other["heater"], "idempotency_key": "k-4"}) + assert rejected.value.business_code == 6008 + # 收尾:没放进来的预留取消 + fresh = _seed(stack, categories=("heating",), occupied=(), samples=1) + later = gateway.reserve_ingress({**body, "carrier_material_uuid": fresh["samples"][0], "idempotency_key": "k-5", + "owner_material_uuid": fresh["heater"], "backend_task_uuid": "task-b"}) + [finished] = gateway.finish_task_ingress("task-b", reason="任务结束") + assert finished["uuid"] == later["uuid"] and finished["state"] == "canceled" + finally: + stack.close() diff --git a/unilabos/client/materials/core.py b/unilabos/client/materials/core.py index 2a3bc4785..1651b2c2f 100644 --- a/unilabos/client/materials/core.py +++ b/unilabos/client/materials/core.py @@ -135,9 +135,30 @@ def material_sanity_facts(self, payload: dict[str, Any]) -> dict[str, Any]: list(payload.get("material_uuids") or []), reservation_uuid=payload.get("reservation_uuid")) def site_admission_facts(self, payload: dict[str, Any]) -> dict[str, Any]: - """任务准入时的只读库位事实:``{"site_uuids": [...]}``(物料参数按库位绑定引用的库位)。""" + """任务准入时的只读库位事实:``{"site_uuids": [...], "owners": [{"owner_material_uuid", + "occupant_material_uuid"}]}``(物料参数按库位绑定、库位参数按所属物料选择)。""" - return self.service.site_admission_facts(site_uuids=list(payload.get("site_uuids") or [])) + return self.service.site_admission_facts( + site_uuids=list(payload.get("site_uuids") or []), owners=list(payload.get("owners") or [])) + + def reserve_ingress(self, payload: dict[str, Any]) -> dict[str, Any]: + """入口预留(``candidate_site_uuids`` 或 ``owner_material_uuid``),返回预留投影;同一幂等键重放返回原预留。""" + + from unilabos.server.services.materials.ingress import IngressReservations + + return IngressReservations(self.service).reserve(payload)[0] + + def mark_ingress_in_transit(self, reservation_uuid: str) -> dict[str, Any]: + from unilabos.server.services.materials.ingress import IngressReservations + + return IngressReservations(self.service).mark_in_transit(reservation_uuid) + + def finish_task_ingress(self, backend_task_uuid: str, *, reason: str) -> list[dict[str, Any]]: + """任务结束:收掉它的活动入口预留(载体已在库位上记 received,否则取消)。""" + + from unilabos.server.services.materials.ingress import IngressReservations + + return IngressReservations(self.service).finish_task(backend_task_uuid, reason=reason) def validate_material_execution(self, value): return self.service.executions.validate(value) @@ -554,8 +575,22 @@ def site_admission_facts(self, payload: dict[str, Any]) -> dict[str, Any]: return self._request("POST", "/inventory/site-admission", { "site_uuids": list(payload.get("site_uuids") or []), + "owners": list(payload.get("owners") or []), }, root=True) + def reserve_ingress(self, payload: dict[str, Any]) -> dict[str, Any]: + """入口预留(``POST /inventory/ingress-reservations``);库位都被占 6007、没有接受的库位 6008 按业务码抛错。""" + + return self._request("POST", "/inventory/ingress-reservations", dict(payload), root=True) + + def mark_ingress_in_transit(self, reservation_uuid: str) -> dict[str, Any]: + return self._request("POST", f"/inventory/ingress-reservations/{reservation_uuid}/in-transit", root=True) + + def finish_task_ingress(self, backend_task_uuid: str, *, reason: str) -> list[dict[str, Any]]: + response = self._request("POST", "/inventory/ingress-reservations/finish-task", + {"backend_task_uuid": backend_task_uuid, "reason": reason}, root=True) + return list((response or {}).get("reservations") or []) + def _command(self, mutation: InventoryMutation, value: Any, *, target_uuid: Optional[str] = None) -> Any: """``materials.v1`` 变更经统一命令入口;拒绝结果按业务码还原成 HTTP 语义的异常。""" diff --git a/unilabos/client/runtime/workflow.py b/unilabos/client/runtime/workflow.py index 7dea6feb2..af3a7dab9 100644 --- a/unilabos/client/runtime/workflow.py +++ b/unilabos/client/runtime/workflow.py @@ -376,7 +376,8 @@ def create_task( 物料参数(``ResourceSlot``)可以按库位绑定:给 ``{"site_uuid": 库位 uuid}`` (``unilabos.protocol.runtime.site_references.material_at_site``),表示此刻占着该库位的物料, - 服务端建任务时解析并冻结。 + 服务端建任务时解析并冻结。库位参数(``SiteSlot``)可以按所属物料选择:给 ``{"owner_uuid": 所属物料 uuid}`` + (``site_under_owner``),调度器在任务准入时选定库位并冻结。 """ operation_id = operation_id or str(uuid4()) diff --git a/unilabos/protocol/runtime/site_references.py b/unilabos/protocol/runtime/site_references.py index ded0cc1f4..6d776d664 100644 --- a/unilabos/protocol/runtime/site_references.py +++ b/unilabos/protocol/runtime/site_references.py @@ -3,8 +3,11 @@ - 物料参数(``ResourceSlot`` / ``list[ResourceSlot]``)按库位绑定:``{"site_uuid": "<库位 uuid>"}``, 表示「此刻占着这个库位的物料」。建任务 / 运行预检时解析成占用物料的 ``{"uuid": ...}`` 并冻结进任务, 之后物料被挪走也不改变任务用的是哪件物料。 +- 库位参数(``SiteSlot``,带 ``Material.site`` 关系)按所属物料选择:``{"owner_uuid": "<所属物料 uuid>"}``, + 表示「这个物料下一个接受放入物料的空库位」。任务准入时调度器按库位序号选一个、经入口预留占住, + 并把选中的库位 uuid 冻结进任务。 -只认恰好一个键的对象:带 ``uuid`` 的照旧是普通物料引用。 +只认恰好一个键的对象:带 ``uuid`` 的照旧是普通物料引用,库位 uuid 字符串照旧是精确库位。 """ from __future__ import annotations @@ -16,6 +19,8 @@ #: 物料参数按库位绑定的键 SITE_UUID_KEY = "site_uuid" +#: 库位参数按所属物料选择的键 +OWNER_UUID_KEY = "owner_uuid" def material_at_site(site_uuid: str) -> dict[str, str]: @@ -32,4 +37,25 @@ def site_reference(value: Any) -> Optional[str]: return None -__all__ = ["SITE_UUID_KEY", "material_at_site", "site_reference"] +def site_under_owner(owner_uuid: str) -> dict[str, str]: + """构造「所属物料下一个接受放入物料的空库位」选择(库位参数的值)。""" + + return {OWNER_UUID_KEY: validate_uuid(owner_uuid)} + + +def owner_reference(value: Any) -> Optional[str]: + """``{"owner_uuid": ...}`` 返回所属物料 uuid(原样,未规范化),否则 ``None``。""" + + if isinstance(value, Mapping) and len(value) == 1 and isinstance(value.get(OWNER_UUID_KEY), str): + return value[OWNER_UUID_KEY] + return None + + +__all__ = [ + "OWNER_UUID_KEY", + "SITE_UUID_KEY", + "material_at_site", + "owner_reference", + "site_reference", + "site_under_owner", +] diff --git a/unilabos/server/api/envelope.py b/unilabos/server/api/envelope.py index a8b4e0a7e..c44057ca9 100644 --- a/unilabos/server/api/envelope.py +++ b/unilabos/server/api/envelope.py @@ -288,6 +288,7 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "material_flow_fan_out", "material_template_mismatch", "material_site_invalid", + "site_selection_invalid", }) _WORKFLOW_NOT_FOUND = frozenset({"not_found", "workflow_not_found", "workflow_template_not_found"}) _WORKFLOW_CONFLICT = frozenset({ @@ -327,6 +328,8 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "preflight_failed", # 物料参数按库位绑定失败(库位不存在 / 为空 / 模板不符,细节在 error.details) "material_site_invalid", + # 库位参数按所属物料选择的写法不对(没有 Material.site 关系、放入物料不确定……,细节在 error.details) + "site_selection_invalid", }) diff --git a/unilabos/server/api/materials/inventory.py b/unilabos/server/api/materials/inventory.py index b2f1dda38..bea548437 100644 --- a/unilabos/server/api/materials/inventory.py +++ b/unilabos/server/api/materials/inventory.py @@ -19,7 +19,7 @@ from typing import Any, Dict, List, Optional from fastapi import APIRouter, Body, FastAPI, Query -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, model_validator from unilabos.server.api.envelope import ( INTERNAL_ERROR, @@ -39,14 +39,32 @@ class IngressReserveRequest(BaseModel): + """入口预留:在候选库位(``candidate_site_uuids``)或所属物料下接受载体的库位(``owner_material_uuid``, + 按库位序号;工作流按所属物料选库位用)里预留一个空库位,两者给且只给一个。""" + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) idempotency_key: str = Field(min_length=1) carrier_material_uuid: str = Field(min_length=1) - candidate_site_uuids: List[str] = Field(min_length=1) + candidate_site_uuids: List[str] = Field(default_factory=list) + owner_material_uuid: Optional[str] = Field(default=None, min_length=1) ttl_seconds: int = Field(strict=True, gt=0) backend_task_uuid: Optional[str] = None invocation_key: Optional[str] = None + @model_validator(mode="after") + def _one_candidate_source(self) -> "IngressReserveRequest": + if bool(self.candidate_site_uuids) == bool(self.owner_material_uuid): + raise ValueError("candidate_site_uuids 与 owner_material_uuid 必须给且只给一个") + return self + + +class IngressFinishTaskRequest(BaseModel): + """任务结束:收掉它的活动入口预留(载体已在库位上记 received,否则按 reason 取消)。""" + + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + backend_task_uuid: str = Field(min_length=1) + reason: str = Field(min_length=1) + class IngressCancelRequest(BaseModel): model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) @@ -70,11 +88,19 @@ class MaterialSanityRequest(BaseModel): reservation_uuid: Optional[str] = None +class SiteAdmissionOwner(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + owner_material_uuid: str = Field(min_length=1) + occupant_material_uuid: str = Field(min_length=1) + + class SiteAdmissionRequest(BaseModel): - """任务准入时要读的库位:物料参数按库位绑定(``{"site_uuid"}``)引用的库位。""" + """任务准入时要读的库位:物料参数按库位绑定(``{"site_uuid"}``)引用的库位,以及库位参数按所属物料选择 + (``{"owner_uuid"}``)时的所属物料与放入物料。""" model_config = ConfigDict(extra="forbid") site_uuids: List[str] = Field(default_factory=list, max_length=2000) + owners: List[SiteAdmissionOwner] = Field(default_factory=list, max_length=2000) def _code_of(exc: BaseException) -> int: @@ -159,9 +185,11 @@ def material_sanity(body: MaterialSanityRequest) -> Any: @router.post("/site-admission") def site_admission(body: SiteAdmissionRequest) -> Any: """建任务 / 运行预检时读一次:物料参数按库位绑定(``{"site_uuid"}``)引用的库位是否存在、此刻被哪件物料 - 占着(模板、``module_name``、类别)。只读不写;绑定成功与否由工作流服务判定。""" + 占着(模板、``module_name``、类别);库位参数按所属物料选择(``owners``)时所属物料下接受放入物料的库位 + 与此刻能用的库位。只读不写;绑定 / 选择成功与否由工作流服务与调度器判定。""" - return service.site_admission_facts(site_uuids=body.site_uuids) + return service.site_admission_facts( + site_uuids=body.site_uuids, owners=[item.model_dump() for item in body.owners]) @router.get("/commands/processed") def processed_commands(limit: int = Query(default=200, ge=1, le=500)) -> Any: @@ -331,6 +359,12 @@ def reserve_ingress(body: IngressReserveRequest) -> Any: projection, _created = ingress.reserve(body.model_dump()) return projection + @router.post("/ingress-reservations/finish-task") + def ingress_finish_task(body: IngressFinishTaskRequest) -> Any: + """工作流任务结束时收掉它的活动入口预留(按所属物料选库位时调度器预留的库位)。""" + + return {"reservations": ingress.finish_task(body.backend_task_uuid, reason=body.reason)} + @router.get("/ingress-reservations") def list_ingress(state: Optional[str] = Query(default=None), limit: int = Query(default=200, ge=1, le=500)) -> Any: return {"reservations": ingress.list(state=state, limit=limit)} diff --git a/unilabos/server/api/runtime/workflow.py b/unilabos/server/api/runtime/workflow.py index 05c635b3d..393f61e88 100644 --- a/unilabos/server/api/runtime/workflow.py +++ b/unilabos/server/api/runtime/workflow.py @@ -307,7 +307,9 @@ class WorkflowTaskCreateRequest(_StrictModel): input: Dict[str, Any] = Field(default_factory=dict, description=( "整图任务的入口参数(工作流 input_contract)。物料参数(ResourceSlot)可以给 {\"site_uuid\": 库位 uuid}," "表示此刻占着该库位的物料:建任务时解析成占用物料的 {\"uuid\"} 并冻结进任务;库位不存在、为空或物料模板不符时" - "拒绝(error.code=material_site_invalid,error.details.reason 为 site_not_found / site_empty / template_mismatch)")) + "拒绝(error.code=material_site_invalid,error.details.reason 为 site_not_found / site_empty / template_mismatch)。" + "库位参数(SiteSlot)可以给 {\"owner_uuid\": 所属物料 uuid}:调度器在任务准入时按库位序号选一个接受放入物料的空库位、" + "经入口预留占住并冻结(写法不对时 error.code=site_selection_invalid)")) #: V1 任务优先级:normal 普通任务,high 高优先级任务(随任务持久化,排序由调度器负责) priority: Literal["normal", "high"] = "normal" #: V1 库存绑定:建任务时落到冻结计划里对应的库存需求,决定预留哪份试剂 / 当前内容物 @@ -349,7 +351,8 @@ class WorkflowPreflightRequest(_BackendModel): target_node_uuid: Optional[str] = None input: Dict[str, Any] = Field(default_factory=dict, description=( "候选入口参数;物料参数按库位绑定({\"site_uuid\"})与建任务同一条解析路径," - "解析失败报 invalid_material_site 检查(details.reason 同建任务)")) + "解析失败报 invalid_material_site 检查(details.reason 同建任务);库位参数按所属物料选择({\"owner_uuid\"})" + "只读候选:没有接受的库位报 invalid_site_selection,都被占着报 site_selection_unavailable")) inventory_bindings: List[WorkflowInventoryBindingRequest] = Field(default_factory=list) #: dev 扩展:工作流修订乐观锁(V1 无此字段) expected_revision: Optional[int] = Field(default=None, ge=1, strict=True) diff --git a/unilabos/server/scheduler/service.py b/unilabos/server/scheduler/service.py index 4a204c83b..e39efb3dc 100644 --- a/unilabos/server/scheduler/service.py +++ b/unilabos/server/scheduler/service.py @@ -83,6 +83,15 @@ from unilabos.server.services.runtime.workflow.service import WorkflowError, WorkflowService from unilabos.server.services.runtime.workflow.store import PROCESS_RESTART_UNCERTAINTY_REASON from unilabos.server.services.runtime.workflow.task_lifecycle import TERMINAL_TASK +from unilabos.server.services.runtime.workflow.site_selections import ( + NO_ACCEPTABLE_SITE, + WAIT_SITE_SELECTION, + SiteSelectionError, + has_owner_selections, + node_reservations, + owner_site_requests, + reservation_payload, +) logger = logging.getLogger(__name__) @@ -191,11 +200,15 @@ class BackendSchedulingError(RuntimeError): def preflight_error(error: Exception) -> Dict[str, Any]: - """任务启动前不可执行:库存不足另标 ``reason``,其余(设备 / 动作缺失、计划非法)只有消息。""" + """任务启动前不可执行:库存不足另标 ``reason``;按所属物料选不出库位标 ``reason`` 并带 ``details`` + (参数、节点、所属物料);其余(设备 / 动作缺失、计划非法)只有消息。""" item: Dict[str, Any] = {"code": "plan_not_executable", "stage": ERROR_STAGE_PREFLIGHT, "scope": "task", "message": str(error)} if getattr(error, "code", None) == "insufficient_inventory": item["reason"] = "inventory_shortage" + if isinstance(error, SiteSelectionError): + item["reason"] = error.reason + item["details"] = dict(error.details) return item @@ -397,6 +410,9 @@ def __init__( self._inventory_waiting_tasks: Dict[str, tuple[str, list[str]]] = {} # 等库存任务已被拒的次数:重试换新的预留命令身份(被拒的命令按幂等会原样重放拒绝) self._inventory_wait_attempts: Dict[str, int] = {} + # 尚未开始、按所属物料选库位时接受的库位都被占着 / 已被预留的任务:task -> 创建时间。 + # 保持 pending 排队,库位空出(任务结束)或兜底重算时按创建先后重新提交。 + self._site_waiting_tasks: Dict[str, str] = {} # 运行任务容量已满、保持 pending 排队的任务:task -> (创建时间, 工作流);按创建先后放行 self._capacity_waiting_tasks: Dict[str, tuple[str, str]] = {} self._dispatched_jobs: set[str] = set() @@ -602,6 +618,9 @@ async def run_task(self, task_uuid: str) -> Dict[str, NodeState]: # waiting_reconciliation:任务可接管,但上一进程在飞的 attempt 要由人裁决; # DAG 照常构建,这些节点在起跑时改为开决策(见 _start_node),不重放。 if prepared["state"] not in {"ready", "waiting_reconciliation"}: + # 起跑前就结束的任务(如排队时被取消):收掉准入时预留的库位 + if self.workflow.get_workflow_task(task_uuid).get("status") in TERMINAL_TASK: + self._finish_task_sites(task_uuid) return {} task = prepared["task"] runs = prepared["runs"] @@ -696,6 +715,7 @@ async def run_task(self, task_uuid: str) -> Dict[str, NodeState]: if not self._stopping: self._cleanup_task_resources(task_uuid) self._release_unconsumed_task_inventory(task_uuid) + self._finish_task_sites(task_uuid, task) with self._guard: self._runners.pop(task_uuid, None) for run_uuid in specs: @@ -718,9 +738,10 @@ async def run_task(self, task_uuid: str) -> Dict[str, NodeState]: # 任务终结(含取消)后不再有待裁决 attempt,控制态不能停留在 waiting_reconciliation self._settle_task_reconciliation(task_uuid) if not self._stopping: - # 它让出了运行容量、预留已释放或结算:排队的任务按先后再试 + # 它让出了运行容量、预留已释放或结算、库位可能空出:排队的任务按先后再试 self._retry_capacity_waiting_tasks() self._retry_inventory_waiting_tasks() + self._retry_site_waiting_tasks() def _admit_fresh_task(self, task_uuid: str) -> bool: """尚未开始的任务先整任务预留库存,再转 ``running``;返回 False 表示这次不起跑。 @@ -737,12 +758,30 @@ def _admit_fresh_task(self, task_uuid: str) -> bool: with self._guard: self._inventory_waiting_tasks.pop(task_uuid, None) self._capacity_waiting_tasks.pop(task_uuid, None) + self._site_waiting_tasks.pop(task_uuid, None) return True runs = self.workflow.list_workflow_node_runs(task_uuid) if any(run["status"] != "pending" for run in runs): return True if not self._admit_task_capacity(task): return False + # 按所属物料选择的库位参数:选定并经入口预留占住,冻结进任务;接受的库位都被占着时排队 + try: + selected = self._select_task_sites(task, runs) + except Exception as exc: + self._fail_unstarted_task(task_uuid, runs, exc) + self._settle_task_reconciliation(task_uuid) + if isinstance(exc, (SiteSelectionError, BackendSchedulingError, MaterialsServiceError, MaterialsHTTPError)): + logger.warning("workflow task %s cannot start: %s", task_uuid, exc) + else: + logger.exception("workflow task %s failed while selecting sites", task_uuid) + return False + if selected is None: + return False + if selected: + # 选定的库位已冻结进任务:按冻结后的计划与节点参数继续准入 + task = self.workflow.get_workflow_task(task_uuid) + runs = self.workflow.list_workflow_node_runs(task_uuid) specs: Optional[Dict[str, Dict[str, Any]]] = None with self._guard: attempt = self._inventory_wait_attempts.get(task_uuid, 0) @@ -773,6 +812,121 @@ def _admit_fresh_task(self, task_uuid: str) -> bool: self._clear_task_inventory_wait(task_uuid, waited) return True + def _select_task_sites(self, task: Dict[str, Any], runs: list[Dict[str, Any]]) -> Optional[bool]: + """任务准入:按所属物料选择的库位参数(``{"owner_uuid"}``)选定库位、经入口预留占住并冻结进任务。 + + 返回 True 表示选定并冻结了库位,False 表示没有要选的;``None`` 表示接受的库位此刻都被占着或已被预留, + 任务保持 ``pending`` 排队(已选定的预留按幂等键保留,重试时原样取回)。写法不对、所属物料下没有接受放入 + 物料的库位抛 :class:`SiteSelectionError`(任务按 ``plan_not_executable`` 失败)。 + """ + + task_uuid = str(task["uuid"]) + requests = owner_site_requests(task.get("execution_plan") or {}) + if not requests: + return False + reserve = getattr(self.materials_gateway, "reserve_ingress", None) + if not callable(reserve): + raise BackendSchedulingError("物料权威尚未接入,不能按所属物料选择库位") + selections: list[Dict[str, Any]] = [] + for request in requests: + try: + reservation = reserve(reservation_payload(task_uuid, request)) + except Exception as error: + if temporary_resource_condition(error) is not None: + self._wait_task_sites(task, runs, request.targets, str(error)) + return None + if getattr(error, "conflict", None) == "site_template" or getattr(error, "business_code", None) == 6008: + raise SiteSelectionError( + NO_ACCEPTABLE_SITE, + f"库位参数 {request.parameter}(节点 {request.node_uuid})按所属物料选库位:{error}", + parameter=request.parameter, owner_uuid=request.owner_uuid, node_uuid=request.node_uuid, + ) from error + raise + selections.append({**request.record(), "site_uuid": str(reservation["site_uuid"]), + "reservation_uuid": str(reservation["uuid"])}) + self.workflow.freeze_task_site_selections(task_uuid, selections) + logger.info("任务 %s 按所属物料选定库位:%s", task_uuid, + "、".join(f"{item['key']} → {item['site_uuid']}" for item in selections)) + with self._guard: + self._site_waiting_tasks.pop(task_uuid, None) + self._clear_task_site_wait(task_uuid) + return True + + def _wait_task_sites(self, task: Dict[str, Any], runs: list[Dict[str, Any]], + targets: Iterable[tuple[str, str]], message: str) -> None: + from .attempt_inventory import attempt_wait + + task_uuid = str(task["uuid"]) + with self._guard: + first = task_uuid not in self._site_waiting_tasks + self._site_waiting_tasks[task_uuid] = str(task.get("create_time") or "") + if first: + logger.info("任务 %s 按所属物料选库位时接受的库位都被占用或已预留,排队等待:%s", task_uuid, message) + nodes = {node_uuid for node_uuid, _name in targets} + for run in runs: + if str(run.get("workflow_node_uuid")) not in nodes: + continue + try: + attempt_wait(self.workflow, self._authority_epoch, str(run["current_job_uuid"]), + {"code": WAIT_SITE_SELECTION, "message": f"按所属物料选库位:{message}"}) + except Exception: # noqa: BLE001 - 排队原因只是观测 + logger.warning("任务 %s 的排队原因写入失败", task_uuid, exc_info=True) + + def _clear_task_site_wait(self, task_uuid: str) -> None: + from .attempt_inventory import attempt_wait + + lister = getattr(self.workflow, "list_workflow_node_jobs", None) + if not callable(lister): + return + try: + jobs = [str(job["uuid"]) for job in lister(task_uuid) + if ((job.get("control_data") or {}).get("wait_reason") or {}).get("code") == WAIT_SITE_SELECTION] + except Exception: # noqa: BLE001 + logger.debug("读取任务 %s 的 attempt 失败", task_uuid, exc_info=True) + return + for job_uuid in jobs: + try: + attempt_wait(self.workflow, self._authority_epoch, job_uuid, None) + except Exception: # noqa: BLE001 + logger.warning("任务 %s 的排队原因清除失败", task_uuid, exc_info=True) + + def _retry_site_waiting_tasks(self) -> None: + """按创建先后重新提交等库位的任务;接受的库位仍被占着的会再次排队。""" + with self._guard: + if self._stopping or not self._site_waiting_tasks: + return + waiting = sorted(self._site_waiting_tasks.items(), key=lambda item: (item[1], item[0])) + for task_uuid, _created in waiting: + self.submit(task_uuid) + + def _start_site_reservations(self, task: Dict[str, Any], spec: Dict[str, Any]) -> None: + """派发用到选定库位的动作前,把它的入口预留转为 in_transit:放入物料直接放进来等同接收。""" + + mark = getattr(self.materials_gateway, "mark_ingress_in_transit", None) + if not callable(mark): + return + for reservation_uuid in node_reservations(task.get("execution_plan"), str(spec["workflow_node_uuid"])): + try: + mark(reservation_uuid) + except Exception as error: # noqa: BLE001 - 预留已接收 / 过期:库位核对照旧保护 + logger.debug("入口预留 %s 转运输中失败:%s", reservation_uuid, error) + + def _finish_task_sites(self, task_uuid: str, task: Optional[Dict[str, Any]] = None) -> None: + """任务结束:收掉准入时为它预留的库位(物料已在库位上记 received,否则取消)。""" + + with self._guard: + self._site_waiting_tasks.pop(task_uuid, None) + finish = getattr(self.materials_gateway, "finish_task_ingress", None) + if not callable(finish): + return + try: + task = task or self.workflow.get_workflow_task(task_uuid) + if not has_owner_selections(task.get("execution_plan")): + return + finish(task_uuid, reason=f"工作流任务 {task_uuid} 已结束") + except Exception: # noqa: BLE001 - 收尾失败不影响任务终态,预留按有效期自然过期 + logger.warning("任务 %s 的库位预留收尾失败", task_uuid, exc_info=True) + def _admit_task_capacity(self, task: Dict[str, Any]) -> bool: """运行任务容量(全局 / 每工作流)还有余量、且没有更早排队又能走的任务时放行;否则保持 pending 排队。 @@ -969,6 +1123,7 @@ async def _inventory_recovery_loop(self) -> None: self._reconcile_resources() self._retry_capacity_waiting_tasks() self._retry_inventory_waiting_tasks() + self._retry_site_waiting_tasks() def _expire_manual_confirmations(self) -> None: """到期仍待决的人工确认(含人工物料步骤)收敛为超时;决策经 resolver 回到本调度器。""" @@ -1740,6 +1895,7 @@ def _dispatch_held_node(self, task: Dict[str, Any], node: DagNode) -> None: dispatch_invoked = False try: self._execution_claims.reserve(spec["resource_request"], authority_epoch=self._authority_epoch) + self._start_site_reservations(task, spec) material_execution = None if spec.get("physical_contract") or spec.get("inventory_reservation_uuid"): from .physical_contract import resolve_physical_contract @@ -3900,6 +4056,7 @@ def _fail_unstarted_task( status="failed", error_info=[preflight_error(error)], ) + self._finish_task_sites(task_uuid) __all__ = [ diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index a23954f6e..977f2d2c3 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -1389,12 +1389,15 @@ def material_sanity_facts( return material_sanity_facts(self, material_uuids, reservation_uuid=reservation_uuid) - def site_admission_facts(self, *, site_uuids: Sequence[str] = ()) -> dict[str, Any]: - """任务准入时按库位绑定物料要的只读库位事实(不写库、不判定),见 ``materials/site_admission.py``。""" + def site_admission_facts( + self, *, site_uuids: Sequence[str] = (), owners: Sequence[Mapping[str, Any]] = (), + ) -> dict[str, Any]: + """任务准入时的只读库位事实(按库位绑定物料 / 按所属物料选库位,不写库、不判定),见 + ``materials/site_admission.py``。""" from .site_admission import site_admission_facts - return site_admission_facts(self, site_uuids=site_uuids) + return site_admission_facts(self, site_uuids=site_uuids, owners=owners) def _candidate_inventory_lots( self, @@ -3391,18 +3394,33 @@ def _assert_no_parent_cycle(self, material_uuid: str, parent_uuid: Optional[str] ).fetchone() cursor = row[0] if row is not None else None - def _assert_site_not_ingress_reserved(self, site: SiteRecord) -> None: + def _assert_site_not_ingress_reserved(self, site: SiteRecord, *, moving_material_uuid: Optional[str] = None) -> None: """活动入口预留(reserved 未过期 / in_transit)期间库位不接受任何放入。 载体本身也只能经预留的 receive 落位(receive 先把预留置为 received 再移动), 人工移动、工作流搬运预检与 transfer 都走这里,拿到 ``site_ingress_reserved`` 冲突。 + 唯一例外:``in_transit`` 的载体(``moving_material_uuid``)被直接放进自己预留的库位,等同接收—— + 预留在同一事务里置为 ``received``(工作流按所属物料选库位时,放入动作派发前把预留转为 in_transit)。 """ + now = self._now_ms() row = self.connection.execute( "SELECT reservation_uuid, carrier_material_uuid, state FROM station_ingress_reservation " "WHERE site_uuid=? AND (state='in_transit' OR (state='reserved' AND expires_at_ms > ?)) LIMIT 1", - (site.site_uuid, self._now_ms()), + (site.site_uuid, now), ).fetchone() + if ( + row is not None + and row["state"] == "in_transit" + and moving_material_uuid is not None + and row["carrier_material_uuid"] == moving_material_uuid + ): + self.connection.execute( + "UPDATE station_ingress_reservation SET state='received', received_at_ms=?, " + "updated_at_ms=MAX(?, created_at_ms, updated_at_ms), revision=revision+1 WHERE reservation_uuid=?", + (now, now, row["reservation_uuid"]), + ) + return if row is not None: raise MaterialConflictError( f"库位 {site.label}({site.site_uuid})已被入口预留 {row['reservation_uuid']}" @@ -3466,7 +3484,7 @@ def _apply_material_move( ): raise MaterialConflictError("destination site is occupied", conflict="site_occupied") if placing: - self._assert_site_not_ingress_reserved(destination) + self._assert_site_not_ingress_reserved(destination, moving_material_uuid=value.material_uuid) self._assert_no_parent_cycle(value.material_uuid, parent_uuid) same_site = ( source is not None diff --git a/unilabos/server/services/materials/ingress.py b/unilabos/server/services/materials/ingress.py index 58fe67e97..5390d622e 100644 --- a/unilabos/server/services/materials/ingress.py +++ b/unilabos/server/services/materials/ingress.py @@ -9,6 +9,12 @@ 活动预留期间库位只留给这次接收:人工移动、transfer、工作流搬运派发前的预检都经 ``MaterialsService._apply_material_move`` 拿到 ``site_ingress_reserved`` 冲突(HTTP 6011), 调度侧把它当作临时资源条件等待;``receive`` 先把预留置为 ``received`` 再在同一事务里移动载体。 +``in_transit`` 的载体被直接放进自己预留的库位(工作流动作把它搬进来)等同接收:同一事务里预留置为 ``received``。 + +调度器按所属物料选库位(库位参数给 ``{"owner_uuid": ...}``)也走这里:请求给 ``owner_material_uuid`` 而不是 +``candidate_site_uuids``,候选是所属物料下接受载体(放入物料)的库位(模板白名单与允许的资源类别,按库位序号); +一个都不接受是 ``site_template`` 冲突(6008,合同错误),都被占着或已被预留是 ``site_occupied`` 冲突(6007, +临时条件,调度器排队等)。预留随任务冻结,派发用到它的动作时转 ``in_transit``,任务结束时 :meth:`finish_task` 收尾。 """ from __future__ import annotations @@ -82,15 +88,20 @@ def reserve(self, values: Mapping[str, Any]) -> tuple[dict[str, Any], bool]: key = str(values.get("idempotency_key") or "").strip() carrier = str(values.get("carrier_material_uuid") or "").strip() candidates: Sequence[str] = [str(item).strip() for item in values.get("candidate_site_uuids") or [] if str(item).strip()] + owner = str(values.get("owner_material_uuid") or "").strip() ttl = values.get("ttl_seconds") - if not key or not carrier or not candidates: - raise MaterialValidationError("idempotency_key, carrier_material_uuid and candidate_site_uuids are required") + if not key or not carrier or bool(candidates) == bool(owner): + raise MaterialValidationError( + "idempotency_key, carrier_material_uuid and one of candidate_site_uuids / owner_material_uuid are required" + ) if not isinstance(ttl, int) or isinstance(ttl, bool) or ttl <= 0: raise MaterialValidationError("ttl_seconds 必须是正整数") request = { "carrier_material_uuid": carrier, "candidate_site_uuids": list(candidates), "ttl_seconds": ttl, "backend_task_uuid": values.get("backend_task_uuid"), "invocation_key": values.get("invocation_key"), } + if owner: + request["owner_material_uuid"] = owner request_hash = canonical_hash(request) now = self.materials._now_ms() with self.materials.write(): @@ -105,6 +116,8 @@ def reserve(self, values: Mapping[str, Any]) -> tuple[dict[str, Any], bool]: carrier_record = MaterialsRepository.get_material(self.materials, carrier) if carrier_record is None: raise MaterialNotFoundError("可搬运载体尚未同步到目标工站", subject="material") + if owner: + candidates = self._owner_candidates(owner, carrier) # 同一载体同时只能去一个入口库位(到期的 reserved 已在上面置为 expired) held = self.connection.execute( "SELECT reservation_uuid, site_uuid, state FROM station_ingress_reservation " @@ -137,6 +150,10 @@ def reserve(self, values: Mapping[str, Any]) -> tuple[dict[str, Any], bool]: tuple(candidates), ).fetchall() if not available: + if owner: + raise MaterialConflictError( + f"物料 {owner} 下接受载体 {carrier} 的库位都被占用或已被预留", conflict="site_occupied" + ) raise MaterialConflictError("逻辑入口当前没有可接收载体的库位", conflict="site_occupied") # 只预留接受载体模板的库位,免得载体到站后 receive 才因库位白名单(6008)失败 accepting = [ @@ -160,6 +177,48 @@ def reserve(self, values: Mapping[str, Any]) -> tuple[dict[str, Any], bool]: ) return self._projection(self._row(reservation_uuid)), True + def _owner_candidates(self, owner: str, carrier: str) -> list[str]: + """所属物料下接受载体的库位(按库位序号);一个都没有是合同错误(``site_template``,6008)。""" + + from .site_admission import acceptable_owner_sites, occupant_facts + + owner_record = MaterialsRepository.get_material(self.materials, owner) + if owner_record is None or owner_record.deleted_at_ms is not None: + raise MaterialNotFoundError(f"库位所属物料 {owner} 不存在", subject="material") + occupant = occupant_facts(self.materials, carrier) or {} + sites = acceptable_owner_sites(self.materials, owner, occupant) + if not sites: + raise MaterialConflictError( + f"物料 {owner_record.display_name}({owner})下没有接受 {occupant.get('template_name') or carrier} 的库位" + "(库位的模板白名单或允许的资源类别不含它)", + conflict="site_template", + ) + return [site.site_uuid for site in sites] + + def finish_task(self, backend_task_uuid: str, *, reason: str) -> list[dict[str, Any]]: + """任务结束:收掉它的活动预留。载体已在预留的库位上记 ``received``,否则按 ``reason`` 取消。""" + + task = str(backend_task_uuid or "").strip() + reason = str(reason or "").strip() + if not task or not reason: + raise MaterialValidationError("backend_task_uuid and reason are required") + now = self.materials._now_ms() + with self.materials.write(): + self._expire_due(now) + rows = self.connection.execute( + "SELECT ingress.reservation_uuid, ingress.carrier_material_uuid, site.occupied_material_uuid " + "FROM station_ingress_reservation AS ingress LEFT JOIN site ON site.site_uuid = ingress.site_uuid " + "WHERE ingress.backend_task_uuid=? AND ingress.state IN ('reserved','in_transit') " + "ORDER BY ingress.created_at_ms, ingress.reservation_uuid", + (task,), + ).fetchall() + for row in rows: + if row["occupied_material_uuid"] == row["carrier_material_uuid"]: + self._transition(row["reservation_uuid"], "received", now, received_at_ms=now) + else: + self._transition(row["reservation_uuid"], "canceled", now, canceled_at_ms=now, cancel_reason=reason) + return [self._projection(self._row(row["reservation_uuid"])) for row in rows] + def get(self, reservation_uuid: str) -> dict[str, Any]: with self.materials.write(): self._expire_due(self.materials._now_ms()) diff --git a/unilabos/server/services/materials/site_admission.py b/unilabos/server/services/materials/site_admission.py index 15ed458ca..0e76fbb80 100644 --- a/unilabos/server/services/materials/site_admission.py +++ b/unilabos/server/services/materials/site_admission.py @@ -1,14 +1,22 @@ -"""任务准入时读的库位事实(调度权威的工作流服务消费,只读不写、不做判定)。 +"""任务准入时读的库位事实(调度权威的工作流服务 / 调度器消费,只读不写、不做判定)。 -物料参数按库位绑定(``{"site_uuid": ...}``)在建任务 / 运行预检时解析:这里读库位此刻的占用物料及其模板 -(模板名、``module_name``、类别),由工作流服务换成 ``{"uuid": 占用物料}`` 并冻结进任务。 +两种按库位的写法在准入时解析成普通参数: + +- 物料参数按库位绑定(``{"site_uuid": ...}``):读库位此刻的占用物料及其模板(模板名、``module_name``、类别), + 由工作流服务换成 ``{"uuid": 占用物料}`` 并冻结进任务; +- 库位参数按所属物料选择(``{"owner_uuid": ...}``):读所属物料下接受放入物料的库位(库位的接收规则: + 模板白名单 ``extra.allowed_resource_template_uuids`` 与 ``allowed_resource_categories``),按库位序号排好, + 并标出此刻能用的(空着、没有活动入口预留、没有未结算物理动作占着)。真正选定与预留走入口预留 + (``ingress.py`` 的 ``owner_material_uuid`` 写法),这里只给建任务与运行预检看。 """ from __future__ import annotations -from collections.abc import Iterable +from collections.abc import Iterable, Mapping from typing import Any, Optional +from unilabos.server.database.tables.materials import SiteRecord + def _template_facts(service: Any, template_uuid: str) -> dict[str, Any]: try: @@ -37,12 +45,89 @@ def _material_facts(service: Any, material_uuid: str) -> Optional[dict[str, Any] } -def site_admission_facts(service: Any, *, site_uuids: Iterable[str] = ()) -> dict[str, Any]: - """一次读出按库位绑定要的事实:``{"sites": {site_uuid: {...}}}``。 +def site_accepts_material(site: SiteRecord, material: Mapping[str, Any]) -> bool: + """库位的接收规则是否接受这件物料:模板白名单(空表示不限)与允许的资源类别(空表示不限)都要满足。""" + + from .core import MaterialsService + + if not MaterialsService.site_accepts_template( + site, template_uuid=str(material.get("template_uuid") or ""), + template_name=str(material.get("template_name") or ""), + ): + return False + allowed = {str(item).casefold() for item in site.allowed_resource_categories or []} + if not allowed: + return True + return bool(allowed & {str(item).casefold() for item in material.get("category") or []}) + + +def acceptable_owner_sites(service: Any, owner_material_uuid: str, occupant: Mapping[str, Any]) -> list[SiteRecord]: + """所属物料下(可见的)接受这件物料的库位,按库位序号排序。""" + + from .store import MaterialsRepository + + return [ + site for site in MaterialsRepository.list_sites(service, owner_material_uuid) + if site.visible and site_accepts_material(site, occupant) + ] + + +def occupant_facts(service: Any, material_uuid: str) -> Optional[dict[str, Any]]: + """放入物料的模板事实(接收规则判定用);物料不存在或已删除时为 ``None``。""" + + return _material_facts(service, material_uuid) + + +def _available(conn: Any, site_uuids: list[str], now_ms: int) -> list[str]: + """空着、没有活动入口预留(未到期的 reserved 或 in_transit)、没有未结算物理动作占着的库位。""" + + if not site_uuids: + return [] + marks = ",".join("?" for _ in site_uuids) + rows = conn.execute( + "SELECT site.site_uuid FROM site LEFT JOIN station_ingress_reservation AS ingress " + "ON ingress.site_uuid = site.site_uuid AND (ingress.state='in_transit' OR " + "(ingress.state='reserved' AND ingress.expires_at_ms > ?)) " + "LEFT JOIN material_execution_hold AS hold " + "ON hold.aggregate_type='site' AND hold.aggregate_uuid = site.site_uuid " + f"WHERE site.site_uuid IN ({marks}) AND site.deleted_at_ms IS NULL " + "AND site.occupied_material_uuid IS NULL AND ingress.reservation_uuid IS NULL AND hold.job_uuid IS NULL", + (now_ms, *site_uuids), + ).fetchall() + found = {row[0] for row in rows} + return [identity for identity in site_uuids if identity in found] + + +def _owner_facts(service: Any, request: Mapping[str, Any]) -> dict[str, Any]: + from .store import MaterialsRepository + + owner_uuid = str(request.get("owner_material_uuid") or "").strip() + occupant_uuid = str(request.get("occupant_material_uuid") or "").strip() + owner = MaterialsRepository.get_material(service, owner_uuid) if owner_uuid else None + owner_exists = owner is not None and owner.deleted_at_ms is None + occupant = _material_facts(service, occupant_uuid) if occupant_uuid else None + acceptable = acceptable_owner_sites(service, owner_uuid, occupant) if owner_exists and occupant else [] + return { + "owner_material_uuid": owner_uuid, + "occupant_material_uuid": occupant_uuid, + "owner_exists": owner_exists, + "occupant": occupant, + "acceptable": [{"site_uuid": site.site_uuid, "label": site.label} for site in acceptable], + "available": _available(service.connection, [site.site_uuid for site in acceptable], service._now_ms()), + } + + +def site_admission_facts( + service: Any, *, site_uuids: Iterable[str] = (), owners: Iterable[Mapping[str, Any]] = (), +) -> dict[str, Any]: + """一次读出按库位绑定 / 按所属物料选择要的事实:``{"sites": {site_uuid: {...}}, "owners": [...]}``。 - 不存在(或已删除)的库位 ``exists=False``;存在的给 ``label``、所属物料、占用物料 ``occupant`` - (``material_uuid`` / ``template_uuid`` / ``template_name`` / ``module_name`` / ``category`` / - ``lifecycle_status``;空库位为 ``None``)。 + - ``sites``:不存在(或已删除)的库位 ``exists=False``;存在的给 ``label``、所属物料、占用物料 ``occupant`` + (``material_uuid`` / ``template_uuid`` / ``template_name`` / ``module_name`` / ``category`` / + ``lifecycle_status``;空库位为 ``None``); + - ``owners``:按请求(``{"owner_material_uuid", "occupant_material_uuid"}``)顺序,每项给 ``owner_exists``、 + 放入物料 ``occupant``(同上;不存在为 ``None``)、接受它的库位 ``acceptable``(``[{"site_uuid", "label"}]``, + 按库位序号)与此刻能用的 ``available``(库位 uuid 列表)。 """ from .store import MaterialsRepository @@ -72,10 +157,10 @@ def site_admission_facts(service: Any, *, site_uuids: Iterable[str] = ()) -> dic "occupied_material_uuid": site.occupied_material_uuid, "occupant": occupant, } - return {"sites": sites} + return {"sites": sites, "owners": [_owner_facts(service, request) for request in owners]} finally: if not nested: conn.rollback() -__all__ = ["site_admission_facts"] +__all__ = ["acceptable_owner_sites", "occupant_facts", "site_accepts_material", "site_admission_facts"] diff --git a/unilabos/server/services/runtime/workflow/run_preflight.py b/unilabos/server/services/runtime/workflow/run_preflight.py index a6e413744..233f702fe 100644 --- a/unilabos/server/services/runtime/workflow/run_preflight.py +++ b/unilabos/server/services/runtime/workflow/run_preflight.py @@ -5,6 +5,7 @@ from typing import Any from unilabos.protocol.materials import InventoryRequirement +from unilabos.protocol.runtime.site_references import owner_reference from unilabos.registry.typed_contract import validate_action_values from .entry_parameters import declared_input_contract, resolve_task_input from .store import utc_now @@ -24,7 +25,7 @@ def __init__(self, message: str, *, wait_code: str | None = None) -> None: def deferred_parameters(plan: Mapping[str, Any], node: Mapping[str, Any]) -> list[str]: - """上游输出、库存分配和循环变量在派发时才能确定。""" + """上游输出、库存分配和循环变量在派发时才能确定;按所属物料选择的库位参数在任务准入时才选定。""" names = { str(edge.get("target_data_key") or "").split("@@@")[-1] for edge in plan.get("edges", []) @@ -38,6 +39,7 @@ def dynamic(value: Any) -> bool: return value.get("kind") == "node_output" or any(dynamic(item) for item in value.values()) return isinstance(value, list) and any(dynamic(item) for item in value) names.update(key for key, value in node.get("param", {}).items() if dynamic(value)) + names.update(key for key, value in node.get("param", {}).items() if owner_reference(value) is not None) return sorted(names - {""}) @@ -120,6 +122,31 @@ 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}) + # 按所属物料选择的库位参数({"owner_uuid"}):任务准入时才选定并预留,这里只读候选 + from .site_selections import SiteSelectionError, check_owner_sites, owner_site_requests, read_owner_facts + + nodes_by_uuid = {item["uuid"]: item for item in plan["nodes"]} + try: + selection_requests = owner_site_requests(plan) + selection_results = check_owner_sites(selection_requests, read_owner_facts(materials, selection_requests)) + except SiteSelectionError as error: + check("resources", "blocked", "invalid_site_selection", error.message, + node=nodes_by_uuid.get(error.details.get("node_uuid")), details=error.details) + return finalize(report) + except (RuntimeError, OSError) as error: + check("resources", "blocked", "site_selection_facts_unavailable", f"无法读取按所属物料选择的库位:{error}") + return finalize(report) + for request, result in zip(selection_requests, selection_results): + details = {"parameter": request.parameter, "owner_uuid": request.owner_uuid, + "occupant_uuid": request.occupant_uuid, **result} + if result["available"]: + check("resources", "passed", "site_selection_ready", + f"库位参数 {request.parameter} 将在任务准入时按库位序号选定(当前可用 {len(result['available'])} 个)", + node=nodes_by_uuid.get(request.node_uuid), details=details) + else: + check("resources", "blocked", "site_selection_unavailable", + f"库位参数 {request.parameter}:所属物料下接受放入物料的库位此刻都被占用或已预留(提交后排队,空出后选定)", + node=nodes_by_uuid.get(request.node_uuid), details=details) endpoints = None if service._preflight_endpoints is not None: try: diff --git a/unilabos/server/services/runtime/workflow/service.py b/unilabos/server/services/runtime/workflow/service.py index 14c482592..02441ea8f 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, "物料参数按库位绑定失败"), + "site_selection_invalid": (422, "库位参数按所属物料选择失败"), "invalid_composite_child_type": (400, "只有实验操作可以作为子工作流被引用"), "invalid_composite_child_status": (409, "被引用的实验操作当前修订尚未发布"), "local_task_authority_forbidden": ( @@ -1528,6 +1529,9 @@ def build_plan(graph: Dict[str, Any]) -> Any: ) # 按库位绑定的物料参数解析成占用物料,计划、attempt 参数与任务输入一起冻结 self._bind_material_sites(plan, jobs, resolved["input"], site_facts) + # 按所属物料选择的库位参数在任务准入时由调度器选定;写法不对(没有 Material.site 关系、放入物料不确定、 + # 与所属物料参数不一致)建任务时就拒绝 + self._check_site_selections(plan) try: bind_plan_inventory(plan, bindings, binding_sources) except (ValueError, InventoryBindingUnavailable) as exc: @@ -1605,6 +1609,15 @@ def _bind_material_sites( except MaterialSiteError as exc: raise WorkflowError("material_site_invalid", detail=exc.message, details=exc.details) from None + @staticmethod + def _check_site_selections(plan: Dict[str, Any]) -> None: + from .site_selections import SiteSelectionError, owner_site_requests + + try: + owner_site_requests(plan) + except SiteSelectionError as exc: + raise WorkflowError("site_selection_invalid", detail=exc.message, details=exc.details) from None + def create_ad_hoc_device_action_task( self, *, diff --git a/unilabos/server/services/runtime/workflow/site_selections.py b/unilabos/server/services/runtime/workflow/site_selections.py new file mode 100644 index 000000000..5b7ad583c --- /dev/null +++ b/unilabos/server/services/runtime/workflow/site_selections.py @@ -0,0 +1,275 @@ +"""库位参数按所属物料选择:``{"owner_uuid": ...}`` 在任务准入时选定一个库位、经入口预留占住并冻结进任务。 + +``SiteSlot`` 参数(带 ``Material.site("site", owner=..., occupant=...)`` 关系)可以给 +``{"owner_uuid": "<所属物料 uuid>"}`` 而不是库位 uuid,工作流入口参数(``SiteSlot``)也可以。规则: + +- 候选是所属物料下接受放入物料(``Material.site`` 的 ``occupant`` 参数,按库位绑定的已先解析)的库位: + 库位的接收规则(模板白名单与允许的资源类别)要接受它;按库位序号选第一个空着、没有被别的任务预留的; +- 调度器在任务准入时(``BackendScheduler._admit_fresh_task``)用物料权威的入口预留占住选中的库位 + (``owner_material_uuid`` 写法,预留随任务:``backend_task_uuid`` = 任务 uuid),再把库位 uuid 冻结进计划节点参数、 + attempt 参数与任务输入(计划的 ``site_selections`` 记录选择与预留); +- 所属物料下没有接受放入物料的库位是预检错误(``reason=no_acceptable_site``);接受的库位此刻都被占着或已被预留 + 按临时条件排队(attempt 的 ``wait_reason.code=site_group_unavailable``),空出后按任务创建先后重试; +- 用到这个库位的动作派发时预留转 ``in_transit``(放入物料直接放进来等同接收),任务结束时收尾 + (物料已在库位上记 received,否则取消)。精确的库位 uuid 照旧不经过这里。 + +本模块只放纯函数(建任务、运行预检与调度器共用);读物料权威与写库由调用方负责。 +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from typing import Any, Optional + +from unilabos.protocol.runtime.site_references import owner_reference + +#: 预检错误的 ``reason`` +NO_SITE_RELATION = "no_site_relation" +OCCUPANT_UNDECLARED = "occupant_undeclared" +OCCUPANT_UNKNOWN = "occupant_unknown" +OWNER_MISMATCH = "owner_mismatch" +OWNER_NOT_FOUND = "owner_not_found" +NO_ACCEPTABLE_SITE = "no_acceptable_site" +#: 接受的库位都被占着 / 已被预留时 attempt 排队的原因码(``resource_wait_policy`` 的临时条件) +WAIT_SITE_SELECTION = "site_group_unavailable" +#: 入口预留的有效期:覆盖任务从准入到用到库位的时间;任务结束时由调度器收尾 +RESERVATION_TTL_SECONDS = 7 * 24 * 3600 + + +class SiteSelectionError(ValueError): + """按所属物料选不出库位(预检错误):``reason`` 见模块常量,``details`` 带参数、节点与所属物料。""" + + def __init__(self, reason: str, message: str, *, parameter: str, owner_uuid: str, + node_uuid: Optional[str] = None) -> None: + super().__init__(message) + self.reason = reason + self.message = message + self.details: dict[str, Any] = {"reason": reason, "parameter": parameter, "owner_uuid": owner_uuid} + if node_uuid is not None: + self.details["node_uuid"] = node_uuid + + +@dataclass(frozen=True) +class SiteSelectionRequest: + """一次库位选择:同一个工作流入口参数在多个节点里用到时只选一次。""" + + key: str + owner_uuid: str + occupant_uuid: str + parameter: str + node_uuid: str + targets: tuple[tuple[str, str], ...] + input_name: Optional[str] = None + + def record(self) -> dict[str, Any]: + return { + "key": self.key, + "owner_uuid": self.owner_uuid, + "occupant_uuid": self.occupant_uuid, + "targets": [{"node_uuid": node, "parameter": name} for node, name in self.targets], + **({"input": self.input_name} if self.input_name else {}), + } + + +def _site_fields(node: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]: + schema = node.get("param_schema") + goal = ((schema or {}).get("properties") or {}).get("goal") if isinstance(schema, Mapping) else None + fields = (goal or {}).get("properties") or {} + return {name: field for name, field in fields.items() if isinstance(field, Mapping)} + + +def _upstream_parameters(plan: Mapping[str, Any], node_uuid: str) -> set[str]: + return { + str(edge.get("target_data_key") or "").split("@@@")[-1] + for edge in plan.get("edges") or [] + if edge.get("target_node_uuid") == node_uuid and not edge.get("dependency_only") + } + + +def _material_uuid(value: Any) -> Optional[str]: + from unilabos.server.scheduler.materials import extract_material_uuids + + if not isinstance(value, Mapping) or value.get("kind") in {"workflow_input", "node_output"}: + return None + found = extract_material_uuids(value) + return next(iter(found)) if len(found) == 1 else None + + +def has_owner_selections(plan: Optional[Mapping[str, Any]]) -> bool: + """计划里有按所属物料选择的库位参数(未冻结的 ``{"owner_uuid"}``,或已冻结的选择记录)。""" + + if not plan: + return False + if plan.get("site_selections"): + return True + return any( + owner_reference(value) is not None + for node in plan.get("nodes") or [] for value in (node.get("param") or {}).values() + ) + + +def owner_site_requests(plan: Mapping[str, Any]) -> list[SiteSelectionRequest]: + """计划里还没选定的库位参数(``{"owner_uuid"}``)→ 选择请求,按拓扑序;写法不对抛 :class:`SiteSelectionError`。""" + + grouped: dict[str, dict[str, Any]] = {} + for node in plan.get("nodes") or []: + node_uuid = str(node["uuid"]) + param = node.get("param") or {} + fields = _site_fields(node) + entry_bindings = node.get("entry_bindings") or {} + for name, value in param.items(): + owner = owner_reference(value) + if owner is None: + continue + where = f"库位参数 {name}(节点 {node_uuid})" + 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 声明这个库位参数的关系," + "选不出接受放入物料的库位;请给库位 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(放进去的物料)," + "无法按库位的接收规则挑选", 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)) + if occupant is None: + raise SiteSelectionError( + OCCUPANT_UNKNOWN, f"{where} 按所属物料 {owner} 选库位:放入物料参数 {occupant_param} 在建任务时还不确定" + "(来自上游结果或没有给),请直接给物料或按库位绑定", parameter=name, owner_uuid=owner, node_uuid=node_uuid) + owner_param = str(selector.get("owner") or "") + declared_owner = None if owner_param in upstream else _material_uuid(param.get(owner_param)) + if declared_owner is not None and declared_owner != owner: + raise SiteSelectionError( + OWNER_MISMATCH, f"{where} 按所属物料 {owner} 选库位:与库位所属物料参数 {owner_param}({declared_owner})不一致", + parameter=name, owner_uuid=owner, node_uuid=node_uuid) + input_name = entry_bindings.get(name) if isinstance(entry_bindings, Mapping) else None + key = f"input:{input_name}" if input_name else f"node:{node_uuid}/{name}" + entry = grouped.setdefault(key, { + "owner_uuid": owner, "occupant_uuid": occupant, "parameter": name, "node_uuid": node_uuid, + "targets": [], "input_name": input_name, + }) + entry["targets"].append((node_uuid, name)) + return [ + SiteSelectionRequest(key=key, owner_uuid=entry["owner_uuid"], occupant_uuid=entry["occupant_uuid"], + parameter=entry["parameter"], node_uuid=entry["node_uuid"], + targets=tuple(entry["targets"]), input_name=entry["input_name"]) + for key, entry in grouped.items() + ] + + +def read_owner_facts(materials: Any, requests: Iterable[SiteSelectionRequest]) -> list[dict[str, Any]]: + """向物料权威读一次每个请求的候选库位(只读)。""" + + requests = list(requests) + if not requests: + return [] + reader = getattr(materials, "site_admission_facts", None) + if not callable(reader): + raise RuntimeError("物料权威尚未接入,不能按所属物料选择库位") + facts = reader({"owners": [ + {"owner_material_uuid": request.owner_uuid, "occupant_material_uuid": request.occupant_uuid} + for request in requests]}) + return list((facts or {}).get("owners") or []) + + +def check_owner_sites( + requests: Iterable[SiteSelectionRequest], facts: Iterable[Mapping[str, Any]], +) -> list[dict[str, Any]]: + """所属物料存在、放入物料存在、至少有一个接受它的库位;返回每个请求的 ``{acceptable, available}``。""" + + results: list[dict[str, Any]] = [] + for request, fact in zip(requests, facts): + where = f"库位参数 {request.parameter}(节点 {request.node_uuid})" + if not fact.get("owner_exists"): + raise SiteSelectionError(OWNER_NOT_FOUND, f"{where} 按所属物料选库位:物料 {request.owner_uuid} 不存在", + parameter=request.parameter, owner_uuid=request.owner_uuid, node_uuid=request.node_uuid) + occupant = fact.get("occupant") + if not occupant: + raise SiteSelectionError( + OCCUPANT_UNKNOWN, f"{where} 按所属物料 {request.owner_uuid} 选库位:放入物料 {request.occupant_uuid} 不存在", + parameter=request.parameter, owner_uuid=request.owner_uuid, node_uuid=request.node_uuid) + acceptable = list(fact.get("acceptable") or []) + if not acceptable: + raise SiteSelectionError( + NO_ACCEPTABLE_SITE, + f"{where} 按所属物料 {request.owner_uuid} 选库位:它下面没有接受 {occupant.get('template_name')} 的库位" + "(库位的模板白名单或允许的资源类别不含它)", + parameter=request.parameter, owner_uuid=request.owner_uuid, node_uuid=request.node_uuid) + results.append({"key": request.key, "acceptable": acceptable, "available": list(fact.get("available") or [])}) + return results + + +def reservation_payload(task_uuid: str, request: SiteSelectionRequest) -> dict[str, Any]: + """入口预留请求:所属物料下接受放入物料的库位里预留一个;幂等键按任务与选择,重放得到同一个预留。""" + + return { + "idempotency_key": f"workflow-site-selection:{task_uuid}:{request.key}", + "carrier_material_uuid": request.occupant_uuid, + "owner_material_uuid": request.owner_uuid, + "ttl_seconds": RESERVATION_TTL_SECONDS, + "backend_task_uuid": task_uuid, + "invocation_key": request.key, + } + + +def freeze_site_selections( + plan: dict[str, Any], input_value: dict[str, Any], selections: Iterable[Mapping[str, Any]], +) -> set[str]: + """就地把选中的库位 uuid 写进计划节点参数(含 ``entry_param_template`` 里的静态值)与任务输入, + 选择记录追加到计划的 ``site_selections``;返回改动的节点 uuid。""" + + nodes = {str(node["uuid"]): node for node in plan.get("nodes") or []} + touched: set[str] = set() + records = list(plan.get("site_selections") or []) + for selection in selections: + site_uuid = str(selection["site_uuid"]) + for target in selection.get("targets") or []: + node = nodes.get(str(target["node_uuid"])) + if node is None: + continue + name = str(target["parameter"]) + node.setdefault("param", {})[name] = site_uuid + template = node.get("entry_param_template") + if isinstance(template, dict) and owner_reference(template.get(name)) is not None: + template[name] = site_uuid + touched.add(str(node["uuid"])) + if selection.get("input") and owner_reference(input_value.get(selection["input"])) is not None: + input_value[selection["input"]] = site_uuid + records.append(dict(selection)) + plan["site_selections"] = records + return touched + + +def node_reservations(plan: Optional[Mapping[str, Any]], node_uuid: str) -> list[str]: + """用到某节点的选择对应的入口预留 uuid。""" + + return [ + str(selection["reservation_uuid"]) + for selection in (plan or {}).get("site_selections") or [] + if selection.get("reservation_uuid") + and any(str(target.get("node_uuid")) == node_uuid for target in selection.get("targets") or []) + ] + + +__all__ = [ + "NO_ACCEPTABLE_SITE", + "NO_SITE_RELATION", + "OCCUPANT_UNDECLARED", + "OCCUPANT_UNKNOWN", + "OWNER_MISMATCH", + "OWNER_NOT_FOUND", + "RESERVATION_TTL_SECONDS", + "SiteSelectionError", + "SiteSelectionRequest", + "WAIT_SITE_SELECTION", + "check_owner_sites", + "freeze_site_selections", + "has_owner_selections", + "node_reservations", + "owner_site_requests", + "read_owner_facts", + "reservation_payload", +] diff --git a/unilabos/server/services/runtime/workflow/store.py b/unilabos/server/services/runtime/workflow/store.py index a55c14627..b4cf5039b 100644 --- a/unilabos/server/services/runtime/workflow/store.py +++ b/unilabos/server/services/runtime/workflow/store.py @@ -1667,6 +1667,44 @@ def edit_task_input( data={"workflow_task_uuid": task_uuid}, now=now) return self.get_task(task_uuid) + def freeze_task_site_selections(self, task_uuid: str, selections: List[Dict[str, Any]]) -> Dict[str, Any]: + """任务准入时按所属物料选定的库位冻结进任务(``site_selections.py``)。 + + 一个事务里改计划节点参数(含 ``entry_param_template`` 的静态值)、对应节点运行与其 pending attempt 的参数、 + 任务输入,并在计划里记下选择(``site_selections``)。只在任务还没开始(``pending``)时写。 + """ + + from .site_selections import freeze_site_selections + + now = utc_now() + with self.transaction() as conn: + task = self.get_task(task_uuid) + if task["status"] != "pending": + raise StoreConflict("只有尚未开始的任务能冻结库位选择") + plan = task["execution_plan"] + input_value = dict(task["input"]) + touched = freeze_site_selections(plan, input_value, selections) + params = {str(node["uuid"]): node.get("param") or {} for node in plan.get("nodes") or []} + for row in conn.execute( + "SELECT uuid, workflow_node_uuid FROM workflow_node_run WHERE workflow_task_uuid=? AND deleted_at IS NULL", + (task_uuid,), + ).fetchall(): + if row["workflow_node_uuid"] not in touched: + continue + param = _json(params[row["workflow_node_uuid"]]) + conn.execute("UPDATE workflow_node_run SET param=?, update_time=? WHERE uuid=?", (param, now, row["uuid"])) + conn.execute( + "UPDATE workflow_node_job SET param=?, update_time=? WHERE workflow_node_run_uuid=? " + "AND deleted_at IS NULL AND status='pending'", + (param, now, row["uuid"]), + ) + conn.execute( + "UPDATE workflow_task SET input=?, execution_plan=?, update_time=? WHERE uuid=?", + (_json(input_value), _json(plan), now, task_uuid), + ) + self._append_event(conn, event="workflow.task.changed", data={"workflow_task_uuid": task_uuid}, now=now) + return self.get_task(task_uuid) + def mark_job_cancel_requested(self, job_uuid: str) -> bool: """已下发的 attempt 收到取消请求:展示为 cancel_requested,直到真实终态回报。""" diff --git a/unilabos/server/services/runtime/workflow/value_schema.py b/unilabos/server/services/runtime/workflow/value_schema.py index db65ebda2..d1604b7ee 100644 --- a/unilabos/server/services/runtime/workflow/value_schema.py +++ b/unilabos/server/services/runtime/workflow/value_schema.py @@ -12,7 +12,7 @@ from typing import Any from unilabos.server.services.runtime.workflow.handle_projection import resource_slot_schema -from unilabos.protocol.runtime.site_references import SITE_UUID_KEY, site_reference +from unilabos.protocol.runtime.site_references import OWNER_UUID_KEY, SITE_UUID_KEY, owner_reference, site_reference from unilabos.protocol.runtime.workflow import validate_uuid @@ -163,6 +163,13 @@ def validate_value( raise WorkflowValueSchemaError("workflow_value_invalid", path) return value.strip() if normalized.get("$slot") == "SiteSlot": + owner = owner_reference(value) + if owner is not None: + # 按所属物料选择:任务准入时调度器选一个接受放入物料的空库位并冻结 + try: + return {OWNER_UUID_KEY: validate_uuid(owner)} + except (TypeError, ValueError): + raise WorkflowValueSchemaError("workflow_value_invalid", path) from None if not isinstance(value, str): raise WorkflowValueSchemaError("workflow_value_invalid", path) try: From bfb52bfed0aa4961db7f027006edb23c86aaf63e Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:05:37 +0800 Subject: [PATCH 55/59] fix(hostlink): a ROS 2 Slave answers material.sync while its devices run post_init A device that calls materials.assign from its post_init makes the authority commit the move and then ask the device to unload / load through the Host relay and HostLink material.sync. The ROS 2 Slave registered its downlink handlers (material.sync, resource tree sync, resource append, device manage) only after every device had been initialized, so that callback came back as "unknown action: material.sync" and the assign failed with 503 while the move stayed committed. setup_slave_network_client now registers the downlink handlers when it creates the Slave's HostLink client, before the link connects and before any device exists; main_slave_run no longer registers them after device init. The handlers look the device node up per request: a ROS device node is in registered_devices before its driver's post_init runs, so a device still in post_init is found, and a device that does not exist yet gets a clear error. Incoming requests run on the client's RPC worker pool and the projection runs on the node's executor, so an assign blocking in post_init does not wait on itself, also when source and target are the calling device. The HostLink Slave already registered its handlers in _start_slave before assembling devices, and its nodes are in the local runtime before post_init; a test now covers an assign from post_init there as well. --- .../host/hostlink/test_backend_service.py | 34 +++ .../host/hostlink/test_slave_startup_order.py | 95 +++++++++ .../host/ros2/test_slave_post_init_assign.py | 196 ++++++++++++++++++ unilabos/client/host/hostlink/network.py | 6 + unilabos/client/host/ros2/main_slave_run.py | 14 +- 5 files changed, 336 insertions(+), 9 deletions(-) create mode 100644 tests/client/host/ros2/test_slave_post_init_assign.py diff --git a/tests/client/host/hostlink/test_backend_service.py b/tests/client/host/hostlink/test_backend_service.py index a3ae1d309..c6340e5e2 100644 --- a/tests/client/host/hostlink/test_backend_service.py +++ b/tests/client/host/hostlink/test_backend_service.py @@ -259,6 +259,40 @@ def test_ros_slave_devices_are_announced_ready_only_after_they_are_built(monkeyp assert {key: value["ready"] for key, value in peer["devices"].items()} == {"pump-a": True, "sensor-b": False} +def test_ros_slave_link_answers_material_downlink_before_any_device_is_built(monkeypatch) -> None: + """ROS 2 Slave 的链路一建好就承接物料 / 设备管理下行,先于任何设备节点。 + + 设备 post_init 里的 materials.assign 会让权威经 HostLink 回调本进程的 material.sync, + 那时设备还在初始化;Slave 必须认得这个动作,而不是回 ``unknown action``。 + """ + + service = setup_host_network_service() + assert service is not None + HostLinkConfig.host = "127.0.0.1" + HostLinkConfig.port = service.server.port + monkeypatch.setattr(BasicConfig, "machine_name", "edge-slave-downlink") + + client, _ = setup_slave_network_client(device_ids=["bench"]) + assert client is not None and client.online + for action in ( + ActionType.MATERIAL_SYNC, + ActionType.RESOURCE_TREE_SYNC, + ActionType.RESOURCE_APPEND, + ActionType.DEVICE_MANAGE, + ): + assert action in client.handlers, action + + # 设备节点还没建:Slave 认得 material.sync,只是本进程还没有这台设备 + with pytest.raises(Exception) as raised: + service.server.request_device( + "bench", + ActionType.MATERIAL_SYNC, + {"device_id": "bench", "action": "unload", "material_uuids": []}, + 2.0, + ) + assert "unknown action" not in str(raised.value) + + def test_slave_material_create_is_proxied_by_host_authority( tmp_path, monkeypatch ) -> None: diff --git a/tests/client/host/hostlink/test_slave_startup_order.py b/tests/client/host/hostlink/test_slave_startup_order.py index e01b38f0d..73a3e68d0 100644 --- a/tests/client/host/hostlink/test_slave_startup_order.py +++ b/tests/client/host/hostlink/test_slave_startup_order.py @@ -161,3 +161,98 @@ def test_slave_connects_then_aligns_then_assembles_devices_from_authority( host.stop() set_materials_gateway(None) service.close() + + +class _AssigningBench: + """post_init 里把台面挂到自身,再把自己持有的板换到台面库位(来源与目标都是自己)。""" + + deck_uuid = "" + + def __init__(self, **_kwargs: Any) -> None: + self.deck: Any = None + self.placed: Any = None + + def post_init(self, node: Any) -> None: + from tests.plr_fixtures import plate + from unilabos.resources import materials + + [self.deck] = materials.assign(node, self.deck_uuid)["resources"] + held = materials.create(plate("bench_plate"), node=node) + [self.placed] = materials.assign(node, held, parent=self.deck_uuid, slot="T1")["resources"] + + +def _resolve_bench(device_id: str, device_config: ResourceDictInstance, *, backend_name=None): + assert backend_name == "hostlink" + apply_device_authority_state(device_config, {"available_sites": []}, REGISTRY_NAME) + return SimpleNamespace( + driver_class=_AssigningBench, + runtime_config={}, + registry_name=REGISTRY_NAME, + display_name=device_id, + action_value_mappings={}, + status_types={}, + hardware_interface={}, + resource_uuid=device_config.res_content.uuid, + ) + + +def test_a_device_assigns_from_its_post_init_on_a_hostlink_slave(tmp_path, monkeypatch) -> None: + """设备在 post_init 里 materials.assign:权威经 HostLink 回调这台还在初始化的设备做 unload / load。 + + Slave 的物料下行 handler 在装配设备之前就挂上,设备节点在 post_init 之前已在本地运行时里; + assign 阻塞在设备自己的 post_init 里也不会等到自己。 + """ + + from tests.plr_fixtures import site_deck + from unilabos.resources import materials + + service = MaterialsService(tmp_path / "host-materials.db") + gateway = LocalMaterialsClient(service) + set_materials_gateway(gateway) + monkeypatch.setattr(HostLinkConfig, "enable", True) + monkeypatch.setattr(HostLinkConfig, "bind", "127.0.0.1") + monkeypatch.setattr(HostLinkConfig, "port", 0) + monkeypatch.setattr(HostLinkConfig, "host", "") + monkeypatch.setattr(HostLinkConfig, "heartbeat_interval", 60.0) + monkeypatch.setattr(HostLinkConfig, "heartbeat_timeout", 120.0) + monkeypatch.setattr(HostLinkConfig, "connect_timeout", 2.0) + monkeypatch.setattr(HostLinkConfig, "request_timeout", 15.0) + monkeypatch.setattr(BasicConfig, "is_host_mode", True) + monkeypatch.setattr(BasicConfig, "slave_no_host", False) + monkeypatch.setattr(BasicConfig, "machine_name", "slave-post-init-assign") + monkeypatch.setattr(main_hostlink_run, "resolve_device_definition", _resolve_bench) + monkeypatch.setattr(device_site, "registry_device_site_templates", lambda: {REGISTRY_NAME: []}) + deck_uuid = str(uuid4()) + materials.ensure(site_deck(deck_uuid, "Bench_Deck", ("T1", "T2")), gateway=gateway) + _AssigningBench.deck_uuid = deck_uuid + + host = HostLinkBackend(HostLinkLocalRuntime(), is_slave=False) + slave = None + try: + host.start() + assert host.server is not None + HostLinkConfig.host = "127.0.0.1" + HostLinkConfig.port = host.server.port + BasicConfig.is_host_mode = False + + device_uuid = str(uuid4()) + graph = _slave_graph(device_uuid, str(uuid4())) + graph.root_nodes[0].children.clear() + slave = HostLinkBackend(HostLinkLocalRuntime(), is_slave=True) + slave.start(populate=main_hostlink_run.startup_populate(graph, graph, is_slave=True)) + + node = slave.local.devices["slave-heater"] + driver = node.driver + tracker = node.resource_tracker + assert tracker.uuid_to_resources[deck_uuid] is driver.deck + assert driver.placed.parent is driver.deck + assert service.get_material(deck_uuid).material.parent_material_uuid == device_uuid + t1 = next(site for site in service.get_material(deck_uuid).sites if site.label == "T1") + assert t1.occupied_material_uuid == driver.placed.unilabos_uuid + assert [res.name for res in tracker.resources] == ["Bench_Deck"] + finally: + if slave is not None: + slave.stop() + host.stop() + set_materials_gateway(None) + service.close() diff --git a/tests/client/host/ros2/test_slave_post_init_assign.py b/tests/client/host/ros2/test_slave_post_init_assign.py new file mode 100644 index 000000000..4dca25d39 --- /dev/null +++ b/tests/client/host/ros2/test_slave_post_init_assign.py @@ -0,0 +1,196 @@ +"""ROS 2 Slave:设备在 post_init 里 materials.assign,权威经 HostLink 回调本进程的 material.sync。 + +按 ``main_slave_run.slave()`` 的真实启动顺序跑(不初始化 rclpy):Host 侧是真实的 HostLink +组网服务与物料权威,Slave 侧是 ``setup_slave_network_client`` 建的真实链路。ROS 设备节点建不起来 +(没有 rclpy 上下文),换成同一 DeviceNode 契约的替身节点,并像 ``BaseROS2DeviceNode.__init__`` +那样先登记进 ``registered_devices`` 再跑驱动的 post_init。 + +覆盖:设备还在 post_init 时 Slave 已能应答 material.sync、按 device_id 找得到这台设备; +assign 同步阻塞在设备自己的 post_init 里时不会等到自己;来源与目标都是调用方设备。 +""" + +from __future__ import annotations + +from typing import Any +from uuid import uuid4 + +import pytest + +from tests.plr_fixtures import plate, site_deck +from unilabos.client.host.hostlink.client import get_hostlink_client +from unilabos.client.host.hostlink.local_runtime import HostLinkDriverSpec, HostLinkLocalRuntime +from unilabos.client.host.hostlink.network import ( + setup_host_network_service, + setup_slave_network_client, + shutdown_network_services, +) +from unilabos.client.host.hostlink.protocol import ActionType +from unilabos.client.host.ros2 import main_slave_run +from unilabos.client.host.ros2.base_device_node import registered_devices +from unilabos.client.host.runtime.resource import AuthorityResourceService +from unilabos.client.materials import HostLinkMaterialsClient, LocalMaterialsClient +from unilabos.config.config import BasicConfig, HostLinkConfig +from unilabos.resources import materials +from unilabos.resources.adapters.device_site import apply_device_authority_state +from unilabos.resources.resource_tracker import ( + ResourceDict, + ResourceDictInstance, + ResourceTreeInstance, + ResourceTreeSet, +) +from unilabos.server.services.materials import MaterialsService + +DEVICE_ID = "bench" +TEMPLATE = "post_init_assign_bench" + + +class _Bench: + """post_init 里把台面挂到自身,再把自己持有的板换到台面库位上(来源与目标都是自己)。""" + + deck_uuid = "" + + def __init__(self, **_kwargs: Any) -> None: + self.deck: Any = None + self.placed: Any = None + + def post_init(self, node: Any) -> None: + # 台面在权威里不属于任何设备:来源设备按本设备算 + [self.deck] = materials.assign(node, self.deck_uuid)["resources"] + # 本设备持有的板:同一台设备先 unload 再 load + held = materials.create(plate("bench_plate"), node=node) + [self.placed] = materials.assign(node, held, parent=self.deck_uuid, slot="T1")["resources"] + + +class _Executor: + def add_node(self, _node: Any) -> None: + pass + + def spin(self) -> None: + pass + + +def _graph(device_uuid: str) -> ResourceTreeSet: + device = ResourceDictInstance( + ResourceDict.model_validate( + { + "id": DEVICE_ID, + "uuid": device_uuid, + "name": DEVICE_ID, + "type": "device", + "class": TEMPLATE, + "template_name": TEMPLATE, + "config": {}, + "data": {}, + "extra": {}, + } + ) + ) + return ResourceTreeSet([ResourceTreeInstance(device)]) + + +@pytest.fixture +def network(monkeypatch): + shutdown_network_services() + monkeypatch.setattr(HostLinkConfig, "enable", True) + monkeypatch.setattr(HostLinkConfig, "bind", "127.0.0.1") + monkeypatch.setattr(HostLinkConfig, "port", 0) + monkeypatch.setattr(HostLinkConfig, "host", "") + monkeypatch.setattr(HostLinkConfig, "advertise_ip", "127.0.0.1") + monkeypatch.setattr(HostLinkConfig, "heartbeat_interval", 0.2) + monkeypatch.setattr(HostLinkConfig, "heartbeat_timeout", 5.0) + monkeypatch.setattr(HostLinkConfig, "connect_timeout", 2.0) + monkeypatch.setattr(HostLinkConfig, "request_timeout", 15.0) + monkeypatch.setattr(HostLinkConfig, "ros_assist_apply", False) + monkeypatch.setattr(HostLinkConfig, "ros_discovery_server", "off") + monkeypatch.setattr(HostLinkConfig, "ros_discovery_port", 0) + monkeypatch.setattr(BasicConfig, "backend", "ros2") + monkeypatch.setattr(BasicConfig, "machine_name", "post-init-slave") + monkeypatch.setattr(BasicConfig, "is_host_mode", True) + monkeypatch.setattr(BasicConfig, "slave_no_host", False) + for key in ("ROS_DOMAIN_ID", "ROS_AUTOMATIC_DISCOVERY_RANGE", "ROS_STATIC_PEERS", "ROS_DISCOVERY_SERVER"): + monkeypatch.delenv(key, raising=False) + yield + shutdown_network_services() + + +def test_a_device_assigns_from_its_post_init_on_a_ros2_slave(tmp_path, monkeypatch, network) -> None: + material_service = MaterialsService(tmp_path / "materials.db") + gateway = LocalMaterialsClient(material_service) + host = setup_host_network_service(material_gateway=gateway) + assert host is not None + # Host 与 Slave 同在测试进程:Host 侧对 Slave 设备按跨机经 HostLink 下发 + # (material_sync_to_device 的跨机分支),不在本进程直调 Slave 的设备节点 + material_service.set_resource_sync_dispatcher( + lambda command: host.server.request_device( + command.device_id, + ActionType.MATERIAL_SYNC, + command.model_dump(mode="json", exclude_none=False), + 15.0, + ) + ) + device_uuid, deck_uuid = str(uuid4()), str(uuid4()) + graph = _graph(device_uuid) + apply_device_authority_state(graph.root_nodes[0], {"available_sites": []}, TEMPLATE, gateway=gateway) + # 台面先在权威里(不属于任何设备),本地还没有它 + materials.ensure(site_deck(deck_uuid, "Bench_Deck", ("T1", "T2")), gateway=gateway) + _Bench.deck_uuid = deck_uuid + + # 与 app/main.py 一致:rclpy 之前先接入 HostLink(Slave 进程身份) + HostLinkConfig.host = "127.0.0.1" + HostLinkConfig.port = host.server.port + BasicConfig.is_host_mode = False + client, _ = setup_slave_network_client(device_ids=[DEVICE_ID]) + assert client is not None and client.online + # 跳过经 ROS service 报送节点信息(第 3 步),其余按 slave() 原样执行 + monkeypatch.setattr(BasicConfig, "slave_no_host", True) + + runtimes: list[HostLinkLocalRuntime] = [] + errors: list[BaseException] = [] + events: list[str] = [] + + def initialize(device_id: str, device_config: Any) -> Any: + runtime = HostLinkLocalRuntime() + runtimes.append(runtime) + node = runtime.add_driver( + HostLinkDriverSpec(device_id, _Bench, {}, resource_uuid=device_config.res_content.uuid) + ) + runtime.set_resource_service(AuthorityResourceService(HostLinkMaterialsClient(get_hostlink_client()))) + # 与 BaseROS2DeviceNode.__init__ 一致:节点先登记进 registered_devices,之后才跑驱动的 post_init + monkeypatch.setitem(registered_devices, device_id, {"base_node_instance": node}) + events.append("post_init") + try: + runtime.start() + except Exception as exc: # noqa: BLE001 - 与 ROS2DeviceNode 一样:post_init 失败只记下,设备照常算初始化过 + errors.append(exc) + return node + + monkeypatch.setattr(main_slave_run, "_init_rclpy", lambda *_args: None) + monkeypatch.setattr(main_slave_run.rclpy, "__executor", _Executor(), raising=False) + monkeypatch.setattr(main_slave_run, "_spin_forever", lambda _executor: None) + monkeypatch.setattr(main_slave_run, "Node", lambda *_args, **_kwargs: object()) + monkeypatch.setattr(main_slave_run, "initialize_device_from_dict", initialize) + monkeypatch.setattr(main_slave_run, "spin_until_shutdown", lambda: events.append("spin")) + monkeypatch.setattr(main_slave_run, "shutdown_ros_runtime", lambda *_args, **_kwargs: None) + + try: + main_slave_run.slave(graph, graph) + + assert events == ["post_init", "spin"] + assert errors == [] + [runtime] = runtimes + node = runtime.devices[DEVICE_ID] + driver = node.driver + tracker = node.resource_tracker + # 台面按权威重建挂到设备自身,板从设备自身换到了台面 T1 + assert tracker.uuid_to_resources[deck_uuid] is driver.deck + assert driver.placed.parent is driver.deck + assert material_service.get_material(deck_uuid).material.parent_material_uuid == device_uuid + t1 = next(site for site in material_service.get_material(deck_uuid).sites if site.label == "T1") + assert t1.occupied_material_uuid == driver.placed.unilabos_uuid + assert [res.name for res in tracker.resources] == ["Bench_Deck"] + # 设备建好之后才对 Host 报就绪 + assert host.server.peers()[0]["devices"][DEVICE_ID]["ready"] is True + finally: + for runtime in runtimes: + runtime.stop() + material_service.close() diff --git a/unilabos/client/host/hostlink/network.py b/unilabos/client/host/hostlink/network.py index 970b0c577..a3ee8decd 100644 --- a/unilabos/client/host/hostlink/network.py +++ b/unilabos/client/host/hostlink/network.py @@ -649,6 +649,12 @@ def setup_slave_network_client( # HostLink 时 Action server 还不存在,这时发出的 goal 没有接收方,会丢。 client.configure_device_descriptors({"id": device_id, "ready": False} for device_id in client.device_ids) client.heartbeat_payload_provider = _descriptor_heartbeat(client) + # 物料 / 设备管理下行 handler 随链路一起挂上,先于任何设备节点:设备在 post_init 里调 + # materials.assign / transfer 时,权威会经 HostLink 回调本进程的 material.sync(unload / load), + # 那时设备还没初始化完。handler 收到请求时才按 device_id 找设备节点,找不到时回明确的错误。 + from unilabos.client.host.hostlink.downlink import register_hostlink_resource_handlers + + register_hostlink_resource_handlers(client) # 协议编译用 Host 的完整物理拓扑图:ROS 2 Slave 同样经 HostLink 取,不经 DDS physical_graph = _slave_physical_graph = attach_physical_graph_sync(client) set_hostlink_client(client) diff --git a/unilabos/client/host/ros2/main_slave_run.py b/unilabos/client/host/ros2/main_slave_run.py index f1a96adfc..0951ddf14 100644 --- a/unilabos/client/host/ros2/main_slave_run.py +++ b/unilabos/client/host/ros2/main_slave_run.py @@ -324,7 +324,10 @@ def slave( else: logger.info("No resources to add.") - # 4. 初始化所有设备实例(resources_config 的 uuid 与权威一致) + # 4. 初始化所有设备实例(resources_config 的 uuid 与权威一致)。 + # 物料下行(material.sync / 资源树同步 / 物料挂载 / 设备管理)走 HostLink,不建 ROS service; + # handler 在 setup_slave_network_client 建链时就已挂上:设备 post_init 里的 materials.assign + # 会让权威回调本进程的 material.sync,设备节点在 post_init 之前已登记进 registered_devices。 devices_instances = {} for device_config in devices_config.root_nodes: device_id = device_config.res_content.id @@ -336,15 +339,8 @@ def slave( else: logger.warning(f"Device {device_id} initialization failed.") - # 4.5 物料下行链路(append_resource / 资源树同步)走 HostLink,不建 ROS service: - # 把下行 handler 挂到 HostLink client,Host 的分发经此调用本进程设备节点实例。 if _hostlink_client is not None: - from unilabos.client.host.hostlink.downlink import register_hostlink_resource_handlers - - register_hostlink_resource_handlers(_hostlink_client) - logger.info("HostLink 物料下行 handler 已注册(资源树同步 / 物料挂载)。") - - # 4.6 设备节点(含 Action server)已建好:告诉 Host 它们就绪。Host 只把就绪的设备当在线, + # 4.5 设备节点(含 Action server)已建好:告诉 Host 它们就绪。Host 只把就绪的设备当在线, # 重启后的 Slave 刚接回 HostLink 时派发的 goal 不会落到还不存在的 Action server 上; # 初始化失败的根设备连同其子设备保持未就绪(离线)。 from unilabos.client.host.hostlink.network import mark_slave_devices_ready, startup_device_ids From bf2381618f6c2e200380bb818eabdbcaa13986be Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:05:47 +0800 Subject: [PATCH 56/59] fix(materials): assign loads a material the authority already has at the destination When the device-side unload or load of an assign fails after the authority committed the move, the caller sees an error while the move stands. Calling assign again then got "material is already at destination" from the authority; unless the node already held the material, assign re-raised it, so the retry could never succeed. A no-change answer now means the authority already has the material where it was asked to be. If the node holds it, assign stays a no-op; if not, assign loads that subtree from the authority through the same material_sync load the transfer uses, on the destination Site, and returns success. Only real errors raise. A multi-material command that the authority rejects as no-change because one material is already in place is retried one material at a time, so the others still move. The authority keeps committing before it projects to devices: it does not probe reachability first (a device can still drop between a probe and the dispatch) and does not roll back. A failed projection converges on retry: replaying the same command replays unload / load, and a new assign loads from the authority as above. The transfer_material docstring and the materials guide say so. --- .../examples/materials_operations_guide.md | 4 + .../test_materials_create_and_place.py | 91 +++++++++++++++++++ unilabos/resources/materials.py | 67 ++++++++++---- unilabos/server/services/materials/core.py | 5 + 4 files changed, 149 insertions(+), 18 deletions(-) diff --git a/docs/developer_guide/examples/materials_operations_guide.md b/docs/developer_guide/examples/materials_operations_guide.md index 50e6b1571..7e4917822 100644 --- a/docs/developer_guide/examples/materials_operations_guide.md +++ b/docs/developer_guide/examples/materials_operations_guide.md @@ -191,6 +191,10 @@ materials.assign(node, deck) materials.assign(node, bottle_carrier, parent=warehouse, slot="A04") ``` +权威答「已在目标位置」时:本设备持有它,`assign` 什么都不做;本设备没有它(例如上一次 `assign` +在权威里已提交,设备侧 unload / load 没做完而报错),`assign` 按同一条 load 从权威重建挂上并成功返回。 +所以一次失败的 `assign` 重试即收敛;其它错误照常抛出。 + **载架型目标(仓库、瓶架等 PLR `Carrier`)**:载架的直接子节点只能是库位 holder (`ResourceHolder`),物料只能经 `assign_resource_to_site` 放到 holder 上。`assign`、 `RESOURCE_APPEND`、资源树下行(`RESOURCE_TREE_SYNC`)和 `transfer` 的 load 都按这条路径放置, diff --git a/tests/resources/test_materials_create_and_place.py b/tests/resources/test_materials_create_and_place.py index 7b1254f44..50962be62 100644 --- a/tests/resources/test_materials_create_and_place.py +++ b/tests/resources/test_materials_create_and_place.py @@ -210,6 +210,97 @@ def test_assign_to_the_device_without_a_site_only_sets_the_parent(device) -> Non ) +def test_assign_loads_a_material_the_authority_already_put_on_this_device(device) -> None: + """权威里它已在目标库位、本设备却没有它:assign 从权威重建挂上并成功,不把「没有变化」当错误。""" + + from unilabos.protocol.materials import MaterialMove + + service, node, gateway = device["service"], device["node"], device["gateway"] + loose = materials.create(plate("committed"), gateway=gateway) + slot_a = _site(service, device["device_uuid"], "slot_a") + # 只改权威、不做设备侧投影(等同一次提交了、material.sync 却没做完的移动) + service.move_material( + _move_mutation(), + MaterialMove(material_uuid=loose.unilabos_uuid, destination_site_uuid=slot_a.site_uuid), + ) + assert loose.unilabos_uuid not in node.resource_tracker.uuid_to_resources + + result = materials.assign(node, loose.unilabos_uuid, slot="slot_a") + + [mounted] = result["resources"] + assert node.resource_tracker.uuid_to_resources[loose.unilabos_uuid] is mounted + assert result["moves"] == [] + assert _site(service, device["device_uuid"], "slot_a").occupied_material_uuid == loose.unilabos_uuid + # 本设备已持有它:再来一次什么都不做,仍是同一份实例 + again = materials.assign(node, loose.unilabos_uuid, slot="slot_a") + assert again["resources"] == [mounted] + + +def test_assign_converges_after_the_device_projection_failed_once(device) -> None: + """权威已提交、设备侧 unload 失败(例如当时还没有 material.sync handler):调用方收到错误, + 再 assign 一次就收敛——权威答「已在目标位置」,本设备从权威加载。来源与目标都是调用方自己。""" + + from tests.plr_fixtures import site_deck + from unilabos.server.services.materials import MaterialTransferSyncError + + service, node, gateway = device["service"], device["node"], device["gateway"] + deck_uuid = str(uuid4()) + materials.ensure(site_deck(deck_uuid, "Bench_Deck", ("T1", "T2")), gateway=gateway) + dispatch = node.__dict__["_hostlink_runtime"].dispatch_material_sync + failures = [] + + def unload_fails_once(command): + if command.action == "unload" and not failures: + failures.append(command) + raise RuntimeError("unknown action: material.sync") + return dispatch(command) + + service.set_resource_sync_dispatcher(unload_fails_once) + + with pytest.raises(MaterialTransferSyncError, match="unload failed"): + materials.assign(node, deck_uuid) + assert failures[0].device_id == "placer" + assert service.get_material(deck_uuid).material.parent_material_uuid == device["device_uuid"] + assert deck_uuid not in node.resource_tracker.uuid_to_resources + + [deck] = materials.assign(node, deck_uuid)["resources"] + + assert node.resource_tracker.uuid_to_resources[deck_uuid] is deck + # 收敛后与权威一致:后续挂到台面库位、严格快照照常进行 + loose = materials.create(plate("after_retry"), gateway=gateway) + [placed] = materials.assign(node, loose, parent=deck_uuid, slot="T1")["resources"] + assert placed.parent is deck + materials.update(node, deck) + + +def test_assign_of_several_materials_moves_the_rest_when_one_is_already_there(device) -> None: + """一条命令里有一个物料已在目标位置时,其余的照常移动,已在的那个不报错。""" + + service, node, gateway = device["service"], device["node"], device["gateway"] + first = materials.create(plate("first_of_two"), gateway=gateway) + second = materials.create(plate("second_of_two"), gateway=gateway) + materials.assign(node, first) + + result = materials.assign(node, [first, second]) + + assert {res.unilabos_uuid for res in result["resources"]} == {first.unilabos_uuid, second.unilabos_uuid} + assert service.get_material(second.unilabos_uuid).material.parent_material_uuid == device["device_uuid"] + assert second.unilabos_uuid in node.resource_tracker.uuid_to_resources + + +def _move_mutation(): + from unilabos.protocol.materials import InventoryMutation + + command_uuid = str(uuid4()) + return InventoryMutation( + command_uuid=command_uuid, + effect_key=f"move_material:{command_uuid}", + operation="move_material", + actor_type="test", + actor_uuid="create-and-place-test", + ) + + def test_assign_rejects_an_unknown_device_site_without_mounting(device) -> None: service, node = device["service"], device["node"] loose = materials.create(plate("stray"), gateway=device["gateway"]) diff --git a/unilabos/resources/materials.py b/unilabos/resources/materials.py index 32ca53359..e9ff9364f 100644 --- a/unilabos/resources/materials.py +++ b/unilabos/resources/materials.py @@ -812,35 +812,50 @@ def _undo_placed_create( logger.error(f"[materials.create] 本地挂载失败后撤销权威里的物料 {root_uuid} 也失败:{exc}") -def _attach_placed( +def _load_on_node( node: Any, - created: CreatedPLRMaterials, - site_uuid: str | None, - command_uuid: str, - timeout: float, -) -> CreatedPLRMaterials: - """权威已在同一事务里建好并落位:本地按 transfer 的 load 投影挂上,返回 tracker 里的实例。 + material_uuids: Sequence[str], + site_uuids: Sequence[str | None], + transfer_uuid: str, + timeout: float = 30.0, +) -> None: + """按 transfer 的 load 投影把权威里的物料子树挂到本设备:在设备自己的执行器上跑,阻塞等它完成。 - 与跨设备转运落到目标设备走同一条投影(``node.material_sync``),本地不另起一条挂载 - 逻辑;投影期间不回写快照。返回值里的实例就是设备 tracker 登记的那一份(uuid → 实例唯一)。 + 与跨设备转运落到目标设备同一条投影(``node.material_sync``),本地不另起一条挂载逻辑; + 投影期间不回写快照。``transfer_uuid`` 是设备侧的幂等键。 """ from unilabos.client.host.runtime.async_utils import run_node_coroutine - root_uuid = str(created.tree.trees[0].root_node.res_content.uuid) run_node_coroutine( node, node.material_sync( { - "transfer_uuid": f"create:{command_uuid}", + "transfer_uuid": transfer_uuid, "device_id": str(node.device_id), "action": "load", - "material_uuids": [root_uuid], - "destination_site_uuids": [site_uuid], + "material_uuids": list(material_uuids), + "destination_site_uuids": list(site_uuids), } ), timeout, ) + + +def _attach_placed( + node: Any, + created: CreatedPLRMaterials, + site_uuid: str | None, + command_uuid: str, + timeout: float, +) -> CreatedPLRMaterials: + """权威已在同一事务里建好并落位:本地按 transfer 的 load 投影挂上,返回 tracker 里的实例。 + + 返回值里的实例就是设备 tracker 登记的那一份(uuid → 实例唯一)。 + """ + + root_uuid = str(created.tree.trees[0].root_node.res_content.uuid) + _load_on_node(node, [root_uuid], [site_uuid], f"create:{command_uuid}", timeout) instance = node.resource_tracker.uuid_to_resources.get(root_uuid) if instance is None: raise RuntimeError(f"物料 {root_uuid} 已在权威创建并落位,但本地挂载后 tracker 里没有它") @@ -1013,6 +1028,10 @@ def assign( 原持有设备按权威的归属推断(最近的设备祖先,或根物料登记的所属设备);不属于任何设备的物料 没有要卸下的地方。返回 ``resources``:本设备 tracker 里重建后的实例(与传入的不是同一个对象)。 阻塞式,不能在本设备的执行器线程里调用(load 要排到那个执行器上)。 + + 权威答「已在目标位置」时它已经在要放的地方:本设备持有它就什么都不做;没有它(上一次移动在 + 权威里提交了、设备侧投影没做完)就按同一条 load 从权威重建挂上并成功返回,所以重试一次失败的 + assign 会收敛。其它错误照常抛出。 """ items = resources if isinstance(resources, (list, tuple)) else [resources] @@ -1046,7 +1065,8 @@ def assign( tracker = node.resource_tracker moves: List[Dict[str, Any]] = [] - for source, group in by_source.items(): + + def move(source: str, group: List[str]) -> None: command_uuid = str(uuid4()) try: result = gw.transfer_material( @@ -1069,11 +1089,22 @@ def assign( ), ) except Exception as exc: - # 已经在目标位置、本设备也持有它:幂等,什么都不做 - if _is_no_change_error(exc) and all(item in tracker.uuid_to_resources for item in group): - continue - raise + if not _is_no_change_error(exc): + raise + if len(group) > 1: + # 一条命令里只要有一个物料已在目标位置,权威就整条答「没有变化」:逐个再移,其余的照常移动 + for item_uuid in group: + move(source, [item_uuid]) + return + if group[0] not in tracker.uuid_to_resources: + # 权威里已在目标位置、本设备却没有它:从权威重建挂上(本设备持有它时什么都不做) + site_uuid = _site_uuid(selector, target_uuid, gw) if selector is not None else None + _load_on_node(node, group, [site_uuid], f"assign:{command_uuid}") + return moves.extend(value.model_dump(mode="json", exclude_none=False) for value in result.data.materials) + + for source, group in by_source.items(): + move(source, group) return { "success": True, "material_uuids": resource_uuids, diff --git a/unilabos/server/services/materials/core.py b/unilabos/server/services/materials/core.py index 977f2d2c3..880cc5afe 100644 --- a/unilabos/server/services/materials/core.py +++ b/unilabos/server/services/materials/core.py @@ -3722,6 +3722,11 @@ def transfer_material( 同一个幂等命令在设备同步阶段失败后可以安全重试:数据库 mutation 会 replay,但 unload/load 仍会使用相同 ``transfer_uuid`` 重放。目标 load 失败时不回滚权威位置,也不会重新挂回来源端,因此不会产生双挂载。 + + 设备投影(来源 unload / 目标 load)在提交之后失败时,权威位置保持已提交,调用方收到 + ``MaterialTransferSyncError``。提交前不探测设备是否可达(探测与下发之间设备照样可能掉线), + 也不做补偿回滚;靠重试收敛:重放同一命令会重放 unload/load;另发一条命令时权威答 + 「已在目标位置」,由目标设备从权威加载(``materials.assign`` 即如此)。 """ if mutation.operation != "transfer_material": From 42899910883993c71bcb8974a6371a59565293b5 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:53:49 +0800 Subject: [PATCH 57/59] test(e2e): pin the materials demo to the commit that declares sample PLR types --- 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 444eb5c5f..7f85e4613 100644 --- a/tests/e2e/readme_demos.py +++ b/tests/e2e/readme_demos.py @@ -216,7 +216,7 @@ def runtime_timeout(self) -> float: url="https://github.com/Xuwznln/LabDeviceMaterialsDemo", # 四条 @workflow 后继续经 API 上传阶段三「出库装板并加液」,验证缺料回滚与补料后出库。 # 默认启动先准备台面,让 API 导入时能把 T1-T4 绑定到已存在的权威 Site。 - ref="99666ad64bd17c6e8ba6865e3176c56af9b1ad11", + ref="5bd0fe3b6717516c0ae709184bc5054b886153bd", package="materials_demo", host_graph="graph/host.json", slave_graph="graph/slave.json", From e885bf328ea10fbc4918f25ef6330c922003d5be Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:18:23 +0800 Subject: [PATCH 58/59] test(workflow): wait for the inventory release after a rejected manual confirmation cancels the task --- tests/server/test_workflow_manual_confirmation.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/server/test_workflow_manual_confirmation.py b/tests/server/test_workflow_manual_confirmation.py index c8658b36d..5af2dea58 100644 --- a/tests/server/test_workflow_manual_confirmation.py +++ b/tests/server/test_workflow_manual_confirmation.py @@ -311,7 +311,8 @@ def test_rejection_cancels_the_task_and_releases_its_inventory(tmp_path) -> None assert settled["status"] == "canceled" and settled["error_info"] == [{"code": "manual_confirmation_rejected"}] runs = {run["workflow_node_uuid"]: run for run in stack.workflow.list_workflow_node_runs(task["uuid"])} assert runs[action["uuid"]]["status"] == "canceled" and executor.dispatched == [] - assert stack.quantities() == (20, 20, 0) + # 任务先落 canceled,库存在同一收尾流程随后释放(与普通取消一致),所以等释放而不是立即断言。 + wait_for(lambda: stack.quantities() == (20, 20, 0)) finally: stack.workflow.set_task_submitter(None) scheduler.stop() From 4dd7bdf51afabb1dfdd589708436216f64d1067f Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:22:05 +0800 Subject: [PATCH 59/59] chore(registry): regenerate liquid_handler schema for the updated class description --- unilabos/registry/devices/liquid_handler.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/unilabos/registry/devices/liquid_handler.yaml b/unilabos/registry/devices/liquid_handler.yaml index 6ee1d61b3..16cd80802 100644 --- a/unilabos/registry/devices/liquid_handler.yaml +++ b/unilabos/registry/devices/liquid_handler.yaml @@ -3913,7 +3913,10 @@ liquid_handler: title: Barcode Symbology type: string class: - description: Resource class name + description: Registry name the resource was initialized from + (registry resource / device id); PLR class name for children + without a registry entry. The PLR class used for deserialization + is config.type title: Class type: string config: