diff --git a/AGENTS.md b/AGENTS.md index 46e61354d3..f4635f868d 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 04cec3b27d..72b0193bc4 100644 --- a/docs/developer_guide/action_standard.md +++ b/docs/developer_guide/action_standard.md @@ -15,9 +15,9 @@ 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`) | 严格;预检与派发前核对库位归属与占用 | +| `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 类型……) | 退回注册表原来的签名类型推断 | 按推断结果;推断不出的部分接受任意值 | @@ -26,11 +26,20 @@ 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 由派发前的物料锁检查保证。不可空的物料参数给空值(`{}` / `""` / `[]`)报 「物料参数 … 没有给物料」;可空的物料参数留空等于没给。 +- 物料参数还可以**按库位绑定**:`{"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 | 校验 | @@ -45,6 +54,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)不做上面的校验。 @@ -104,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_*`)。 @@ -158,6 +222,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 f23ac49bb9..a7495f3acf 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/developer_guide/api_v1_migration.md b/docs/developer_guide/api_v1_migration.md index 25872bd5af..727533a60a 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`、 @@ -148,8 +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 合同里,暂保持原名。CLI `workflow watch` 同步修改。 + `runtime.logs.changed`(日志通知)与物料的 `/api/v1/materials/events`(`materials.changed`)不在 + V1 合同里,暂保持原名。物料失效另以 V1 名 `material.changed`(`data.sequence` 为物料账本末尾, + `data.material_uuids` 列出这段账本里变了的物料,Site 的变化归到所属物料、拓扑边归到两端;空列表表示没有物料变化, + 涉及模板、账本重置或超过 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 落地) @@ -164,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 35d01522b7..a9c75a58a2 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. @@ -207,9 +215,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; `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`; 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. | +| 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 | @@ -220,7 +228,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; 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 | @@ -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) | @@ -299,6 +307,17 @@ 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`). 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/databases.md b/docs/developer_guide/databases.md index f36d9911ab..25700f012c 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/edge_ui_api.md b/docs/developer_guide/edge_ui_api.md index 3516db6209..3c2624f4f1 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/examples/materials_operations_guide.md b/docs/developer_guide/examples/materials_operations_guide.md index 5606de8a0c..7e49178222 100644 --- a/docs/developer_guide/examples/materials_operations_guide.md +++ b/docs/developer_guide/examples/materials_operations_guide.md @@ -169,27 +169,32 @@ 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 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 都按这条路径放置, @@ -211,30 +216,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 侧调用方会先收到超时。 - -创建多件耗材再逐件 `assign` 时,先校验目标位点空闲;挂载失败要 `materials.remove` 掉本轮已经 -发号的物料,否则权威里会留下不挂在任何台面上的孤儿。 +Host 下发的 `RESOURCE_APPEND`(出库并挂载)仍由设备节点的 `append_resource` 执行;它的 `timeout` +(默认 30 s)只约束提交点之前:等挂载锁、从权威拉取物料。超时就取消,本地与权威都不变,抛 `TimeoutError`。 +本地 PLR 挂上之后(提交点),权威 move 与快照回报一定走完再返回:快照按物料所在的整棵根树做,上千个物料的 +台面要几十秒,期间每过一个 `timeout` 记一条 WARNING,不会在提交之后取消。 -目标位参数(二选一): +目标位参数(`site` 与 `slot` 都给时必须指向同一个库位),由权威按父物料的库位解析: -| 参数 | 承载 | 示例 | 适用 | -| ------ | ---------------------- | ----------------------- | ------------------------- | -| `site` | 权威 `ResourceSite.uuid` | `"26da5442-…"` | 机器路径(前端/微后端下发),move 直传免反查 | -| `slot` | label 或 0-based 数字字符串 | `"A1"` / `"T2"` / `"0"` | 人类/脚本路径;label 优先于数字解释 | +| 参数 | 承载 | 示例 | +| ------ | ------------------------------------ | -------------------------- | +| `site` | 库位实例、权威 `ResourceSite.uuid`、label 或 index | `site_instance` / `"26da5442-…"` | +| `slot` | label 或库位自己的 index | `"A1"` / `"T2"` | -行为细节(自动完成,无需干预): +行为细节: -- 本地已持有该 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 内容物与状态同步 @@ -344,9 +345,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. 三种创建来源规范 @@ -368,8 +367,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` 语义) @@ -470,8 +469,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/examples/materials_tutorial.md b/docs/developer_guide/examples/materials_tutorial.md index befb9ee74b..0b0f9366df 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/developer_guide/interfaces/api-catalog.md b/docs/developer_guide/interfaces/api-catalog.md index b3c6bb400f..99aa777803 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 还需识别设备投影失败。不要收到错误后直接改数据库或更换幂等键重放物理动作。 @@ -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/materials.md b/docs/developer_guide/interfaces/materials.md index 142bfa20c9..31eed2be72 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 的记录。 @@ -200,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`,工作流按所属物料选库位时用到)。这是临时条件, 预留接收、取消或过期后同一请求可以重试。 执行顺序: @@ -252,7 +257,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/python-cli-mcp.md b/docs/developer_guide/interfaces/python-cli-mcp.md index b391bdcb2e..20542d48ba 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; @@ -226,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 3b079babee..1d3bd4362f 100644 --- a/docs/developer_guide/interfaces/realtime.md +++ b/docs/developer_guide/interfaces/realtime.md @@ -4,11 +4,12 @@ | 使用者 | 通道 | 内容 | | --- | --- | --- | -| 浏览器工作流页、日志页 | SSE `/api/v1/events` | 持久工作流变更 + 瞬时日志失效通知 | -| 浏览器物料库、地图 | SSE `/api/v1/materials/events` | 物料账本变更通知 | +| 浏览器(每个工站一条) | 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 只有一个活动执行控制连接, @@ -22,27 +23,88 @@ | 项目 | `/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 | -| 无事件时 | keepalive 注释;工作流检查约 1 秒,心跳约 15 秒 | keepalive 注释;约 1 秒检查账本 | - -三个游标相互独立:工作流 id、物料 sequence、日志 stream:offset。不能混用,也不能以最后日志通知替换工作流游标。 +| 无 Last-Event-ID 首连 | 固定当前最新序号,先发只含 `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 秒检查账本 | + +三个游标相互独立:`/api/v1/events` 的 SSE id、物料账本 sequence、日志 stream:offset。不能混用。 +`material.changed` 的 `data.sequence` 是物料账本序号,不是 `/api/v1/events` 的游标。 + +### `/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 个物料),**整体重读**。 + +浏览器因此每个工站只需维持 `/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 +id: 42:3f9c0a1b7d2e4c55 event: materials.changed data: {"sequence":42,"operation":"update_position","aggregate_type":"material","aggregate_uuid":"..."} ``` -通知只说明什么发生了变化,不带完整树、液体或模板正文。 +通知只说明什么发生了变化,不带完整树、液体或模板正文。需要账本序号时读 `data.sequence`, +不要解析 SSE id。账本由上面那条共享轮询读(与 `material.changed` 的写入器共用),每个连接从自己的游标补读, +之后共用同一份结果,不按连接重复读,也不占默认线程池(runtime.v1 控制 socket 的出站泵、edge 代理用它)。 + +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 快照**。重连同样重新读快照, 避免“首次取数据 → 开始订阅”之间的变更遗漏。 @@ -76,6 +138,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(); }; } @@ -97,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` / @@ -108,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:[...]}`。 @@ -128,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 687d1025f6..add51edb8d 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 a01b9f53db..fb13f15930 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/networking_overview.md b/docs/developer_guide/networking_overview.md index f5987f1c12..d74a20510d 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/docs/developer_guide/scheduling_and_execution.md b/docs/developer_guide/scheduling_and_execution.md index fd4936996c..d1fa7c357f 100644 --- a/docs/developer_guide/scheduling_and_execution.md +++ b/docs/developer_guide/scheduling_and_execution.md @@ -61,7 +61,10 @@ 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`)走同一条解析路径。按所属物料选择的库位参数(`{"owner_uuid": ...}`)在调度器准入任务时 + (`_admit_fresh_task`,先于整任务库存预留)选定、经入口预留占住并冻结;接受的库位都被占着时任务保持 `pending` 排队。 3. `WorkflowService` 调用已绑定的 `BackendScheduler.submit(task_uuid)`。 4. Scheduler 从持久化 Task/节点运行构建 `TaskDag`,恢复已完成节点后开始走图。 @@ -257,7 +260,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/docs/developer_guide/v1_dev_reconciliation.md b/docs/developer_guide/v1_dev_reconciliation.md index ddac075a57..9919ffe2d0 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` | diff --git a/docs/developer_guide/v1_file_index/app.md b/docs/developer_guide/v1_file_index/app.md index ec90ddab97..a6a923779c 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 节点面板拿不到条件 / 循环模板 | diff --git a/docs/developer_guide/v1_file_index/scheduler.md b/docs/developer_guide/v1_file_index/scheduler.md index 630dfcbee6..9c9c8ec976 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/docs/developer_guide/workflow_static_conditions.md b/docs/developer_guide/workflow_static_conditions.md index 7b8bc36ec1..0d69482c5d 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 合同再开放界面选项。 diff --git a/docs/user_guide/graph_files.md b/docs/user_guide/graph_files.md index 39f0df925e..3fc24993a5 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/docs/user_guide/virtual_devices.md b/docs/user_guide/virtual_devices.md index 8544c3ff03..b2d508f18e 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/app/test_no_ros_installation.py b/tests/app/test_no_ros_installation.py index 25db77c349..b6a99d7ac2 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 06e43eb62a..d23dc96ea7 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 5fd623a62c..41acd5b871 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 7d25405c29..1c0f16b922 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 b083733e39..2a7e2146aa 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/app/test_workflow_watch_sse.py b/tests/app/test_workflow_watch_sse.py index 0e36a26560..f619b4791c 100644 --- a/tests/app/test_workflow_watch_sse.py +++ b/tests/app/test_workflow_watch_sse.py @@ -13,12 +13,15 @@ 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.workflow import format_sse_event def test_sse_lines_split_crlf_across_chunks_without_extra_blank_lines() -> None: @@ -155,6 +158,108 @@ def test_watch_follows_stream_reset_and_skips_unchanged_snapshots() -> None: ] +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" + + 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", 41), (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), + ] + + +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/tests/client/host/hostlink/test_backend.py b/tests/client/host/hostlink/test_backend.py index 6c16128ba2..dfe500000f 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/hostlink/test_backend_service.py b/tests/client/host/hostlink/test_backend_service.py index a3ae1d3097..c6340e5e23 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_device_material_maintenance.py b/tests/client/host/hostlink/test_device_material_maintenance.py new file mode 100644 index 0000000000..2a2eb58d51 --- /dev/null +++ b/tests/client/host/hostlink/test_device_material_maintenance.py @@ -0,0 +1,195 @@ +"""设备持有的物料建不成 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" + + +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/client/host/hostlink/test_host_node.py b/tests/client/host/hostlink/test_host_node.py index 15df658274..ab9df899c7 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/hostlink/test_material_creation_flows_e2e.py b/tests/client/host/hostlink/test_material_creation_flows_e2e.py index 78f3ed5a79..97773baf49 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 059f07e1f0..c2b2c5dc46 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_materials_proxy.py b/tests/client/host/hostlink/test_materials_proxy.py index bc9664d656..489270f04b 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_slave_startup_order.py b/tests/client/host/hostlink/test_slave_startup_order.py index e01b38f0d7..73a3e68d08 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/hostlink/test_virtual_heating_platform_dispatch.py b/tests/client/host/hostlink/test_virtual_heating_platform_dispatch.py index 03d6b876f9..ce9623181a 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/client/host/hostlink/test_warehouse_site_placement.py b/tests/client/host/hostlink/test_warehouse_site_placement.py index 13432da35c..af2698292c 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/ros2/test_slave_post_init_assign.py b/tests/client/host/ros2/test_slave_post_init_assign.py new file mode 100644 index 0000000000..4dca25d398 --- /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/tests/client/host/ros2/test_slave_shutdown.py b/tests/client/host/ros2/test_slave_shutdown.py index afc1456bb7..b469e8f5ad 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_action_context_injection.py b/tests/client/host/runtime/test_action_context_injection.py new file mode 100644 index 0000000000..6a0233fc9b --- /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/client/host/runtime/test_append_resource_commit.py b/tests/client/host/runtime/test_append_resource_commit.py index fa4d89fea6..36127d1d6e 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/client/host/runtime/test_node.py b/tests/client/host/runtime/test_node.py index a61b7edf82..f0b7def397 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 b8baea082e..b028966b71 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 54f13c915a..e80f250b47 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: @@ -969,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/devices/test_virtual_heating_platform.py b/tests/devices/test_virtual_heating_platform.py index edf8f35f5b..451492c301 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,296 @@ 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: +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" + + +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 + + 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} + + +@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-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 - ) + yield rig + finally: + rig.stop() + set_materials_gateway(None) + service.close() - result = platform.heat_site( - site_id=2, - target_temperature_c=72.5, - duration_seconds=0.1, - action_context=ActionContext(action_id="demo-job-1"), + +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-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] + 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_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-sample-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) + - 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 +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_material_temperature_is_latest_passive_device_projection( - tmp_path, monkeypatch -) -> None: +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 = 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 + 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/tests/e2e/readme_demos.py b/tests/e2e/readme_demos.py index 3ba5974e2e..7f85e46137 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", @@ -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) @@ -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 diff --git a/tests/e2e/run_mcp_demos.py b/tests/e2e/run_mcp_demos.py index 0412917c80..d33c4016e9 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 ae33708f55..45607108d4 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 7d10ac8dbb..886b8b018a 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/heating_fixtures.py b/tests/heating_fixtures.py new file mode 100644 index 0000000000..22cf57f7e8 --- /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/tests/plr_fixtures.py b/tests/plr_fixtures.py index f05acf6f05..259f7d450d 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/registry/test_action_context_by_type.py b/tests/registry/test_action_context_by_type.py new file mode 100644 index 0000000000..89fba7e2bd --- /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 544fff7e7e..0cf2941784 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/tests/registry/test_host_node_backend_parity.py b/tests/registry/test_host_node_backend_parity.py index 699d6674dc..af8fd3aa24 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 97ef34b72a..c046fea659 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/resources/test_device_available_sites.py b/tests/resources/test_device_available_sites.py index 64fcb1540c..64266bbe45 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_material_class_contract.py b/tests/resources/test_material_class_contract.py new file mode 100644 index 0000000000..85c6810dbe --- /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_materials_create_and_place.py b/tests/resources/test_materials_create_and_place.py new file mode 100644 index 0000000000..50962be629 --- /dev/null +++ b/tests/resources/test_materials_create_and_place.py @@ -0,0 +1,564 @@ +"""物料创建即落位(原子)与挂到设备自身库位:``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 unilabos.server.services.materials.core import MaterialValidationError +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)) + # assign 与 transfer 同一条路:权威提交后经物料服务下发 unload / load + service.set_resource_sync_dispatcher(runtime.dispatch_material_sync) + 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"]) + + 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 + ) + # 同设备换位也是一次 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: + 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_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"]) + + 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 + 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") + + +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") + + [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(moved) is None + # 原父树与权威一致:严格快照不再因为「本地多一个孩子」被拒 + materials.update(node, created) + materials.update(node, moved) + + +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(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 + 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_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"] + + +# ── 本地加载失败时不留分叉:先查前提,提交后失败就在同一条命令下撤销 ───────── + + +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 + + +# ── 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/tests/resources/test_plr_registration_hook.py b/tests/resources/test_plr_registration_hook.py index 32ed25170f..c10fb299ad 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/tests/resources/test_registry_material_adapter.py b/tests/resources/test_registry_material_adapter.py index 49995d1bfa..e779749776 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_backend_control_protocol.py b/tests/server/test_backend_control_protocol.py index b6c10b62a0..7f2c3b6dc9 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, "远程计算机拒绝网络连接") diff --git a/tests/server/test_content_quantity_workflow.py b/tests/server/test_content_quantity_workflow.py index 2f80ce49de..8bf1555683 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_database_schema_versions.py b/tests/server/test_database_schema_versions.py index 24faab8b61..397cc6b7c4 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, "a32591765329a4b4526bd142b7c8622d991bdacdb10cca2645b78f2c49d1d193"), "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_driver_source_changes.py b/tests/server/test_driver_source_changes.py index 1facb0c8cd..d76b66f95d 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 77e7c094b1..cac305ffd1 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_graph_carrier_holders.py b/tests/server/test_graph_carrier_holders.py new file mode 100644 index 0000000000..f791cb0de9 --- /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/tests/server/test_inventory_seam_v1.py b/tests/server/test_inventory_seam_v1.py index a4290a5afa..1a80c8c7c2 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_legacy_graph_compat.py b/tests/server/test_legacy_graph_compat.py index cc9e73a2fb..82966de5eb 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 402f133a10..caa1e81a02 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_log_notices.py b/tests/server/test_log_notices.py index 9914afb877..1cfc6742ab 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_material_io_inventory.py b/tests/server/test_material_io_inventory.py index d25beda915..c846147280 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: @@ -206,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/tests/server/test_material_io_scheduler.py b/tests/server/test_material_io_scheduler.py index ceef016ff7..bd10c0cb3c 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_material_links.py b/tests/server/test_material_links.py index f925404562..63fa4d881e 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(), ) @@ -211,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_material_site_binding.py b/tests/server/test_material_site_binding.py new file mode 100644 index 0000000000..bb18ab676f --- /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/tests/server/test_materials_device_subtree_plr_only.py b/tests/server/test_materials_device_subtree_plr_only.py new file mode 100644 index 0000000000..f43e663bce --- /dev/null +++ b/tests/server/test_materials_device_subtree_plr_only.py @@ -0,0 +1,377 @@ +"""设备持有的物料只收格式合规的 PLR 物料,一棵 PLR 树里 PLR 键不重复(权威在每一条写路径上把关)。 + +设备启动时按 ``ResourceTreeSet`` 把设备子树整棵反序列化成 PLR 实例,靠每个节点的 +``config.type``(PLR 自己的类型名)找类,PLR 还要求一棵树里名字唯一。权威只核对格式(Python 标识符 +形式的类名),不判断类是否存在(类不存在由 Host 发现,那台设备进入维护模式)。建树即落位、move / +transfer、patch config(含 V1 PUT)与设备快照都按写入后的最终状态走同一道检查。 +""" + +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, + 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 MaterialConflictError, 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, 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=config, + ), + ) + + +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="config.type"): + _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"] + + +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/tests/server/test_materials_events.py b/tests/server/test_materials_events.py index 247ea31730..f485517220 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/tests/server/test_mcp.py b/tests/server/test_mcp.py index ef3bb70dc1..4781cb16ec 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/tests/server/test_monitor_events_resume.py b/tests/server/test_monitor_events_resume.py new file mode 100644 index 0000000000..2cf487ede7 --- /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_package_operation_recovery.py b/tests/server/test_package_operation_recovery.py index 01a096e24f..43f2e7a1a6 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_events_material_notices.py b/tests/server/test_runtime_events_material_notices.py new file mode 100644 index 0000000000..d52acc9c6a --- /dev/null +++ b/tests/server/test_runtime_events_material_notices.py @@ -0,0 +1,569 @@ +"""/api/v1/events 的物料与日志通知:权威进程合并、限速后写进 frontend_event,与工作流事件同一序列。 + +每一帧都带整数 id:断线期间的物料变化在重连(Last-Event-ID)后补发,过期 / 超前游标照常 stream.reset。 +通知列出这段账本里变了的物料,前端只重读这些(空列表:没有物料变化);列不准时省略,前端整体重读。 +账本由一个物料权威一条的共享轮询线程读,写入器是它的常驻订阅者。 +""" + +from __future__ import annotations + +import asyncio +import json +import time +from contextlib import contextmanager +from types import SimpleNamespace + +import pytest + +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 + +NOW = "2026-11-04T00:00:00Z" + + +class _Ledger: + """最小物料权威:账本末尾、账本条目、Site → 所属物料。""" + + def __init__(self, tail: int, rows=(), sites=None): + self.tail = tail + 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 + + 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 + + +class _NoLogs: + def subscribe(self, listener): + return lambda: None + + +class _Hub: + listener = None + + def subscribe(self, listener): + self.listener = listener + return lambda: setattr(self, "listener", None) + + +class _ManualWatch(LedgerWatch): + """手动投递账本批次:记下订阅起点与回调,由测试决定每一批什么时候到。""" + + def __init__(self) -> None: + super().__init__(None) + self.after: object = "unset" + self.deliver = None + + def subscribe(self, after, deliver): + self.after, self.deliver = after, deliver + return lambda: None + + +@pytest.fixture +def workflow(monkeypatch): + monkeypatch.setattr(events, "shutting_down", lambda: False) + service = WorkflowService(":memory:") + yield service + service.close() + + +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] + + +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) + + +@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() + + +def _material_rows_after(service: WorkflowService, recorded: int, ledger: _Ledger) -> list[dict]: + """先记下一条“上次写到 recorded”的物料通知,再启动写入器,返回它续写出的物料通知。""" + + 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:]] + + +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 _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_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") + + 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): + 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", + ) + + 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 = LedgerWatch(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.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() + + +def test_many_connections_share_one_ledger_read_per_tick(): + """N 个订阅者共用一次读:账本末尾的读取次数与连接数无关。""" + + import threading + + 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.add((4, "material", "m")) + 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(): + 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"])] + + +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/tests/server/test_runtime_logs.py b/tests/server/test_runtime_logs.py index b56b55e40f..cb1b1125ae 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_scheduler_inventory_authority.py b/tests/server/test_scheduler_inventory_authority.py index 00b3cc31ff..1b288c4f61 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_server_monotonic.py b/tests/server/test_server_monotonic.py index ce8a0d3f7c..d72fcebf60 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/tests/server/test_site_holder_placement.py b/tests/server/test_site_holder_placement.py index 389a8869cd..619d864cb9 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/tests/server/test_site_selection_by_owner.py b/tests/server/test_site_selection_by_owner.py new file mode 100644 index 0000000000..9eeb7a1686 --- /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/tests/server/test_task_inventory_bindings.py b/tests/server/test_task_inventory_bindings.py index fa12599e70..f0d94d5b83 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 4bced5854d..010edc18e5 100644 --- a/tests/server/test_v1_inventory_api.py +++ b/tests/server/test_v1_inventory_api.py @@ -108,6 +108,38 @@ 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"}), + # 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]), + ], +) +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" + 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"] + 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) @@ -158,7 +190,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") @@ -189,7 +221,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={ @@ -220,7 +252,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 b96f15e458..8525720afa 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", @@ -64,7 +66,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_v1_resource_contract.py b/tests/server/test_v1_resource_contract.py index 5fd489a52c..3e131a8909 100644 --- a/tests/server/test_v1_resource_contract.py +++ b/tests/server/test_v1_resource_contract.py @@ -172,6 +172,250 @@ 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(tmp_path, monkeypatch) -> None: + """建物料、放入库位与装液是同一个事务:装液失败时物料与落位一起回滚,库位仍空、不留半成品。 + + 失败必须发生在服务里(建树与落位已经写进事务之后),而不是被请求模型挡在门外。 + """ + + 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: + """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,由生命周期派生。""" + + 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_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={ + "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"] == [] + # 空值不算点名(``?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) + + 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/tests/server/test_workflow_export_import_roundtrip.py b/tests/server/test_workflow_export_import_roundtrip.py new file mode 100644 index 0000000000..b6b7607ec5 --- /dev/null +++ b/tests/server/test_workflow_export_import_roundtrip.py @@ -0,0 +1,389 @@ +"""导出(读图)→ 导入 → 再导出:图结构稳定,节点引用随新身份改写,组合调用的私有子图重新展开。 + +导出只含本层(组合调用的私有子图隐藏),图根 ``inventory_requirements`` 是从节点派生的只读投影; +导入换掉全部节点 / 连线身份。覆盖:组合调用父图(子操作与本层同名需求、子操作里的循环与携带)、 +分组、循环、条件分支、禁用节点、以上游结果为来源的库存需求、作者声明的 I/O 合同、节点输入绑定、 +资源作用域与创作顺序,以及工作流复制。 +""" + +from __future__ import annotations + +import copy +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 +from tests.server.test_workflow_publication import ( + DEVICE_TEMPLATE, + NUMBER, + VOLUME_SOURCE, + VOLUME_TARGET, + _install_device_template, +) + +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 _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 = { + "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"] + ], + } + 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: + """图里每一种指向节点的引用都换成新身份;旧身份一个不剩。""" + + 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 + + +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"]) + + +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 + + +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/tests/server/test_workflow_inventory_requirements_projection.py b/tests/server/test_workflow_inventory_requirements_projection.py new file mode 100644 index 0000000000..a8a2182f89 --- /dev/null +++ b/tests/server/test_workflow_inventory_requirements_projection.py @@ -0,0 +1,278 @@ +"""工作流库存需求:节点 ``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" + + +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:") + 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" + + +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) + + 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: + """列表给出的 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/tests/server/test_workflow_manual_confirmation.py b/tests/server/test_workflow_manual_confirmation.py index da3e4e408b..5af2dea58c 100644 --- a/tests/server/test_workflow_manual_confirmation.py +++ b/tests/server/test_workflow_manual_confirmation.py @@ -264,6 +264,61 @@ 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 == [] + # 任务先落 canceled,库存在同一收尾流程随后释放(与普通取消一致),所以等释放而不是立即断言。 + wait_for(lambda: 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/tests/server/test_workflow_site_bindings.py b/tests/server/test_workflow_site_bindings.py index 82800f5713..b044bb3745 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", diff --git a/tests/server/test_workflow_source_monitor_wiring.py b/tests/server/test_workflow_source_monitor_wiring.py index 647e2d1ed1..db2b3bbb34 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() diff --git a/tests/test_action_policy.py b/tests/test_action_policy.py index 429662b695..fbf95889ce 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() diff --git a/unilabos/client/host/dora/benchmark/run.py b/unilabos/client/host/dora/benchmark/run.py index 6065f60445..814131b21b 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 b2ab0bfe99..56570c7c69 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/host/hostlink/backend.py b/unilabos/client/host/hostlink/backend.py index a48a7b2e4d..4a49dba082 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 e2a7a17f30..49bd831602 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 @@ -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() @@ -1515,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/hostlink/main_hostlink_run.py b/unilabos/client/host/hostlink/main_hostlink_run.py index ff9e5a585f..74f6802713 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/hostlink/network.py b/unilabos/client/host/hostlink/network.py index 970b0c577f..a3ee8decd5 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/legacy_adaptor/legacy/graph.py b/unilabos/client/host/legacy_adaptor/legacy/graph.py index c01d049caf..7fd88840e5 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/base_device_node.py b/unilabos/client/host/ros2/base_device_node.py index ae27e6bdae..3f9fcb6aa7 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/ros2/main_slave_run.py b/unilabos/client/host/ros2/main_slave_run.py index f1a96adfc3..0951ddf146 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 diff --git a/unilabos/client/host/ros2/presets/host_node.py b/unilabos/client/host/ros2/presets/host_node.py index f2df41b888..60e0566f70 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/ros2/presets/resource_mesh_manager.py b/unilabos/client/host/ros2/presets/resource_mesh_manager.py index e29d146b84..a54dff198b 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/client/host/runtime/action.py b/unilabos/client/host/runtime/action.py index 6bfdad67ee..ad2b6a6ecf 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/client/host/runtime/driver_creator.py b/unilabos/client/host/runtime/driver_creator.py index c7feac41ce..e3c40b8c7e 100644 --- a/unilabos/client/host/runtime/driver_creator.py +++ b/unilabos/client/host/runtime/driver_creator.py @@ -15,11 +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, + require_plr_config_type, ) from unilabos.utils import logger from unilabos.utils.cls_creator import create_instance_from_config @@ -34,6 +36,43 @@ def create_instance(self, *args: Any, **kwargs: Any) -> T: raise NotImplementedError +def build_device_materials(children: List[ResourceDictInstance]) -> Dict[str, Any]: + """把设备持有的每棵物料子树建成 PLR 实例,返回 ``{子树根 uuid: 实例}``;建不成就抛错。 + + 设备持有的物料只收 PLR 物料(权威核对 ``config.type`` 的格式);类是否存在、能否反序列化只有 + Host 知道。任何一棵建不成(缺 / 写错 ``config.type``、类不存在、反序列化失败)都抛 + :class:`DeviceMaterialError`:这台设备进入维护模式、不启动,Host 与其余设备照常运行。没有 + 「跳过建不成的物料、设备照常启动」的退路。``config.type`` 的问题指名到那个物料;反序列化失败 + 指名到那棵子树的根,附 PLR 的报错。子设备由它自己的构造器处理。 + """ + + built: Dict[str, Any] = {} + for child in children: + if child.res_content.type == "device": + continue + 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]): """Create a Python driver and attach its non-device child resources.""" @@ -42,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.children = list(children) self.resource_tracker = 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: @@ -58,10 +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( @@ -91,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") @@ -143,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() @@ -352,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 e258fc03a6..d74b93cf95 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 f5162226eb..e56b0f8e16 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): @@ -824,6 +874,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,10 +1005,30 @@ 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: + # 设备自身的库位在提交点之前解析:选择器无效、或给的 Site uuid 不是本设备的库位时 + # 什么都不改(site 与 slot 走同一套匹配,别的设备的 Site 不会被当成本设备的) + stage = "解析设备库位" + 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] = [] @@ -963,8 +1056,22 @@ 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)) + 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: @@ -996,7 +1103,8 @@ async def append_resource( report_tree_set, parent_uuid, material_uuid ), ) - elif self.resource_uuid: + elif self.resource_uuid and device_site_uuid is None: + # 挂到设备自身、没指定库位:只落父子关系(指定了库位的已在本地挂载前 move 过) for material_uuid in resource_uuids: await self._attach_root_to_device(material_uuid) # 4. 同步:挂载后的父树经 update_resource 直连权威(权威已有 create 记录,严禁 add) diff --git a/unilabos/client/host/runtime/resource.py b/unilabos/client/host/runtime/resource.py index fe9add40c9..5351ee9f7e 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/client/materials/core.py b/unilabos/client/materials/core.py index 1696b3f276..1651b2c2f4 100644 --- a/unilabos/client/materials/core.py +++ b/unilabos/client/materials/core.py @@ -134,6 +134,32 @@ 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": [...], "owners": [{"owner_material_uuid", + "occupant_material_uuid"}]}``(物料参数按库位绑定、库位参数按所属物料选择)。""" + + 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) @@ -544,6 +570,27 @@ 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 []), + "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 5e19bbf491..af3a7dab9d 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, [] @@ -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: @@ -371,7 +372,13 @@ 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``),表示此刻占着该库位的物料, + 服务端建任务时解析并冻结。库位参数(``SiteSlot``)可以按所属物料选择:给 ``{"owner_uuid": 所属物料 uuid}`` + (``site_under_owner``),调度器在任务准入时选定库位并冻结。 + """ operation_id = operation_id or str(uuid4()) return self._http.post( @@ -517,7 +524,8 @@ def watch_task( """订阅 SSE 失效通知,并在每次相关通知后经 HTTP 拉取任务与 Job 正文。 ``after`` 为 0 时从服务端当前水位开始,不回放历史通知;大于 0 时作为 - ``Last-Event-ID`` 从该序号之后续传。``stream.reset`` 表示游标失效,水位 + ``Last-Event-ID`` 从该序号之后续传。产出的 ``cursor`` 是收到的最后一帧的 id(任何帧都推进它, + 包括物料、日志通知),可作下一次的 ``after``。``stream.reset`` 表示游标失效,水位 可能回退,客户端重读 HTTP 校准。快照没有变化的通知不重复产出。 """ @@ -573,15 +581,15 @@ def watch_task( # 游标过期或超前:采用服务端给出的新水位(可能回退)并重读 HTTP。 if sequence is not None: cursor = sequence - elif not self._notice_matches_task(notice, task_uuid): - # 水位帧与其他任务的通知只推进游标,便于调用方用 after 续传。 - 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) @@ -659,23 +667,16 @@ 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,即 ``/api/v1/events`` 那一个序列上的游标;不是非负整数时返回 None。 + + 游标只取 SSE id:``material.changed`` 的 ``data.sequence`` 是物料账本的序号,不能拿来推进游标。 + """ + + value = notice.get("id") + if isinstance(value, int) and not isinstance(value, bool) and value >= 0: + return value return None diff --git a/unilabos/client/session.py b/unilabos/client/session.py index 5d5cb6c3a3..1f72afd035 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/device_mesh/resource_visalization.py b/unilabos/device_mesh/resource_visalization.py index 5dc2423ca3..bb493e6fc0 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/devices/virtual/heating_platform.py b/unilabos/devices/virtual/heating_platform.py index e158908eaf..64d5b4c842 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,126 @@ ] +def _site_label(site_id: int) -> str: + return f"site_{site_id}" + + +#: 新样品身份被占用时最多换几次序号 +_IDENTITY_ATTEMPTS = 10 + + +@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 +244,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 +261,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 +300,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 +325,187 @@ 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 + 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 _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`` 之后取第一个空着的序号, + 建一个新样品,不去动那一个。 + """ + + base = f"{self.device_id}-sample-{site_id}" 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) - ) - state["target_temperature_c"] = float( - material.data.data.get( - "target_temperature_c", state["temperature_c"] + 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) + except Exception: # noqa: BLE001 - 查不到即可用;权威读不到时交给建树报错 + 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, *, after: int = 0) -> tuple[VirtualHeatingSample, int]: + from unilabos.resources.resource_tracker import set_plr_template_name + + resource_id, barcode, number = self._sample_identity(site_id, after=after) + sample = VirtualHeatingSample( + resource_id, + barcode=Barcode( + data=barcode, + 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, 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: + 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}" + 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 ) - ) - serialized = material.data.data.get("serialized_state", {}) - if isinstance(serialized, dict): - state["state"] = str(serialized.get("state", state["state"])) + break + if created is not None: + 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 +516,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 +531,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 +566,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 +588,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 +612,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 +675,8 @@ def serialized_state(self) -> dict[str, Any]: __all__ = [ "AMBIENT_TEMPERATURE_C", "SAMPLE_DISPLAY_COLORS", + "SAMPLE_TEMPLATE", "VIRTUAL_HEATING_PLATFORM_SITES", "VirtualHeatingPlatform", + "VirtualHeatingSample", ] diff --git a/unilabos/protocol/materials.py b/unilabos/protocol/materials.py index d4a300f3d9..950f047d73 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" ] @@ -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 = "" @@ -386,8 +389,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 +981,7 @@ class MaterialDeltaResult(ServerObject): "MaterialIdentityRead", "MaterialIdentityWrite", "MaterialMove", + "MaterialPlacement", "MaterialNodeCreate", "MaterialPatch", "MaterialPosition", diff --git a/unilabos/protocol/runtime/site_references.py b/unilabos/protocol/runtime/site_references.py new file mode 100644 index 0000000000..6d776d6646 --- /dev/null +++ b/unilabos/protocol/runtime/site_references.py @@ -0,0 +1,61 @@ +"""按库位给参数值的线上形态(服务端识别、客户端构造共用)。 + +- 物料参数(``ResourceSlot`` / ``list[ResourceSlot]``)按库位绑定:``{"site_uuid": "<库位 uuid>"}``, + 表示「此刻占着这个库位的物料」。建任务 / 运行预检时解析成占用物料的 ``{"uuid": ...}`` 并冻结进任务, + 之后物料被挪走也不改变任务用的是哪件物料。 +- 库位参数(``SiteSlot``,带 ``Material.site`` 关系)按所属物料选择:``{"owner_uuid": "<所属物料 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" +#: 库位参数按所属物料选择的键 +OWNER_UUID_KEY = "owner_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 + + +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/registry/action_context.py b/unilabos/registry/action_context.py new file mode 100644 index 0000000000..3eba7e1d62 --- /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 d55027b8e4..b413ebf2a8 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 f32dce496b..a7963274f8 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 daa3dc328a..be4a1e21aa 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 1b6951a4b1..0ac0992961 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 888d433fd3..f5c337d66a 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/devices/liquid_handler.yaml b/unilabos/registry/devices/liquid_handler.yaml index 6ee1d61b3d..16cd80802e 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: diff --git a/unilabos/registry/placeholder_keys.py b/unilabos/registry/placeholder_keys.py index f98007cfce..53d39b0aae 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 435a73c4be..d1b7f8b777 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/resources/adapters/plr_materials.py b/unilabos/resources/adapters/plr_materials.py index a73ff22ebf..9d5f434b22 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 @@ -23,6 +24,7 @@ MaterialMove, MaterialNodeCreate, MaterialNodeDelta, + MaterialPlacement, MaterialPosition, MaterialSnapshot, MaterialSnapshotDiff, @@ -256,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, @@ -626,18 +632,33 @@ def create_plr_materials( resources: Sequence[Any], *, 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。 根 extra 是树级元数据的落点(如所属设备 ``unilabos_bound_device_id``); 在 create 请求上合并可保证入库即带元数据,且不修改调用方的输入实例。 + ``placement`` 让权威在建树的同一事务里把根物料落到父物料 / 库位上(原子)。 + ``display_name`` 是根物料的人读标签(省略时取 PLR 名);PLR 运行时不承载展示名, + 之后的快照也不会改写它。``root_position`` 是落位时根物料没有位置时入库的位置(库位的位置或原点), + 权威里不留没有位置的孩子。 """ 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 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) tree = material_tree_to_resource_tree(result.data) return CreatedPLRMaterials( diff --git a/unilabos/resources/adapters/registry_materials.py b/unilabos/resources/adapters/registry_materials.py index dd7ee515c5..2f0bc7ce64 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 0000000000..213c292cfd --- /dev/null +++ b/unilabos/resources/material_class.py @@ -0,0 +1,102 @@ +"""物料 ``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`` +把注册表条目 ``class.module`` 所在的模块 import 进来,让类可见(见 +:func:`unilabos.resources.plr_additional_res_reg.register_registry_resources`),不用 ``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 f3b6eb7fbd..e9ff9364f1 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; @@ -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 @@ -29,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, @@ -42,11 +43,12 @@ ACTOR_DEVICE, ACTOR_EDGE, MaterialMove, + MaterialPlacement, MaterialTransfer, 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 @@ -663,14 +665,212 @@ 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 +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 _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: + """阻塞等待本地挂载的调用不能跑在设备节点自己的事件循环上:挂载要排到那个循环里,会等到自己。""" + + 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 _load_on_node( + node: Any, + material_uuids: Sequence[str], + site_uuids: Sequence[str | None], + transfer_uuid: str, + timeout: float = 30.0, +) -> None: + """按 transfer 的 load 投影把权威里的物料子树挂到本设备:在设备自己的执行器上跑,阻塞等它完成。 + + 与跨设备转运落到目标设备同一条投影(``node.material_sync``),本地不另起一条挂载逻辑; + 投影期间不回写快照。``transfer_uuid`` 是设备侧的幂等键。 + """ + + from unilabos.client.host.runtime.async_utils import run_node_coroutine + + run_node_coroutine( + node, + node.material_sync( + { + "transfer_uuid": transfer_uuid, + "device_id": str(node.device_id), + "action": "load", + "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 里没有它") + 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 +896,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 +948,30 @@ 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 + 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( - gateway or resolve_materials_gateway(), + resolved_gateway, request, resources, root_extra=( @@ -745,10 +979,20 @@ def create( if node is not None else None ), + placement=placement, + display_name=display_name, + root_position=root_position, ) 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: + 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: @@ -765,52 +1009,109 @@ def assign( *, parent: Any | None = None, slot: Any | None = None, - site: str | None = None, - location: Optional[Dict[str, float]] = None, - timeout: float = 30.0, + site: Any | None = None, + 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 键);None 表示挂到设备自身 - (只登记进 tracker,不做 assign); - - ``slot``:label 或 0-based 数字字符串(如 ``"A1"`` / ``"0"``); - - ``site``:权威 ``ResourceSite`` uuid(与 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 要排到那个执行器上)。 + + 权威答「已在目标位置」时它已经在要放的地方:本设备持有它就什么都不做;没有它(上一次移动在 + 权威里提交了、设备侧投影没做完)就按同一条 load 从权威重建挂上并成功返回,所以重试一次失败的 + assign 会收敛。其它错误照常抛出。 """ items = resources if isinstance(resources, (list, tuple)) else [resources] resource_uuids = [material_uuid(item) for item in items] - if parent is None: - bind_parent_id = str(node.device_id) + gw = gateway or _node_gateway(node) + _require_off_node_executor(node, "materials.assign") + if parent is None or parent is node: + 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) + 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)} 个" ) - other: Dict[str, Any] = {} - if slot is not None and str(slot).strip() != "": - other["slot"] = str(slot) - if site: - other["site"] = str(site) - 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]] = [] + + def move(source: str, group: List[str]) -> None: + 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 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, + "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( diff --git a/unilabos/resources/objects/resource.py b/unilabos/resources/objects/resource.py index 8fc6e35bde..13a3a476a1 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/plr_additional_res_reg.py b/unilabos/resources/plr_additional_res_reg.py index 500dcc00f2..20bf8eaca9 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 e66ff0e5f1..639ad375b3 100644 --- a/unilabos/resources/resource_tracker.py +++ b/unilabos/resources/resource_tracker.py @@ -15,10 +15,11 @@ 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 -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, @@ -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": { @@ -1241,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( @@ -2032,6 +2059,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) diff --git a/unilabos/server/api/envelope.py b/unilabos/server/api/envelope.py index b43bcf88a1..c44057ca9b 100644 --- a/unilabos/server/api/envelope.py +++ b/unilabos/server/api/envelope.py @@ -287,6 +287,8 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "invalid_material_source", "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({ @@ -324,6 +326,10 @@ def _detail_message(detail: Any) -> tuple[str, Any]: "debug_task_conflict", "device_action_not_allowed", "preflight_failed", + # 物料参数按库位绑定失败(库位不存在 / 为空 / 模板不符,细节在 error.details) + "material_site_invalid", + # 库位参数按所属物料选择的写法不对(没有 Material.site 关系、放入物料不确定……,细节在 error.details) + "site_selection_invalid", }) diff --git a/unilabos/server/api/materials/core.py b/unilabos/server/api/materials/core.py index c1fc9558fe..826754028e 100644 --- a/unilabos/server/api/materials/core.py +++ b/unilabos/server/api/materials/core.py @@ -15,7 +15,9 @@ from __future__ import annotations +import asyncio import json +import re from typing import Literal, Optional from fastapi import APIRouter, FastAPI, Header, HTTPException, Query, Request @@ -28,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): @@ -69,6 +72,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 +212,52 @@ 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 快照后, + # 首连再追平账本会吞掉这期间的创建/移动。基线与纪元在共享账本轮询的线程上读, + # 不占默认线程池;之后的变化也由那条线程统一读出、分给所有连接,不按连接重复读。 + 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 + 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,21 +270,58 @@ 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" + + 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 - yield "retry: 3000\n: connected\n\n" - # 停机开始就主动结束:浏览器按 retry 自动重连,uvicorn 不必超时取消 - while not shutting_down() and not await request.is_disconnected(): - rows = service.changes(after_sequence=cursor, limit=500) - 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 + nonlocal cursor, epoch + 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/materials/inventory.py b/unilabos/server/api/materials/inventory.py index 51012d3003..bea548437d 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 @@ -18,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, @@ -38,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) @@ -69,6 +88,21 @@ 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"}``)引用的库位,以及库位参数按所属物料选择 + (``{"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: api_error = to_api_error(exc, RESOURCE) return api_error.code if api_error is not None else INTERNAL_ERROR @@ -148,6 +182,15 @@ 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``、类别);库位参数按所属物料选择(``owners``)时所属物料下接受放入物料的库位 + 与此刻能用的库位。只读不写;绑定 / 选择成功与否由工作流服务与调度器判定。""" + + 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: return {"commands": commands.processed(limit=limit)} @@ -316,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/materials/resources.py b/unilabos/server/api/materials/resources.py index 9960811cdc..93bf4401a2 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="只要空容器:不含设备、台面与载架,且没有内容登记、也没有数量大于 0 的内容物"), ) -> 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/api/runtime/events.py b/unilabos/server/api/runtime/events.py index df9eb90ab3..cadb874fb4 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,13 +12,22 @@ 保留窗口边界与事件页在同一 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`` 协议不变。 +所有通知都是 ``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 @@ -31,10 +40,10 @@ from fastapi import APIRouter, Header, Request from fastapi.responses import Response, StreamingResponse -from unilabos.protocol.runtime.logs import RuntimeLogNotice 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``) @@ -66,27 +75,29 @@ def to_v1_event(event: Dict[str, Any]) -> Dict[str, Any]: 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, ): 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 - 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): + def woken() -> None: + # 写入器线程上调用:只把唤醒交回事件循环 if not closed: - loop.call_soon_threadsafe(put, notice) + try: + loop.call_soon_threadsafe(wake.set) + except RuntimeError: # 事件循环已关闭 + pass - release = log_notices.subscribe(receive) - next_workflow = 0.0 + release = appended.subscribe(woken) + next_poll = 0.0 heartbeat = time.monotonic() + 15 try: yield "retry: 3000\n: connected\n\n" @@ -95,8 +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 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 @@ -110,22 +121,23 @@ 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() @@ -156,14 +168,31 @@ 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 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, ), 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/api/runtime/scheduling_v1.py b/unilabos/server/api/runtime/scheduling_v1.py index 292407c8c2..a56ed1acab 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/api/runtime/workflow.py b/unilabos/server/api/runtime/workflow.py index 46b405a638..393f61e885 100644 --- a/unilabos/server/api/runtime/workflow.py +++ b/unilabos/server/api/runtime/workflow.py @@ -298,12 +298,18 @@ 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)。" + "库位参数(SiteSlot)可以给 {\"owner_uuid\": 所属物料 uuid}:调度器在任务准入时按库位序号选一个接受放入物料的空库位、" + "经入口预留占住并冻结(写法不对时 error.code=site_selection_invalid)")) #: V1 任务优先级:normal 普通任务,high 高优先级任务(随任务持久化,排序由调度器负责) priority: Literal["normal", "high"] = "normal" #: V1 库存绑定:建任务时落到冻结计划里对应的库存需求,决定预留哪份试剂 / 当前内容物 @@ -343,7 +349,10 @@ 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 同建任务);库位参数按所属物料选择({\"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) @@ -518,7 +527,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 +539,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 图根列表每次从完整图派生(禁用、私有子图的 + # 规则在投影里),供客户端查看。 + projected["inventory_requirements"] = project_inventory_requirements(projected) return definition_graph(projected) def write_payload(body: BaseModel) -> Dict[str, Any]: diff --git a/unilabos/server/api/runtime/workflow_definition.py b/unilabos/server/api/runtime/workflow_definition.py index a4a6e84a6b..a415a1b8ca 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/composition.py b/unilabos/server/composition.py index 1740dacf59..7e8822058d 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 b294f600b2..29938b2e52 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) <> ''), @@ -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 13f0edd4e2..c406843617 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/execution_composition.py b/unilabos/server/execution_composition.py index 10673c2be1..d3edc76a90 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/mcp/__init__.py b/unilabos/server/mcp/__init__.py index 54aa32c093..50888104a6 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) diff --git a/unilabos/server/mcp/guide.py b/unilabos/server/mcp/guide.py index 323ac034b9..2b43e2328e 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/scheduler/service.py b/unilabos/server/scheduler/service.py index dbdfe4b2f2..e39efb3dca 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 @@ -2058,7 +2214,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 +3373,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 +3410,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 +3862,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: @@ -3894,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/driver_packages.py b/unilabos/server/services/driver_packages.py index c50a00c297..7c5a0fea90 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/server/services/materials/core.py b/unilabos/server/services/materials/core.py index f6a39be145..880cc5afe4 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 @@ -33,7 +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_BACKEND, + ACTOR_GRAPH, + ACTOR_HUMAN, ChemicalSummary, InventoryAllocation, InventoryLotCorrection, @@ -54,6 +56,7 @@ MaterialDeviceSync, MaterialIdentityRead, MaterialMove, + MaterialPlacement, MaterialNodeCreate, MaterialPatch, MaterialDelta, @@ -80,6 +83,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, @@ -1385,6 +1389,16 @@ def material_sanity_facts( return material_sanity_facts(self, material_uuids, reservation_uuid=reservation_uuid) + 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, owners=owners) + def _candidate_inventory_lots( self, requirement: InventoryRequirement, @@ -2143,6 +2157,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, *, @@ -2153,8 +2206,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, @@ -2165,6 +2219,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, @@ -2175,9 +2236,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 @@ -2189,6 +2252,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( @@ -2200,6 +2265,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() @@ -2217,12 +2283,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]] @@ -2275,6 +2347,7 @@ def ensure_links( if key not in _RESERVED }, timestamp=timestamp, + actor_type=ACTOR_GRAPH, ) stats[outcome] += 1 return stats @@ -2284,7 +2357,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}" @@ -2298,11 +2372,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( @@ -2409,6 +2492,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]] = {} @@ -2429,6 +2513,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", @@ -2497,7 +2583,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 = [ @@ -2560,7 +2648,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, @@ -2706,6 +2794,22 @@ def apply(timestamp: int) -> _Applied[MaterialTreeRead]: for node in value.nodes if node.parent_client_ref is None ) + 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) @@ -2713,6 +2817,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, @@ -2860,6 +2989,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, @@ -3049,8 +3180,8 @@ def _site_holder_uuids( ``holder.location`` 生成 Site 位姿)。权威里按同一结构识别,规则全部满足才算: - 所属物料不是设备,至少有一个 Site; - - 直接子物料里,除去占着它自己 Site 的(台面型 Site 的物料直接挂在台面下, - 旧版 transfer 的坏树也是这样)和 ``exclude``(正在移动的物料),剩下的与 + - 直接子物料里,除去占着它自己 Site 的(台面型 Site 的物料直接挂在台面下) + 和 ``exclude``(正在移动的物料),剩下的与 Site 一一对应:数量相同,按顺序第 k 个子物料对应第 k 个 Site; - 每个这样的子物料没有自己的 Site、最多一个子物料,且位置就是对应 Site 的位置。 @@ -3122,52 +3253,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)与活动入口预留。""" @@ -3190,6 +3275,110 @@ 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 _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``: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,不受影响。 + """ + + 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 tree(material_uuid, resource_type) AS ( + SELECT material_uuid, resource_type FROM material WHERE material_uuid = ? + UNION ALL + 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.material_uuid, m.resource_id, m.resource_type, m.config_json + FROM material m JOIN tree USING (material_uuid) + """, + (root.material_uuid, root.material_uuid), + ).fetchall() + 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 = {} + 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"设备 {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: """新父物料不能是物料自己或它的后代(V1 6004);库位所属物料是新父物料时同样适用。""" @@ -3205,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']}" @@ -3280,14 +3484,14 @@ 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 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 @@ -3345,11 +3549,8 @@ 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) + self._assert_plr_tree_rules([value.material_uuid]) if destination is not None: destination_changed_at = max(timestamp, destination.updated_at_ms) @@ -3521,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": @@ -3839,7 +4045,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] = [] @@ -4113,6 +4319,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): diff --git a/unilabos/server/services/materials/graph.py b/unilabos/server/services/materials/graph.py index cc4eb83eac..647abaeb5d 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") diff --git a/unilabos/server/services/materials/ingress.py b/unilabos/server/services/materials/ingress.py index 58fe67e970..5390d622ea 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/inventory_commands.py b/unilabos/server/services/materials/inventory_commands.py index 011c3b4d17..0d7ad78a5d 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',?,?,?)", @@ -780,7 +788,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/ledger_watch.py b/unilabos/server/services/materials/ledger_watch.py new file mode 100644 index 0000000000..55c766a07f --- /dev/null +++ b/unilabos/server/services/materials/ledger_watch.py @@ -0,0 +1,239 @@ +"""物料账本的共享轮询:一个物料权威一条专用线程,所有 SSE 连接共用它的结果。 + +``/api/v1/events`` 的 ``material.changed``(由权威进程的前端通知写入器订阅,合并后写进 ``frontend_event``) +与 ``/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: Optional[int], deliver: Deliver) -> Callable[[], None]: + """从 ``after`` 之后开始收到每一批账本变化;``after`` 为 None 时从共享进度开始。返回取消订阅的函数。""" + + 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(self._latest if after is None else 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"] diff --git a/unilabos/server/services/materials/material_io.py b/unilabos/server/services/materials/material_io.py index 5bbbc26ccf..46fcbbc100 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 f60916e465..671bb67042 100644 --- a/unilabos/server/services/materials/resource_contract.py +++ b/unilabos/server/services/materials/resource_contract.py @@ -18,10 +18,9 @@ InventoryMutation, MaterialDataWrite, MaterialDelete, - MaterialIdentityWrite, MaterialMove, - MaterialNodeCreate, MaterialPatch, + MaterialPlacement, MaterialPosition, MaterialTreeCreate, ResourceTemplateRead, @@ -34,6 +33,7 @@ MaterialNoChangeError, MaterialNotFoundError, MaterialsService, + MaterialsServiceError, MaterialValidationError, ) @@ -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,39 @@ 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 的有效登记仍算非空),也没有数量大于 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 ?") @@ -550,60 +622,49 @@ 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()) - tree = MaterialTreeCreate(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.resource_type or "Resource", - barcode=barcode, - template_name=template.name, - config=_mapping(values.get("config")), - meta_data=_mapping(values.get("meta_data")), - ), - position=position, - )]) + # 放入库位 = 挂到库位的所属物料并占用它;只给父物料 = 只落父子关系。与建树同一事务(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 = 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: - 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"] = [] @@ -613,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,) @@ -911,13 +1032,61 @@ 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 + # 空值(``?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) + 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 +1117,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} diff --git a/unilabos/server/services/materials/site_admission.py b/unilabos/server/services/materials/site_admission.py new file mode 100644 index 0000000000..0e76fbb80f --- /dev/null +++ b/unilabos/server/services/materials/site_admission.py @@ -0,0 +1,166 @@ +"""任务准入时读的库位事实(调度权威的工作流服务 / 调度器消费,只读不写、不做判定)。 + +两种按库位的写法在准入时解析成普通参数: + +- 物料参数按库位绑定(``{"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, 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: + 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_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": [...]}``。 + + - ``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 + + 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, "owners": [_owner_facts(service, request) for request in owners]} + finally: + if not nested: + conn.rollback() + + +__all__ = ["acceptable_owner_sites", "occupant_facts", "site_accepts_material", "site_admission_facts"] diff --git a/unilabos/server/services/materials/store.py b/unilabos/server/services/materials/store.py index 99bc1e08bc..cb10fc335a 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 @@ -909,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: @@ -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]: diff --git a/unilabos/server/services/runtime/devices.py b/unilabos/server/services/runtime/devices.py index 4349d185fa..9cc814b8ed 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: diff --git a/unilabos/server/services/runtime/workflow/definition_edit.py b/unilabos/server/services/runtime/workflow/definition_edit.py index 21e7c72fa2..b7727d7ad1 100644 --- a/unilabos/server/services/runtime/workflow/definition_edit.py +++ b/unilabos/server/services/runtime/workflow/definition_edit.py @@ -2,15 +2,20 @@ from __future__ import annotations +import json +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, 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): @@ -224,59 +229,71 @@ 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: + """节点自己或任一祖先(分组 / 循环 / 组合调用)被禁用:不进执行计划,需求不预留、不列出。""" + + 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]: @@ -297,6 +314,144 @@ 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 _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``;数量先按调度同一规则规范化(``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 "") + 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 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 {} + policy = node.get("execution_policy") if isinstance(node.get("execution_policy"), Mapping) else {} + mode = str(meta.get("inventory_mode") or "task") + try: + normalized = normalize_inventory([dict(item) for item in declared]) + deferred = inventory_deferred(normalized, policy=policy, mode=mode) + except ValueError: + 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 + + +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`` 是不是读图时从节点派生的列表(导出后原样导入的回声)。 + + 派生列表的每一条都是某个节点上声明的需求原条目(``consume_node_uuid`` + ``meta_data.unilab.inventory``), + 只按这一对比较:``requirement_key``、数量、``deferred`` 等投影字段随投影规则(可见性、禁用、重名、 + 规范化)变化,导入时重新派生会和导出时对不上。对不上任何节点条目(手写、改了需求本身)就不是回声。 + 投影字段只读,改了也不生效。 + """ + + if not isinstance(requirements, list): + return False + 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]: """返回本层节点和边,保留子操作合同 pin、具名实参及外部输出接线。""" owners = private_node_owners(graph["nodes"]) @@ -308,14 +463,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 @@ -391,7 +538,11 @@ def restore_private_subgraphs( "create_node", "duplicate_graph", "duplicate_node", + "is_derived_inventory_requirements", + "node_or_ancestor_disabled", "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 d2975bc440..16b007df3c 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/frontend_notices.py b/unilabos/server/services/runtime/workflow/frontend_notices.py new file mode 100644 index 0000000000..636b4f6059 --- /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/material_sites.py b/unilabos/server/services/runtime/workflow/material_sites.py new file mode 100644 index 0000000000..6ae4dae3e4 --- /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 5e5a71e53b..233f702fe7 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 - {""}) @@ -104,6 +106,47 @@ 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}) + # 按所属物料选择的库位参数({"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 d6ea6d6581..02441ea8f7 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, @@ -89,6 +90,10 @@ publication_source_hash, publication_summary, ) +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 ( @@ -100,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 @@ -149,6 +155,8 @@ "工作流模板的角色未能绑定到设备,请在 bindings 中指定", ), "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": ( @@ -361,7 +369,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}" @@ -369,6 +377,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): @@ -1118,31 +1128,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"], @@ -1180,6 +1174,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]: @@ -1477,6 +1506,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]]] = {} @@ -1496,6 +1527,11 @@ 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) + # 按所属物料选择的库位参数在任务准入时由调度器选定;写法不对(没有 Material.site 关系、放入物料不确定、 + # 与所属物料参数不一致)建任务时就拒绝 + self._check_site_selections(plan) try: bind_plan_inventory(plan, bindings, binding_sources) except (ValueError, InventoryBindingUnavailable) as exc: @@ -1543,6 +1579,45 @@ 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 + + @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, *, @@ -1599,6 +1674,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()), @@ -2143,7 +2232,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 +2582,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`` 按字典读取。 @@ -3373,7 +3442,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,16 +3455,26 @@ 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): 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, 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 []), @@ -3401,12 +3483,169 @@ 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, + workflow_unilab=workflow_unilab if isinstance(workflow_unilab, Mapping) else {}, + node_identity=node_identity, + ) 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]], + *, + workflow_unilab: Mapping[str, Any], + node_identity: Mapping[str, str], + ) -> Dict[str, Any]: + """导入的本层图落库:保留作者声明的保留元数据,组合调用按固定的发布修订重新展开,再整图保存。 + + 文件里的保留元数据(``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, + ) + + 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 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): + # 引用设备动作模板的节点:先把注册表投影同步进模板表,图校验才能找到模板 + 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(workflow_uuid): + 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( + workflow_uuid, + invocation=node["uuid"], + child=child, + child_revision=child_revision, + arguments=node.get("param") or {}, + 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"] + 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( + workflow_uuid, + revision=record["revision"], + 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=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( self, registration: Dict[str, Any], 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 0000000000..5b7ad583c3 --- /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 b60fdeddf3..b4cf5039be 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,直到真实终态回报。""" @@ -3837,6 +3875,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/server/services/runtime/workflow/timeline.py b/unilabos/server/services/runtime/workflow/timeline.py index bb4019f5cf..17cb89aee0 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"] diff --git a/unilabos/server/services/runtime/workflow/value_schema.py b/unilabos/server/services/runtime/workflow/value_schema.py index 81bd4df689..d1604b7ee6 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 OWNER_UUID_KEY, SITE_UUID_KEY, owner_reference, 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: @@ -155,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: 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 99980a8a67..5421b701f9 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 186b3081bb..52718ba3c8 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 ff6b1db41e..53bf0fd43b 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 615a2ec671..be1892afef 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 d57d4b66dc..923fa00b67 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 1995bb76e2..5791717bcd 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 831e445455..5e6070ccdd 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 25e9b849af..659c411307 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 1191cd587d..546b0dfb8d 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 e340028d04..80b8013c2d 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 983b55257a..7c1f952fe4 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 ae83181628..dd62e9336a 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 606f6b7cc6..2458a902a0 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 e92684b5c2..3f84f585bb 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 8d2f5d135b..b8cdf697d6 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 a114fb8b2e..07cfbaf41d 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 25095caa08..cc3a09d9cd 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 2f7f37676e..1afba7b176 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 7f0c803e90..7a1de5e541 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 53d8d9c368..6d130d8fdb 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 1e3f67e367..04906ab08f 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 06e75ae98f..05e5f1ea1d 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 75ab58f540..0c812f21ab 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 5d58d2cbbf..c497e7bfa9 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 c451212017..504c284667 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 1d0c9ccb46..5ae28aa4be 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, diff --git a/unilabos/utils/environment_check.py b/unilabos/utils/environment_check.py index a561ee063d..645e8a6560 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 diff --git a/unilabos/utils/import_manager.py b/unilabos/utils/import_manager.py index 3b76b82ce2..d7bc08f182 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 diff --git a/unilabos/utils/log_notices.py b/unilabos/utils/log_notices.py index c98d193fe7..69cdcd61bb 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