Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/developer_guide/add_registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@
| file_path | string | 否 | 文件路径,系统自动设置 |
| registry_type | string | 否 | 注册表类型,自动设为 "device" |

PLR 资源条目的 `config_info` 由注册表在上报模式下生成:实例化一次资源,把整棵树按节点展开。它是**模板**,不带实例身份:
节点没有 `uuid` / `parent_uuid` / `name`,父子关系写在 `parent_id`(父节点的 `id`,根为 `null`);库位(`sites`)也没有
`uuid` / `material_uuid`。同一份资源定义每次生成的结果相同,物料权威的模板不会因 Host 重启或缓存重建而变版本;
实例的 uuid 由物料权威在建物料时分配。旧云端后端仍要每个节点带 uuid,旧协议适配层上报时按(模板 id, 节点 id)派生稳定 uuid 补上。

### class 字段详解

class 是核心部分,包含这些内容:
Expand Down
97 changes: 97 additions & 0 deletions tests/resources/test_registry_template_config_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""注册表模板(``config_info``)不带实例 uuid:同一资源定义每次生成逐字节相同,旧后端仍拿到带 uuid 的旧形状。"""

from __future__ import annotations

import json
import re
from concurrent.futures import ThreadPoolExecutor
from typing import Any

import pytest
from pylabrobot.resources import boekel_15mL_falcon_carrier, eppendorf_96_tiprack_10ul_eptips

from unilabos.client.host.legacy_adaptor.legacy.sync import _legacy_registry_entry
from unilabos.registry.registry import lab_registry
from unilabos.resources.adapters.registry_materials import registry_definition_to_template
from unilabos.resources.resource_tracker import ResourceTreeSet

_UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
_MODULES = {
"tiprack": "pylabrobot.resources:eppendorf_96_tiprack_10ul_eptips",
# 载架带库位(sites),库位上也有实例 uuid
"carrier": "pylabrobot.resources:boekel_15mL_falcon_carrier",
}


def _templates(factory) -> list[dict[str, Any]]:
tree = ResourceTreeSet.from_plr_resources([factory(name=factory.__name__)], known_random_uuid=True, old_size=True)
return tree.dump_templates()[0]


@pytest.mark.parametrize("factory", [eppendorf_96_tiprack_10ul_eptips, boekel_15mL_falcon_carrier])
def test_template_dump_is_identical_across_generations_and_has_no_uuid(factory) -> None:
first, second = _templates(factory), _templates(factory)
text = json.dumps(first, sort_keys=True)
assert text == json.dumps(second, sort_keys=True)
assert not _UUID.search(text)
assert all("uuid" not in node and "parent_uuid" not in node and "name" not in node for node in first)
# 父子关系用父节点 id 表示:根没有父,其余节点的父都在同一棵树里
ids = {node["id"] for node in first}
assert first[0]["parent_id"] is None
assert all(node["parent_id"] in ids for node in first[1:])
# 实例化物料需要的内容都还在
assert first[0]["type"] and first[0]["config"]["type"]


def test_carrier_template_keeps_site_definitions_without_instance_identity() -> None:
sites = _templates(boekel_15mL_falcon_carrier)[0]["sites"]
assert sites, "载架模板应保留库位定义"
assert all({"uuid", "material_uuid", "occupied_material_uuid"}.isdisjoint(site) for site in sites)
assert all("label" in site and "index" in site for site in sites)


def test_registry_generates_uuid_free_config_info_and_a_stable_template_hash(monkeypatch) -> None:
"""注册表两次重新生成 config_info:内容一样,物料权威的模板哈希也一样(不会每次启动都变一版)。"""

def generate() -> dict[str, list[dict[str, Any]]]:
entries = {
rid: {"id": rid, "class": {"type": "pylabrobot", "module": module}, "config_info": []}
for rid, module in _MODULES.items()
}
monkeypatch.setattr(lab_registry, "resource_type_registry", entries)
executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="RegistryTemplateTest")
monkeypatch.setattr(lab_registry, "_startup_executor", executor)
try:
lab_registry._populate_resource_config_info(config_cache={}) # noqa: SLF001
finally:
executor.shutdown(wait=True)
return {rid: entry["config_info"] for rid, entry in entries.items()}

first, second = generate(), generate()
assert json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True)
assert all(first[rid] for rid in _MODULES)
assert not _UUID.search(json.dumps(first))
for rid, config_info in first.items():
a = registry_definition_to_template({"id": rid, "config_info": config_info})
b = registry_definition_to_template({"id": rid, "config_info": second[rid]})
assert a.model_dump() == b.model_dump()


def test_legacy_upload_restores_stable_uuids_and_parent_links() -> None:
config_info = _templates(eppendorf_96_tiprack_10ul_eptips)
entry = {"id": "tiprack_10ul", "config_info": config_info}
uploaded = _legacy_registry_entry(entry)["config_info"]
assert uploaded == _legacy_registry_entry(entry)["config_info"]
by_id = {node["id"]: node for node in uploaded}
for template, node in zip(config_info, uploaded):
assert "parent_id" not in node
assert _UUID.fullmatch(node["uuid"]) and node["name"] == node["uuid"]
parent_id = template["parent_id"]
assert node["parent_uuid"] == (by_id[parent_id]["uuid"] if parent_id else None)
assert len({node["uuid"] for node in uploaded}) == len(uploaded)
# 另一个模板里同名的节点得到不同的 uuid
other = _legacy_registry_entry({"id": "tiprack_other", "config_info": config_info})["config_info"]
assert other[0]["uuid"] != uploaded[0]["uuid"]
# 旧版本生成、已带 uuid 的定义原样上报
legacy_nodes = [{"id": "root", "uuid": "11111111-1111-4111-8111-111111111111", "name": "x", "parent_uuid": None}]
assert _legacy_registry_entry({"id": "old", "config_info": legacy_nodes})["config_info"] == legacy_nodes
30 changes: 29 additions & 1 deletion unilabos/client/host/legacy_adaptor/legacy/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Set
from uuid import UUID, uuid5

from unilabos.client.host.legacy_adaptor.legacy.http import (
LegacyBackendHTTPClient,
Expand All @@ -43,6 +44,31 @@
)


# 旧后端模板节点的 uuid 命名空间:按 (模板 id, 节点 id) 派生,同一模板每次上报都相同
_LEGACY_TEMPLATE_NODE_NAMESPACE = UUID("0d3c1f9e-6a57-4f0b-9a52-3c7e2b8d41a6")


def _legacy_config_info(template_id: str, nodes: Any) -> List[Any]:
"""注册表模板不带实例身份(``parent_id`` 表示父子);旧后端的 config_info 每个节点要有
``uuid`` / ``parent_uuid`` / ``name``(= uuid)。这里按模板 id 与节点 id 派生稳定 uuid 补回旧形状,
已经带 uuid 的节点(旧版本生成的定义)原样保留。"""

def node_uuid(node_id: Any) -> str:
return str(uuid5(_LEGACY_TEMPLATE_NODE_NAMESPACE, f"{template_id}/{node_id}"))

result: List[Any] = []
for node in nodes if isinstance(nodes, (list, tuple)) else []:
if not isinstance(node, Mapping) or "uuid" in node or not node.get("id"):
result.append(node)
continue
item = dict(node)
parent_id = item.pop("parent_id", None)
item["uuid"] = item["name"] = node_uuid(item["id"])
item["parent_uuid"] = node_uuid(parent_id) if parent_id else None
result.append(item)
return result


@dataclass(frozen=True)
class RegistryUploadReport:
device_count: int
Expand All @@ -61,6 +87,8 @@ def _legacy_registry_entry(entry: Mapping[str, Any]) -> Dict[str, Any]:
if display_name and not item.get("displayname"):
item["displayname"] = display_name
item.pop("available_sites", None)
if "config_info" in item:
item["config_info"] = _legacy_config_info(str(item.get("id") or ""), item["config_info"])
klass = item.get("class")
if isinstance(klass, dict):
klass.pop("supported_backends", None)
Expand Down Expand Up @@ -194,7 +222,7 @@ def legacy_template_from_authority(template: Any) -> Dict[str, Any]:
"description": str(definition.get("description") or ""),
"icon": str(definition.get("icon") or ""),
"category": list(getattr(template, "category", None) or []),
"config_info": list(definition.get("config_info") or []),
"config_info": _legacy_config_info(name, definition.get("config_info") or []),
"handles": [
handle.model_dump(mode="json") if hasattr(handle, "model_dump") else dict(handle)
for handle in (getattr(template, "handles", None) or [])
Expand Down
8 changes: 4 additions & 4 deletions unilabos/registry/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,8 +753,7 @@ def _run_ast_scan(
cached_devices = cached_build.get("devices", {})
cached_resources = cached_build.get("resources", {})
if set(cached_devices) == set(ast_devices) and set(cached_resources) == set(ast_resources):
# 按本次扫描的顺序登记:缓存可能是旧版本按线程完成先后写下的。不靠升缓存版本作废它,
# 那样每台 Host 都会重新生成一遍资源 config_info,其中的随机 uuid 让每个资源模板都变一版
# 按本次扫描的顺序登记:缓存可能是旧版本按线程完成先后写下的
self.device_type_registry.update({did: cached_devices[did] for did in ast_devices})
self.resource_type_registry.update({rid: cached_resources[rid] for rid in ast_resources})
logger.info(
Expand Down Expand Up @@ -1912,7 +1911,7 @@ def _get_config_cache_path() -> Optional[Path]:
return Path(BasicConfig.working_dir) / "registry_cache.pkl"
return None

_CACHE_VERSION = 10 # 10:物料锁不再按动作改写,YAML 里的 materials_need_lock / materials_free 一律忽略
_CACHE_VERSION = 11 # 11:config_info 不再带实例 uuid(旧缓存里是随机 uuid,需要重新生成一次)
# 同一进程内的缓存文件快照:(mtime_ns, size, data)。AST / YAML / config_info 几个阶段各自
# 加载一次同一个十几 MB 的 pickle 要几百毫秒;文件没变就复用已加载的对象。
_config_cache_memo: Optional[Tuple[int, int, dict]] = None
Expand Down Expand Up @@ -2045,7 +2044,8 @@ def _import_and_dump(resource_id: str, module_str: str):
tree_set = ResourceTreeSet.from_plr_resources(
[res_instance], known_random_uuid=True, old_size=True
)
dumped = tree_set.dump()
# 模板不带实例 uuid:同一资源定义每次生成都一样,模板哈希不会因重新生成而变
dumped = tree_set.dump_templates()
return resource_id, dumped[0] if dumped else []
except Exception as e:
logger.warning(f"[Uni-Lab-OS Registry] 资源 {resource_id} config_info 生成失败: {e}")
Expand Down
41 changes: 41 additions & 0 deletions unilabos/resources/resource_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@
# 权威容量约束不属于 PLR 构造参数,通过运行时 sidecar 往返。
EXTRA_RESOURCE_CAPACITY = "unilabos_capacity"

# 实例身份字段:注册表模板(config_info)里不带,见 ResourceTreeSet.dump_templates
_TEMPLATE_INSTANCE_FIELDS = frozenset({"uuid", "parent_uuid", "name"})
_TEMPLATE_SITE_INSTANCE_FIELDS = frozenset({"uuid", "material_uuid", "occupied_material_uuid"})


def iter_serialized_plr_children(
resource: "PLRResource", serialized: Mapping[str, Any]
Expand Down Expand Up @@ -1655,6 +1659,43 @@ def dump(self) -> List[List[ResourceDictType]]:
result.append(tree_nodes)
return result

def dump_templates(self) -> List[List[ResourceDictType]]:
"""按 :meth:`dump` 的形状序列化,但去掉实例身份,用作注册表模板(``config_info``)。

模板不是实例:``uuid`` / ``parent_uuid`` / 等于 uuid 的 ``name``,以及库位的
``uuid`` / ``material_uuid`` / ``occupied_material_uuid`` 每次生成都是随机值,会让模板哈希
每次都变,实例化时物料权威也会另发。父子关系改用父节点的 ``id``(``parent_id``,根为 None;
PLR 要求同一棵树里名字唯一)。同一份资源定义生成的结果逐字节相同。
"""

result = []
for tree in self.trees:
nodes = [node.res_content.model_dump(by_alias=True) for node in tree.get_all_nodes()]
id_of_uuid = {node["uuid"]: node["id"] for node in nodes}
ids = [node["id"] for node in nodes]
if len(set(ids)) != len(ids):
raise ValueError(f"资源模板 {ids[0]} 的子资源 id 重复,无法用 id 表示父子关系")
templates = []
for node in nodes:
template = {
key: value
for key, value in node.items()
if key not in _TEMPLATE_INSTANCE_FIELDS
}
template["parent_id"] = id_of_uuid.get(node.get("parent_uuid"))
if template.get("sites"):
template["sites"] = [
{
key: value
for key, value in site.items()
if key not in _TEMPLATE_SITE_INSTANCE_FIELDS
}
for site in template["sites"]
]
templates.append(template)
result.append(templates)
return result

@classmethod
def load(cls, data: List[List[Dict[str, Any]]]) -> "ResourceTreeSet":
"""
Expand Down