From fac87df9cc403d5807192cf421a4e51adf798187 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:32:20 +0800 Subject: [PATCH 1/3] fix(resources): import the registered PLR modules before a device's config.type check, so a restart does not put devices holding preset carriers into maintenance --- tests/resources/test_plr_registration_hook.py | 27 +++++++++++++++++++ unilabos/resources/resource_tracker.py | 5 ++++ 2 files changed, 32 insertions(+) diff --git a/tests/resources/test_plr_registration_hook.py b/tests/resources/test_plr_registration_hook.py index c10fb299a..bd152c838 100644 --- a/tests/resources/test_plr_registration_hook.py +++ b/tests/resources/test_plr_registration_hook.py @@ -151,6 +151,33 @@ def test_core_preset_classes_deserialize_in_a_fresh_process(tmp_path): assert {"BottleCarrier", "Bottle", "WareHouse", "RegularContainer"} <= classes +def test_class_check_finds_core_presets_before_any_tree_is_rebuilt(): + """Host 重启后先逐台核对设备物料的 config.type(``require_plr_config_type``),再建 PLR 实例。 + + 核对本身也要先导入登记的模块:否则新进程里第一台持有 ``BottleCarrier`` / ``WareHouse`` 的设备 + 在任何 ``to_plr_resources`` 之前被核对,类「不存在」,设备误进维护模式(是否出错取决于设备启动顺序)。 + """ + + import os + import subprocess + + script = ( + "import sys\n" + "from unilabos.resources.resource_tracker import find_plr_resource_class, require_plr_config_type\n" + "assert not [m for m in sys.modules if m.startswith('unilabos.resources.presets')]\n" + "for name in ('BottleCarrier', 'Bottle', 'WareHouse', 'RegularContainer'):\n" + " require_plr_config_type({'type': name}, uuid='u-' + name, template_name='t')\n" + " assert find_plr_resource_class(name).__name__ == name\n" + "print('ok')\n" + ) + env = {**os.environ, "PYTHONPATH": os.pathsep.join(filter(None, [os.getcwd(), os.environ.get("PYTHONPATH")]))} + completed = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, encoding="utf-8", env=env, timeout=300 + ) + assert completed.returncode == 0, completed.stderr[-3000:] + assert completed.stdout.strip().splitlines()[-1] == "ok" + + @pytest.fixture() def registry_pkg(tmp_path, monkeypatch): """注册表里登记了工厂函数、自己不主动登记的驱动包:类只有 import 工厂所在的模块后才可见。""" diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index 639ad375b..f60f379b7 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -96,6 +96,11 @@ def find_plr_resource_class(class_name: str) -> Optional[type]: from pylabrobot.resources import Resource as PLRResource from pylabrobot.utils.object_parsing import find_subclass + from unilabos.resources import plr_additional_res_reg + + # 先导入登记过的模块(内置预设 BottleCarrier / WareHouse 等 + 驱动包登记的): + # 重启后从库里恢复设备物料时,可能还没有任何代码 import 过它们。 + plr_additional_res_reg.register() found = find_subclass(class_name, PLRResource) if found is not None: return found From e1946c7ed79394644f5019a7f931545e99f70c66 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:34:31 +0800 Subject: [PATCH 2/3] fix(results): return a PLR material in an action result as its {"uuid"} reference --- tests/test_action_policy.py | 18 ++++++++++++++++++ unilabos/utils/serialization.py | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/tests/test_action_policy.py b/tests/test_action_policy.py index fbf95889c..8186bb7c8 100644 --- a/tests/test_action_policy.py +++ b/tests/test_action_policy.py @@ -212,6 +212,24 @@ def test_result_info_distinguishes_three_success_types(suc_type, return_value): assert serialized["return_value"] == return_value +def test_plr_material_in_result_is_returned_as_its_uuid_reference(): + """驱动直接返回 PLR 实例(单个、嵌在 dict / list 里)时,结果里是 ``{"uuid"}``,不是整个对象。""" + + from pylabrobot.resources import Resource + + beaker = Resource("beaker", size_x=10, size_y=10, size_z=10) + beaker.unilabos_uuid = "b-uuid" + plain = Resource("plain", size_x=1, size_y=1, size_z=1) + + result = serialize_result_info("", True, {"beaker": beaker, "all": [beaker], "site": "S061"}) + assert result["return_value"] == {"beaker": {"uuid": "b-uuid"}, "all": [{"uuid": "b-uuid"}], "site": "S061"} + assert serialize_result_info("", True, beaker)["return_value"] == {"uuid": "b-uuid"} + # 没有权威 uuid 的 PLR 对象不当作物料引用 + from unilabos.utils.serialization import _material_reference + + assert _material_reference(plain) is None + + def test_failed_result_does_not_claim_success_type(): result = serialize_result_info("failed", False, None) diff --git a/unilabos/utils/serialization.py b/unilabos/utils/serialization.py index 0ec3cc143..58c6f6953 100644 --- a/unilabos/utils/serialization.py +++ b/unilabos/utils/serialization.py @@ -51,12 +51,31 @@ def represent_ordereddict(dumper, data): NoAliasDumper.add_representer(OrderedDict, represent_ordereddict) +def _material_reference(obj) -> Optional[dict]: + """动作结果里的 PLR 物料实例按物料引用 ``{"uuid"}`` 返回(与 ResourceSlot 的结果形状一致)。 + + 驱动直接返回 PLR 实例时不必自己转换;没有权威 uuid 的 PLR 对象不在此处理。 + """ + + uuid = getattr(obj, "unilabos_uuid", None) + if not uuid: + return None + try: + from pylabrobot.resources import Resource + except ImportError: # pragma: no cover - 核心总带 PLR + return None + return {"uuid": str(uuid)} if isinstance(obj, Resource) else None + + class ResultInfoEncoder(json.JSONEncoder): """专门用于处理任务执行结果信息的JSON编码器""" def default(self, obj): if isinstance(obj, type): return json_default(obj) + reference = _material_reference(obj) + if reference is not None: + return reference try: if hasattr(obj, "__dict__"): From 23dadcf9da3f103da0a636e60b57988859081342 Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:49:39 +0800 Subject: [PATCH 3/3] test(resources): reproduce the restart class check with a factory that imports its carrier lazily --- tests/resources/test_plr_registration_hook.py | 28 +++++++++++++++---- unilabos/resources/resource_tracker.py | 4 +-- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/tests/resources/test_plr_registration_hook.py b/tests/resources/test_plr_registration_hook.py index bd152c838..d8a989149 100644 --- a/tests/resources/test_plr_registration_hook.py +++ b/tests/resources/test_plr_registration_hook.py @@ -151,26 +151,42 @@ def test_core_preset_classes_deserialize_in_a_fresh_process(tmp_path): assert {"BottleCarrier", "Bottle", "WareHouse", "RegularContainer"} <= classes -def test_class_check_finds_core_presets_before_any_tree_is_rebuilt(): - """Host 重启后先逐台核对设备物料的 config.type(``require_plr_config_type``),再建 PLR 实例。 +def test_class_check_finds_core_presets_before_any_tree_is_rebuilt(tmp_path): + """Host 在已有数据库上重启:先逐台核对设备物料的 config.type(``require_plr_config_type``),再建 PLR 实例。 - 核对本身也要先导入登记的模块:否则新进程里第一台持有 ``BottleCarrier`` / ``WareHouse`` 的设备 - 在任何 ``to_plr_resources`` 之前被核对,类「不存在」,设备误进维护模式(是否出错取决于设备启动顺序)。 + 核对找不到类时只会懒加载注册表条目所在的模块。驱动包的工厂函数常在函数体里才 import 它返回的类 + (这里返回核心预设 ``BottleCarrier``),条目模块被导入后类仍不可见,设备误进维护模式。全新数据库不出现, + 因为建图时会调用工厂。核对前要先导入登记的模块(含内置预设),不能指望驱动包在模块顶层 import。 """ import os import subprocess + pkg = tmp_path / "lazy_carrier_pkg" + pkg.mkdir() + (pkg / "__init__.py").write_text("", encoding="utf-8") + (pkg / "warehouses.py").write_text( + "def process_warehouse(name='wh'):\n" + " from unilabos.resources.presets.itemized_carrier import BottleCarrier\n" + " return BottleCarrier(name, size_x=10, size_y=10, size_z=10, sites={})\n", + encoding="utf-8", + ) script = ( "import sys\n" + "from unilabos.registry.registry import lab_registry\n" "from unilabos.resources.resource_tracker import find_plr_resource_class, require_plr_config_type\n" + "lab_registry.resource_type_registry['pkg.process_warehouse'] = " + "{'class': {'module': 'lazy_carrier_pkg.warehouses:process_warehouse', 'type': 'pylabrobot'}}\n" "assert not [m for m in sys.modules if m.startswith('unilabos.resources.presets')]\n" "for name in ('BottleCarrier', 'Bottle', 'WareHouse', 'RegularContainer'):\n" - " require_plr_config_type({'type': name}, uuid='u-' + name, template_name='t')\n" + " require_plr_config_type({'type': name}, uuid='u-' + name, template_name='pkg.process_warehouse')\n" " assert find_plr_resource_class(name).__name__ == name\n" "print('ok')\n" ) - env = {**os.environ, "PYTHONPATH": os.pathsep.join(filter(None, [os.getcwd(), os.environ.get("PYTHONPATH")]))} + env = { + **os.environ, + "PYTHONPATH": os.pathsep.join(filter(None, [str(tmp_path), os.getcwd(), os.environ.get("PYTHONPATH")])), + } completed = subprocess.run( [sys.executable, "-c", script], capture_output=True, text=True, encoding="utf-8", env=env, timeout=300 ) diff --git a/unilabos/resources/resource_tracker.py b/unilabos/resources/resource_tracker.py index f60f379b7..d421fda5f 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -98,8 +98,8 @@ def find_plr_resource_class(class_name: str) -> Optional[type]: from unilabos.resources import plr_additional_res_reg - # 先导入登记过的模块(内置预设 BottleCarrier / WareHouse 等 + 驱动包登记的): - # 重启后从库里恢复设备物料时,可能还没有任何代码 import 过它们。 + # 先导入登记过的模块(内置预设 BottleCarrier / WareHouse 等 + 驱动包登记的):重启后核对设备物料时 + # 还没有建过图;下面的注册表兜底只导入条目所在模块,工厂函数在函数体里才 import 的类仍不可见。 plr_additional_res_reg.register() found = find_subclass(class_name, PLRResource) if found is not None: