From 48725430a875343acac2de7623e355401e8fa332 Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Thu, 3 Dec 2026 00:11:29 +0800 Subject: [PATCH 1/2] fix(entity): resolve authored site tracking --- docs/sphinx/source/changelog.md | 24 +++- .../2-contracts/1-env_contract.md | 7 +- .../2-contracts/1-env_contract.md | 6 +- src/unilab/base/backend_factory.py | 7 ++ src/unilab/base/scene.py | 118 +++++++++++++++++- src/unilab/envs/manager_based_rl_env.py | 17 ++- tests/base/test_entity_site_state.py | 61 ++++++++- tests/base/test_mjwarp_site_state.py | 38 ++++++ 8 files changed, 260 insertions(+), 18 deletions(-) diff --git a/docs/sphinx/source/changelog.md b/docs/sphinx/source/changelog.md index 982562424..bb9da1a1c 100644 --- a/docs/sphinx/source/changelog.md +++ b/docs/sphinx/source/changelog.md @@ -28,9 +28,10 @@ PyPI 版本变更与未发布变更;发布日期采用 PyPI 上传日期。完 `SceneTensorReadPlan.site_tensor_view` returns the phase view, and Manager environments publish every declared site automatically. Entities without sites return empty tensors, and sites owned by the static world body keep a - constant pose with zero velocity. Declaring `site_names` keeps the full - named-body tracking request on MuJoCo and MJWarp; an explicit - `SceneCfg.tracked_body_names` that omits a site's owning body fails closed + constant pose with zero velocity. Declaring `site_names` tracks the resolved + dynamic owning bodies on MuJoCo and MJWarp when the authored model is + available; an explicit `SceneCfg.tracked_body_names` that omits a site's + owning body fails closed at read-plan compilation ([#2673](https://github.com/Motphys/UniLab/issues/2673)). `EntityData` 现在为声明了 `site_names` 的实体发布与 mjlab 对齐的 site 状态: @@ -42,13 +43,26 @@ PyPI 版本变更与未发布变更;发布日期采用 PyPI 上传日期。完 `SceneTensorReadSpec.site_names` 发起该发布,`SceneTensorReadPlan.site_tensor_view` 返回 phase 视图,Manager 环境会自动发布所有已声明的 site。未声明 site 的实体 返回空张量;挂在静态 world body 上的 site 保持常量位姿和零速度。声明 - `site_names` 会在 MuJoCo 与 MJWarp 上保留完整的命名 body 跟踪请求;显式的 - `SceneCfg.tracked_body_names` 若漏掉某个 site 的所属 body,则在 read plan + `site_names` 时,MuJoCo 与 MJWarp 在 authored 模型可用的情况下只跟踪解析出的 + 动态所属 body;显式的 `SceneCfg.tracked_body_names` 若漏掉某个 site 的所属 + body,则在 read plan 编译期 fail closed ([#2673](https://github.com/Motphys/UniLab/issues/2673))。 ### Fixed / 修复 +- Manager-based MuJoCo and MJWarp scenes now resolve declared sites from authored + models before backend construction, tracking only their dynamic parent bodies + instead of every named body when resolution is available. Fixed variants whose + world-owned static site frames differ are rejected with the variant, site, and + changed fields identified instead of publishing one canonical pose to every + environment ([#2675](https://github.com/Motphys/UniLab/issues/2675)). + Manager-Based 的 MuJoCo 与 MJWarp 场景现在会在后端构造前从 authored 模型解析 + 声明的 site;解析可用时只跟踪其动态所属 body,不再跟踪全部命名 body。若 fixed + variants 中挂在 world body 上的静态 site 本地帧不同,则报错并指明 variant、 + site 与变化字段,不再向所有环境发布同一个 canonical 位姿 + ([#2675](https://github.com/Motphys/UniLab/issues/2675))。 + - Refreshed the bilingual documentation against the current CLI, owner configs, backend support evidence, training/runtime behavior, Sim2Sim and Sim2Real contracts, and extension workflows. Corrected stale commands, dependency diff --git a/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md b/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md index 89e6571f6..ea8f8ec81 100644 --- a/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md +++ b/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md @@ -65,7 +65,12 @@ carrier; they do not replace the `obs` plus optional `critic` semantics. is compiled the carrier is zero-valued so Manager construction can probe term shapes; afterwards an unrefreshed phase fails closed. Entities without sites return empty tensors, and sites owned by the static world body keep a constant - pose with zero velocity. + pose with zero velocity. On MuJoCo and MJWarp, the Manager cold-compiles + authored model sources to track only dynamic site-owning bodies in addition to + the root and explicitly declared bodies; sources that cannot be resolved before + materialization retain full named-body tracking. Because the public local-frame + contract is canonical, fixed variants with different world-owned static site + poses are rejected with the variant, site, and changed fields identified. ## Evidence In Repo diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md index 7c3dc3b46..549b51581 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md @@ -57,7 +57,11 @@ Env 生命周期由 `src/unilab/base/base.py` 与 `src/unilab/base/torch_env.py` `SceneTensorReadPlan.site_tensor_view` 返回 phase 视图。read plan 编译之前 carrier 为零值,供 Manager 构造期探测 term 形状;编译之后未刷新的 phase 会 fail closed。未声明 site 的 entity 返回空张量,挂在静态 world body 上的 - site 保持常量位姿和零速度。 + site 保持常量位姿和零速度。在 MuJoCo 与 MJWarp 上,Manager 在冷路径编译 + authored 模型源,除 root 与显式声明的 body 外只跟踪动态 site 的所属 body; + 无法在物化前解析的模型源仍保留完整命名 body 跟踪。由于公开的本地帧契约只有 + canonical 值,fixed variants 中挂在 world body 上的静态 site 位姿不同时会 + fail closed,错误信息指明 variant、site 与变化字段。 ## 仓库中的证据 diff --git a/src/unilab/base/backend_factory.py b/src/unilab/base/backend_factory.py index 104313e56..7c9c0815a 100644 --- a/src/unilab/base/backend_factory.py +++ b/src/unilab/base/backend_factory.py @@ -338,7 +338,14 @@ def create_backend( ) if scene.entity_variant is not None: paths.extend(source.model_file for source in scene.entity_variant.plan.variants) + fixed_variant_plan = getattr(scene, "fixed_variant_plan", None) + if fixed_variant_plan is not None: + paths.extend(source.model_file for source in fixed_variant_plan.variants) ensure_robot_assets_for_paths(list(dict.fromkeys(paths))) + if backend_type in SELECTIVE_TRACKED_BODY_BACKENDS and fixed_variant_plan is not None: + from unilab.base.scene import validate_fixed_variant_site_frames + + validate_fixed_variant_site_frames(scene) # MotrixSim GPU owns its per-world contact storage; translate the owner # capacities into the adapter's constructor names and drop them for every # other backend so they never leak into an unrelated constructor. diff --git a/src/unilab/base/scene.py b/src/unilab/base/scene.py index b551a421f..69f7a9b1b 100644 --- a/src/unilab/base/scene.py +++ b/src/unilab/base/scene.py @@ -4,6 +4,7 @@ from collections.abc import Mapping from dataclasses import dataclass, field +from typing import TYPE_CHECKING import numpy as np from unisim.dr.types import FixedVariantLayout, FixedVariantPlan, ModelSourceDescriptor @@ -17,7 +18,10 @@ resolve_scene_fragment_path, ) -from unilab.base.entity import EntityCfg +from unilab.base.entity import EntityCfg, NamesCfg + +if TYPE_CHECKING: + from unisim.ray_query import RaySiteFrameDescription @dataclass @@ -32,9 +36,10 @@ class SceneCfg(_UniSimSceneCfg): inject named body-state sensors. ``None`` preserves the backend's existing full request; EntityCfg selectors remain the source of truth for Manager body reads. Concrete (non-pattern) EntityCfg selectors may still derive the - default selection on MuJoCo and MJWarp for backward compatibility, unless an - entity declares ``site_names``: site owning bodies resolve only after - backend materialization, so the full request is kept. + default selection on MuJoCo and MJWarp for backward compatibility. Declared + sites contribute their dynamic owning bodies when the authored model can be + compiled before backend materialization; composed or unavailable sources + retain the full request. """ model_file: str = "" @@ -111,9 +116,114 @@ def __post_init__(self) -> None: super().__post_init__() +def _load_authored_site_frames( + model_file: str, site_names: tuple[str, ...] +) -> tuple["RaySiteFrameDescription", ...]: + import mujoco + from unisim.backend.ray_scene import ray_site_frames_from_mujoco_model + + model_type = getattr(mujoco, "MjModel") + model = ( + model_type.from_binary_path(model_file) + if model_file.lower().endswith(".mjb") + else model_type.from_xml_path(model_file) + ) + frames: tuple[RaySiteFrameDescription, ...] = ray_site_frames_from_mujoco_model( + model, site_names + ) + return frames + + +def resolve_authored_site_frames( + scene: SceneCfg, site_names: NamesCfg +) -> tuple["RaySiteFrameDescription", ...] | None: + """Resolve declared sites from authored models before backend construction. + + The first fixed variant is the parent-layout reference. World-owned static + frames must be identical across every variant because the public backend + frame contract exposes only one canonical local frame. ``None`` means that + the source cannot be compiled or does not contain the declared sites, so a + caller must retain its materialized-backend resolution path. + """ + if not site_names: + return () + if isinstance(site_names, str): + return None + names = tuple(site_names) + plan = scene.fixed_variant_plan + sources = ( + tuple(variant.model_file for variant in plan.variants) + if plan is not None + else (scene.model_file,) + ) + if any(not source for source in sources): + return None + resolved: list[tuple[RaySiteFrameDescription, ...]] = [] + for source in sources: + try: + resolved.append(_load_authored_site_frames(source, names)) + except (ImportError, OSError, ValueError): + return None + + mismatches: list[str] = [] + canonical = resolved[0] + for variant_index, frames in enumerate(resolved[1:], start=1): + for reference, candidate in zip(canonical, frames, strict=True): + if reference.body_name != "world" and candidate.body_name != "world": + continue + fields = [] + if reference.body_name != candidate.body_name: + fields.append("site_bodyid") + if not np.array_equal(reference.pos, candidate.pos): + fields.append("site_pos") + if not ( + np.array_equal(reference.quat, candidate.quat) + or np.array_equal(reference.quat, -candidate.quat) + ): + fields.append("site_quat") + if fields: + mismatches.append( + f"variant {variant_index} ({sources[variant_index]!r}) changes static " + f"site {reference.site_name!r} ({', '.join(fields)})" + ) + if mismatches: + raise ValueError( + "Fixed variants must keep world-owned static site frames identical because " + "SimBackend.get_ray_site_frames exposes one canonical local frame: " + + "; ".join(mismatches) + ) + return canonical + + +def resolve_site_parent_body_names(scene: SceneCfg, site_names: NamesCfg) -> tuple[str, ...] | None: + """Return dynamic site-owning bodies in declaration order, or ``None`` if unresolved.""" + frames = resolve_authored_site_frames(scene, site_names) + if frames is None: + return None + return tuple(dict.fromkeys(frame.body_name for frame in frames if frame.body_name != "world")) + + +def validate_fixed_variant_site_frames(scene: SceneCfg) -> None: + """Fail closed when declared static sites differ between fixed model variants.""" + if scene.fixed_variant_plan is None: + return + for entity_name, entity in scene.entities.items(): + if not isinstance(entity, EntityCfg) or not entity.site_names: + continue + if resolve_authored_site_frames(scene, entity.site_names) is None: + raise NotImplementedError( + f"Entity '{entity_name}' fixed-variant site frames cannot be validated from " + "the authored model sources; declare sites in complete MJCF/MJB variant " + "sources so static per-world poses cannot be published incorrectly" + ) + + __all__ = [ "SceneCfg", "TerrainSceneCfg", + "resolve_authored_site_frames", "resolve_scene_default_qpos", "resolve_scene_fragment_path", + "resolve_site_parent_body_names", + "validate_fixed_variant_site_frames", ] diff --git a/src/unilab/envs/manager_based_rl_env.py b/src/unilab/envs/manager_based_rl_env.py index 76104af31..a32ef4af0 100644 --- a/src/unilab/envs/manager_based_rl_env.py +++ b/src/unilab/envs/manager_based_rl_env.py @@ -50,7 +50,11 @@ from unilab.base.reset_selection import ResetSelection from unilab.base.reset_selectors import ResetMaskBuffer, resolve_reset_env_ids from unilab.base.reset_state import ResetStateTransaction -from unilab.base.scene import SceneCfg, resolve_scene_default_qpos +from unilab.base.scene import ( + SceneCfg, + resolve_scene_default_qpos, + resolve_site_parent_body_names, +) from unilab.base.torch_env import TorchEnv, TorchEnvState from unilab.base.variants import ( build_fixed_variant_plan, @@ -357,11 +361,14 @@ def _resolve_backend_entity_contract( tracked_body_names = None elif tracked_body_names is not None: tracked_body_names.extend(selector_names) - if isinstance(entity_cfg, EntityCfg) and entity_cfg.site_names: - # Site owning bodies are resolved by the materialized backend, so a - # declared site namespace keeps the full named-body request. + if entity_cfg.site_names: body_state_requested = True - tracked_body_names = None + if tracked_body_names is not None and backend_type in SELECTIVE_TRACKED_BODY_BACKENDS: + site_parents = resolve_site_parent_body_names(cfg.scene, entity_cfg.site_names) + if site_parents is None: + tracked_body_names = None + else: + tracked_body_names.extend(site_parents) if not root_entities: raise ValueError( diff --git a/tests/base/test_entity_site_state.py b/tests/base/test_entity_site_state.py index c291891b3..fa2ab15ff 100644 --- a/tests/base/test_entity_site_state.py +++ b/tests/base/test_entity_site_state.py @@ -7,6 +7,7 @@ from __future__ import annotations +from pathlib import Path from typing import Any, cast import mujoco @@ -15,8 +16,10 @@ import torch from unisim.backend.base import SimBackend from unisim.backend.mujoco.backend import MuJoCoBackend +from unisim.dr.types import FixedVariantLayout, FixedVariantPlan, ModelSourceDescriptor import unilab.envs.manager_based_rl_env as manager_env_module +from unilab.base.backend_factory import create_backend from unilab.base.entity import EntityCfg, EntityScene, SceneTensorReadSpec from unilab.base.scene import SceneCfg from unilab.envs import ManagerBasedRlEnv, make_manager_based_rl_env, mdp @@ -310,13 +313,67 @@ def _proxy(backend: SimBackend) -> SimBackend: return cast(SimBackend, _NoSiteFramesBackend(backend)) -def test_declared_sites_keep_the_full_tracked_body_request() -> None: +def test_declared_sites_track_only_their_dynamic_parent_bodies(tmp_path: Path) -> None: cfg = site_env_cfg() - assert manager_env_module._resolve_backend_entity_contract(cfg)[2] is None + assert cfg.scene is not None + model_file = tmp_path / "site_frames_with_unused_body.xml" + model_file.write_text( + MODEL_FILE.read_text().replace( + " ", ' \n ' + ) + ) + cfg.scene.model_file = str(model_file) + + assert manager_env_module._resolve_backend_entity_contract(cfg)[2] == ( + "base", + "link2", + "link1", + ) cfg.scene.tracked_body_names = ("base", "link2") assert manager_env_module._resolve_backend_entity_contract(cfg)[2] == ("base", "link2") +def test_declared_sites_fall_back_when_authored_model_is_unavailable(tmp_path: Path) -> None: + cfg = site_env_cfg() + assert cfg.scene is not None + cfg.scene.model_file = str(tmp_path / "missing.xml") + + assert manager_env_module._resolve_backend_entity_contract(cfg)[2] is None + + +def test_fixed_variant_static_site_mismatch_fails_closed(tmp_path: Path) -> None: + source = MODEL_FILE.read_text() + canonical = tmp_path / "v0.xml" + changed = tmp_path / "v1.xml" + canonical.write_text(source) + changed.write_text( + source.replace( + ' None: env = make_manager_based_rl_env(site_env_cfg(), num_envs=NUM_ENVS, backend_type="mujoco") try: diff --git a/tests/base/test_mjwarp_site_state.py b/tests/base/test_mjwarp_site_state.py index da7e291c9..6c56a6dfd 100644 --- a/tests/base/test_mjwarp_site_state.py +++ b/tests/base/test_mjwarp_site_state.py @@ -7,6 +7,7 @@ from __future__ import annotations import sys +from pathlib import Path from typing import Any import mujoco @@ -14,6 +15,7 @@ import pytest import torch from unisim.backend.mujoco.backend import MuJoCoBackend +from unisim.dr.types import FixedVariantLayout, FixedVariantPlan, ModelSourceDescriptor from unilab.base.backend_factory import create_backend from unilab.base.entity import EntityCfg, EntityScene, SceneTensorReadSpec @@ -145,6 +147,42 @@ def forbidden_host_read(self: torch.Tensor) -> torch.Tensor: backend.close() +def test_mjwarp_fixed_variant_static_site_mismatch_fails_closed(tmp_path: Path) -> None: + _require_cuda_mjwarp() + source = MODEL_FILE.read_text() + canonical = tmp_path / "v0.xml" + changed = tmp_path / "v1.xml" + canonical.write_text(source) + changed.write_text( + source.replace( + ' None: _require_cuda_mjwarp() scene_cfg = _scene_cfg(("tip", "palm")) From 95878833f0475fb71c8464679692c59f2217f4d8 Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Thu, 3 Dec 2026 12:12:04 +0800 Subject: [PATCH 2/2] fix(entity): validate all variant site frames --- docs/sphinx/source/changelog.md | 8 +- .../2-contracts/1-env_contract.md | 4 +- .../2-contracts/1-env_contract.md | 2 +- src/unilab/base/backend_factory.py | 4 +- src/unilab/base/scene.py | 96 ++++++++++++------- tests/base/test_entity_site_state.py | 76 +++++++++++++-- tests/base/test_mjwarp_site_state.py | 2 +- 7 files changed, 141 insertions(+), 51 deletions(-) diff --git a/docs/sphinx/source/changelog.md b/docs/sphinx/source/changelog.md index bb9da1a1c..d5aa8f319 100644 --- a/docs/sphinx/source/changelog.md +++ b/docs/sphinx/source/changelog.md @@ -53,13 +53,13 @@ PyPI 版本变更与未发布变更;发布日期采用 PyPI 上传日期。完 - Manager-based MuJoCo and MJWarp scenes now resolve declared sites from authored models before backend construction, tracking only their dynamic parent bodies - instead of every named body when resolution is available. Fixed variants whose - world-owned static site frames differ are rejected with the variant, site, and + instead of every named body when resolution is available. Scene and physical-entity + fixed variants whose site frames differ are rejected with the variant, site, and changed fields identified instead of publishing one canonical pose to every environment ([#2675](https://github.com/Motphys/UniLab/issues/2675)). Manager-Based 的 MuJoCo 与 MJWarp 场景现在会在后端构造前从 authored 模型解析 - 声明的 site;解析可用时只跟踪其动态所属 body,不再跟踪全部命名 body。若 fixed - variants 中挂在 world body 上的静态 site 本地帧不同,则报错并指明 variant、 + 声明的 site;解析可用时只跟踪其动态所属 body,不再跟踪全部命名 body。若 scene 或 + physical entity 的 fixed variants 中任意 site 本地帧不同,则报错并指明 variant、 site 与变化字段,不再向所有环境发布同一个 canonical 位姿 ([#2675](https://github.com/Motphys/UniLab/issues/2675))。 diff --git a/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md b/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md index ea8f8ec81..5b51c25ac 100644 --- a/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md +++ b/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md @@ -69,8 +69,8 @@ carrier; they do not replace the `obs` plus optional `critic` semantics. authored model sources to track only dynamic site-owning bodies in addition to the root and explicitly declared bodies; sources that cannot be resolved before materialization retain full named-body tracking. Because the public local-frame - contract is canonical, fixed variants with different world-owned static site - poses are rejected with the variant, site, and changed fields identified. + contract is canonical, scene and physical-entity fixed variants with different + site frames are rejected with the variant, site, and changed fields identified. ## Evidence In Repo diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md index 549b51581..a486f8713 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md @@ -60,7 +60,7 @@ Env 生命周期由 `src/unilab/base/base.py` 与 `src/unilab/base/torch_env.py` site 保持常量位姿和零速度。在 MuJoCo 与 MJWarp 上,Manager 在冷路径编译 authored 模型源,除 root 与显式声明的 body 外只跟踪动态 site 的所属 body; 无法在物化前解析的模型源仍保留完整命名 body 跟踪。由于公开的本地帧契约只有 - canonical 值,fixed variants 中挂在 world body 上的静态 site 位姿不同时会 + canonical 值,scene 或 physical entity 的 fixed variants 中任意 site 本地帧不同时会 fail closed,错误信息指明 variant、site 与变化字段。 ## 仓库中的证据 diff --git a/src/unilab/base/backend_factory.py b/src/unilab/base/backend_factory.py index 7c9c0815a..d995e21b4 100644 --- a/src/unilab/base/backend_factory.py +++ b/src/unilab/base/backend_factory.py @@ -342,7 +342,9 @@ def create_backend( if fixed_variant_plan is not None: paths.extend(source.model_file for source in fixed_variant_plan.variants) ensure_robot_assets_for_paths(list(dict.fromkeys(paths))) - if backend_type in SELECTIVE_TRACKED_BODY_BACKENDS and fixed_variant_plan is not None: + if backend_type in SELECTIVE_TRACKED_BODY_BACKENDS and ( + fixed_variant_plan is not None or scene.entity_variant is not None + ): from unilab.base.scene import validate_fixed_variant_site_frames validate_fixed_variant_site_frames(scene) diff --git a/src/unilab/base/scene.py b/src/unilab/base/scene.py index 69f7a9b1b..9af792846 100644 --- a/src/unilab/base/scene.py +++ b/src/unilab/base/scene.py @@ -134,30 +134,9 @@ def _load_authored_site_frames( return frames -def resolve_authored_site_frames( - scene: SceneCfg, site_names: NamesCfg +def _resolve_authored_site_frames( + sources: tuple[str, ...], names: tuple[str, ...] ) -> tuple["RaySiteFrameDescription", ...] | None: - """Resolve declared sites from authored models before backend construction. - - The first fixed variant is the parent-layout reference. World-owned static - frames must be identical across every variant because the public backend - frame contract exposes only one canonical local frame. ``None`` means that - the source cannot be compiled or does not contain the declared sites, so a - caller must retain its materialized-backend resolution path. - """ - if not site_names: - return () - if isinstance(site_names, str): - return None - names = tuple(site_names) - plan = scene.fixed_variant_plan - sources = ( - tuple(variant.model_file for variant in plan.variants) - if plan is not None - else (scene.model_file,) - ) - if any(not source for source in sources): - return None resolved: list[tuple[RaySiteFrameDescription, ...]] = [] for source in sources: try: @@ -169,8 +148,6 @@ def resolve_authored_site_frames( canonical = resolved[0] for variant_index, frames in enumerate(resolved[1:], start=1): for reference, candidate in zip(canonical, frames, strict=True): - if reference.body_name != "world" and candidate.body_name != "world": - continue fields = [] if reference.body_name != candidate.body_name: fields.append("site_bodyid") @@ -183,18 +160,44 @@ def resolve_authored_site_frames( fields.append("site_quat") if fields: mismatches.append( - f"variant {variant_index} ({sources[variant_index]!r}) changes static " - f"site {reference.site_name!r} ({', '.join(fields)})" + f"variant {variant_index} ({sources[variant_index]!r}) changes site " + f"{reference.site_name!r} ({', '.join(fields)})" ) if mismatches: raise ValueError( - "Fixed variants must keep world-owned static site frames identical because " + "Fixed variants must keep site frames identical because " "SimBackend.get_ray_site_frames exposes one canonical local frame: " + "; ".join(mismatches) ) return canonical +def resolve_authored_site_frames( + scene: SceneCfg, site_names: NamesCfg +) -> tuple["RaySiteFrameDescription", ...] | None: + """Resolve declared sites from authored models before backend construction. + + The first fixed variant is the parent-layout reference. Site frames must be + identical across every variant because the public backend frame contract + exposes only one canonical local frame. ``None`` means that the source + cannot be compiled or does not contain the declared sites, so a caller must + retain its materialized-backend resolution path. + """ + if not site_names: + return () + if isinstance(site_names, str): + return None + plan = scene.fixed_variant_plan + sources = ( + tuple(variant.model_file for variant in plan.variants) + if plan is not None + else (scene.model_file,) + ) + if any(not source for source in sources): + return None + return _resolve_authored_site_frames(sources, tuple(site_names)) + + def resolve_site_parent_body_names(scene: SceneCfg, site_names: NamesCfg) -> tuple[str, ...] | None: """Return dynamic site-owning bodies in declaration order, or ``None`` if unresolved.""" frames = resolve_authored_site_frames(scene, site_names) @@ -204,17 +207,46 @@ def resolve_site_parent_body_names(scene: SceneCfg, site_names: NamesCfg) -> tup def validate_fixed_variant_site_frames(scene: SceneCfg) -> None: - """Fail closed when declared static sites differ between fixed model variants.""" - if scene.fixed_variant_plan is None: + """Fail closed when declared site frames differ between fixed model variants.""" + if scene.fixed_variant_plan is not None: + for entity_name, entity in scene.entities.items(): + if not isinstance(entity, EntityCfg) or not entity.site_names: + continue + if resolve_authored_site_frames(scene, entity.site_names) is None: + raise NotImplementedError( + f"Entity '{entity_name}' fixed-variant site frames cannot be validated from " + "the authored model sources; declare sites in complete MJCF/MJB variant " + "sources so per-world poses cannot be published incorrectly" + ) + return + + binding = scene.entity_variant + if binding is None: return + prefix = binding.target_entity + "/" + sources = tuple(variant.model_file for variant in binding.plan.variants) for entity_name, entity in scene.entities.items(): if not isinstance(entity, EntityCfg) or not entity.site_names: continue - if resolve_authored_site_frames(scene, entity.site_names) is None: + physical_entity = entity.physical_entity + if physical_entity is None and entity.root_body_name and "/" in entity.root_body_name: + physical_entity = entity.root_body_name.split("/", 1)[0] + if physical_entity != binding.target_entity: + continue + if isinstance(entity.site_names, str): + resolved = None + else: + names = tuple(entity.site_names) + if any(not name.startswith(prefix) for name in names): + raise ValueError("mapped logical selectors must belong to their physical entity") + resolved = _resolve_authored_site_frames( + sources, tuple(name[len(prefix) :] for name in names) + ) + if resolved is None: raise NotImplementedError( f"Entity '{entity_name}' fixed-variant site frames cannot be validated from " "the authored model sources; declare sites in complete MJCF/MJB variant " - "sources so static per-world poses cannot be published incorrectly" + "sources so per-world poses cannot be published incorrectly" ) diff --git a/tests/base/test_entity_site_state.py b/tests/base/test_entity_site_state.py index fa2ab15ff..1f36ffc68 100644 --- a/tests/base/test_entity_site_state.py +++ b/tests/base/test_entity_site_state.py @@ -17,6 +17,7 @@ from unisim.backend.base import SimBackend from unisim.backend.mujoco.backend import MuJoCoBackend from unisim.dr.types import FixedVariantLayout, FixedVariantPlan, ModelSourceDescriptor +from unisim.entities import EntityVariantBinding, SceneEntitySpec import unilab.envs.manager_based_rl_env as manager_env_module from unilab.base.backend_factory import create_backend @@ -341,29 +342,84 @@ def test_declared_sites_fall_back_when_authored_model_is_unavailable(tmp_path: P assert manager_env_module._resolve_backend_entity_contract(cfg)[2] is None -def test_fixed_variant_static_site_mismatch_fails_closed(tmp_path: Path) -> None: +@pytest.mark.parametrize( + ("site_name", "authored", "changed"), + [ + ( + "marker", + ' None: source = MODEL_FILE.read_text() canonical = tmp_path / "v0.xml" - changed = tmp_path / "v1.xml" + variant = tmp_path / "v1.xml" canonical.write_text(source) - changed.write_text( - source.replace( - ' None: + source = MODEL_FILE.read_text() + canonical = tmp_path / "v0.xml" + variant = tmp_path / "v1.xml" + canonical.write_text(source) + variant.write_text( + source.replace( + '