Skip to content

Official Codebase of 3DCodeVerse

Python

mimic: one rule set for the plan, the lint and the URDF loader

ziyao7ee00669a97c
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.py
index 88a66e3e..b75dd454 100644
--- a/harness/codeverse/contracts/common.py
+++ b/harness/codeverse/contracts/common.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from collections.abc import Collection
from enum import StrEnum
-from typing import Annotated
+from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field
@@ -185,3 +185,79 @@ class Backends(BaseModel):
# flash (calibration 2026-08-23: std 0.03 vs 0.08-0.12) for ~$0.07 per verdict.
judge: str = "gemini:gemini-3.1-pro-preview"
captioner: str = "gemini:gemini-3.7-flash"
+
+
+# ------------------------------------------------------------------ joint coupling
+#: |multiplier| below this is a coupling that transmits no motion. ONE value: the plan
+#: validator used 1e-9 while the URDF loader and lint used 1e-12, so a coupling the
+#: planner was forbidden to write was one the loader accepted.
+MIMIC_MIN_MULTIPLIER = 1e-9
+
+
+class MimicSpec(BaseModel):
+ """One joint as the coupling rules see it, in whatever vocabulary the caller has.
+
+ ``key`` is the caller's canonical name (the plan folds case and underscores, URDF
+ does not); ``name`` is what its messages should print.
+ """
+
+ model_config = ConfigDict(frozen=True)
+
+ key: str
+ name: str
+ movable: bool
+ target: str | None = None # key of the joint this one follows; None = drives itself
+ multiplier: float = 1.0
+
+
+class MimicIssue(BaseModel):
+ """One broken coupling rule. ``kind`` is what is wrong, ``joint``/``target`` are
+ names as written, ``detail`` carries the joint a cycle closes through."""
+
+ model_config = ConfigDict(frozen=True)
+
+ joint: str
+ kind: Literal["immobile", "zero_multiplier", "self", "unknown_target", "immobile_target", "cycle"]
+ target: str
+ detail: str = ""
+
+
+def mimic_issues(specs: Collection[MimicSpec]) -> list[MimicIssue]:
+ """Every rule a ``<mimic>`` has to satisfy, checked once over the whole joint set.
+
+ Three layers reject the same bad couplings — ``ArticulatedPlan._check_mimics``,
+ ``languages/urdf.lint`` and ``spatial.joints_model.load_urdf`` — and they had three
+ copies of the walk that disagreed on the multiplier floor. The rules live here; each
+ caller renders the issues in its own vocabulary (``ValueError`` / gate finding /
+ ``UrdfError``) and picks the first one when it reports only one.
+ """
+ order = list(specs)
+ by_key = {s.key: s for s in order}
+ out: list[MimicIssue] = []
+ for s in order:
+ if s.target is None:
+ continue
+ if not s.movable:
+ out.append(MimicIssue(joint=s.name, kind="immobile", target=s.target))
+ if abs(s.multiplier) < MIMIC_MIN_MULTIPLIER:
+ out.append(MimicIssue(joint=s.name, kind="zero_multiplier", target=s.target))
+ if s.target == s.key:
+ out.append(MimicIssue(joint=s.name, kind="self", target=s.name))
+ continue
+ src = by_key.get(s.target)
+ if src is None:
+ out.append(MimicIssue(joint=s.name, kind="unknown_target", target=s.target))
+ continue
+ if not src.movable:
+ out.append(MimicIssue(joint=s.name, kind="immobile_target", target=src.name))
+ seen, cur = {s.key}, src
+ while cur.target is not None:
+ if cur.key in seen:
+ out.append(MimicIssue(joint=s.name, kind="cycle", target=s.target, detail=cur.name))
+ break
+ seen.add(cur.key)
+ nxt = by_key.get(cur.target)
+ if nxt is None:
+ break # that joint reports its own unknown target on its own turn
+ cur = nxt
+ return out
diff --git a/harness/codeverse/contracts/plan.py b/harness/codeverse/contracts/plan.py
index a98f60ba..aee00d08 100644
--- a/harness/codeverse/contracts/plan.py
+++ b/harness/codeverse/contracts/plan.py
@@ -16,7 +16,12 @@ from typing import Literal
from pydantic import BaseModel, Field, field_validator, model_validator
-from codeverse.contracts.common import Vec3
+from codeverse.contracts.common import (
+ MIMIC_MIN_MULTIPLIER,
+ MimicSpec,
+ Vec3,
+ mimic_issues,
+)
from codeverse.conventions import to_snake
@@ -188,7 +193,7 @@ class MimicPlan(BaseModel):
@model_validator(mode="after")
def _sane(self) -> MimicPlan:
- if abs(self.multiplier) < 1e-9:
+ if abs(self.multiplier) < MIMIC_MIN_MULTIPLIER:
raise ValueError(f"mimic of {self.joint}: multiplier 0 means the joint cannot move; use type=fixed")
return self
@@ -509,33 +514,27 @@ class ArticulatedPlan(StaticPlan):
return self
def _check_mimics(self) -> None:
- """Every declared coupling must name a joint that exists, moves, and does not
- lead back to the joint that follows it."""
- by_key = {to_snake(j.name): j for j in self.joints}
- for j in self.joints:
- if j.mimic is None:
- continue
- if j.type == "fixed":
- raise ValueError(f"joint {j.name}: a fixed joint cannot mimic {j.mimic.joint}")
- src = by_key.get(to_snake(j.mimic.joint))
- if src is None:
- raise ValueError(
- f"joint {j.name}: mimic joint {j.mimic.joint} is not a joint in this plan; the joints are: "
- f"{', '.join(sorted(x.name for x in self.joints))}")
- if src.type == "fixed":
- raise ValueError(f"joint {j.name}: mimics {src.name}, which is fixed and never moves")
- if to_snake(src.name) == to_snake(j.name):
- raise ValueError(f"joint {j.name}: mimics itself")
- seen, cur = {to_snake(j.name)}, src
- while cur.mimic is not None:
- key = to_snake(cur.name)
- if key in seen:
- raise ValueError(f"joint {j.name}: mimic chain loops back through {cur.name}")
- seen.add(key)
- nxt = by_key.get(to_snake(cur.mimic.joint))
- if nxt is None:
- raise ValueError(f"joint {cur.name}: mimic joint {cur.mimic.joint} is not a joint in this plan")
- cur = nxt
+ """Every declared coupling must name a joint that exists, moves, and does not lead
+ back to the joint that follows it — the rules are ``common.mimic_issues`` so the
+ plan, the lint and the URDF loader cannot drift apart."""
+ by_name = {j.name: j for j in self.joints}
+ issues = mimic_issues([
+ MimicSpec(key=to_snake(j.name), name=j.name, movable=j.type != "fixed",
+ target=to_snake(j.mimic.joint) if j.mimic else None,
+ multiplier=j.mimic.multiplier if j.mimic else 1.0)
+ for j in self.joints])
+ for i in issues:
+ follower = by_name.get(i.joint)
+ wanted = follower.mimic.joint if follower is not None and follower.mimic else i.target
+ raise ValueError({
+ "immobile": f"joint {i.joint}: a fixed joint cannot mimic {wanted}",
+ "zero_multiplier": f"mimic of {wanted}: multiplier 0 means the joint cannot move; use type=fixed",
+ "self": f"joint {i.joint}: mimics itself",
+ "unknown_target": f"joint {i.joint}: mimic joint {wanted} is not a joint in this plan; "
+ f"the joints are: {', '.join(sorted(x.name for x in self.joints))}",
+ "immobile_target": f"joint {i.joint}: mimics {i.target}, which is fixed and never moves",
+ "cycle": f"joint {i.joint}: mimic chain loops back through {i.detail}",
+ }[i.kind])
class ZonePlan(BaseModel):
diff --git a/harness/codeverse/languages/urdf/__init__.py b/harness/codeverse/languages/urdf/__init__.py
index 38f3336f..a72fc718 100644
--- a/harness/codeverse/languages/urdf/__init__.py
+++ b/harness/codeverse/languages/urdf/__init__.py
@@ -19,7 +19,7 @@ import numpy as np
from codeverse.config import Settings, get_settings
from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
-from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.common import ENTRY_FILE, Language, MimicSpec, mimic_issues
from codeverse.contracts.plan import ArticulatedPlan, JointPlan, PartPlan, Plan
from codeverse.conventions import to_snake
from codeverse.languages._ast_lint import (
@@ -191,9 +191,6 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
joint_names: list[str] = []
parent_of: dict[str, str] = {}
- # <mimic> may name a joint declared later in the file, so the whole name set is
- # collected before any joint is linted
- all_joint_names = {el.get("name", "") for el in joints if el.get("name")}
for el in joints:
jname = el.get("name", "")
if not jname:
@@ -202,7 +199,9 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
if jname in joint_names:
out.append(_f(Severity.ERROR, f"duplicate joint name '{jname}'", target=jname, fix="Joint names must be unique."))
joint_names.append(jname)
- _lint_joint(el, jname, link_names, parent_of, out, all_joint_names)
+ _lint_joint(el, jname, link_names, parent_of, out)
+
+ _lint_mimics(joints, out)
# tree structure
children = set(parent_of)
@@ -222,6 +221,58 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
return out, link_names
+def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:
+ """``<mimic>`` couplings, over the whole file: a declaration may name a joint that is
+ written later, and a cycle is only visible on the graph. The RULES are
+ ``contracts.common.mimic_issues`` — shared with the plan validator and the URDF
+ loader, which rejected different multipliers from this lint until 2026-09-03."""
+ # EVERY named joint becomes a spec, coupled or not: an uncoupled joint is what the
+ # coupled ones are allowed to name, and mimic_issues resolves targets against the set
+ # it is given.
+ specs: list[MimicSpec] = []
+ for el in joints:
+ jname = el.get("name", "")
+ if not jname:
+ continue
+ movable = el.get("type", "") != "fixed"
+ mim = el.find("mimic")
+ src = (mim.get("joint") or "").strip() if mim is not None else ""
+ mult = 1.0
+ if mim is not None and not src:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> without joint=", target=jname,
+ fix='<mimic joint="runner_slide" multiplier="1" offset="0"/>'))
+ src = ""
+ elif mim is not None:
+ try:
+ mult = float(mim.get("multiplier", 1) or 1)
+ float(mim.get("offset", 0) or 0)
+ except ValueError:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> multiplier/offset must be numbers", target=jname))
+ src = ""
+ specs.append(MimicSpec(key=jname, name=jname, movable=movable,
+ target=src or None, multiplier=mult))
+ known = sorted({el.get("name", "") for el in joints if el.get("name")})
+ for i in mimic_issues(specs):
+ j, t = i.joint, i.target
+ if i.kind == "immobile":
+ out.append(_f(Severity.ERROR, f"joint '{j}': a fixed joint has nothing to mimic", target=j,
+ fix="give it a type and a limit, or drop the <mimic>"))
+ elif i.kind == "zero_multiplier":
+ out.append(_f(Severity.ERROR, f"joint '{j}': <mimic multiplier=\"0\"> — the joint cannot move",
+ target=j, fix="use type=fixed, or a non-zero multiplier"))
+ elif i.kind == "self":
+ out.append(_f(Severity.ERROR, f"joint '{j}': <mimic> names itself", target=j))
+ elif i.kind == "unknown_target":
+ out.append(_f(Severity.ERROR, f"joint '{j}': <mimic joint=\"{t}\"> names no joint in this file",
+ target=j, fix=f"one of: {', '.join(known)}"))
+ elif i.kind == "immobile_target":
+ out.append(_f(Severity.ERROR, f"joint '{j}': mimics '{t}', which is fixed and never moves", target=j,
+ fix="mimic a joint that moves, or give that joint a type and a limit"))
+ else:
+ out.append(_f(Severity.ERROR, f"joint '{j}': <mimic> chain is a cycle through '{i.detail or j}'",
+ target=j, fix="one joint drives the chain; the rest follow it, directly or in a line"))
+
+
def _lint_link(el: ET.Element, name: str, out: list[GateFinding]) -> None:
if name in RESERVED_LINK_NAMES:
out.append(_f(Severity.ERROR, f"link name '{name}' is reserved by the GLB scene graph (glTF readers use it as the base frame)",
@@ -288,7 +339,7 @@ def _lint_origin(o: ET.Element | None, what: str, target: str, out: list[GateFin
def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: dict[str, str],
- out: list[GateFinding], joint_names: set[str] | None = None) -> None:
+ out: list[GateFinding]) -> None:
jtype = el.get("type", "")
if jtype not in JOINT_TYPES:
out.append(_f(Severity.ERROR, f"joint '{jname}': type '{jtype}' must be one of {JOINT_TYPES}", target=jname,
@@ -353,26 +404,6 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
elif jtype == "continuous" and lim is not None and (lim.get("lower") is not None or lim.get("upper") is not None):
out.append(_f(Severity.WARN, f"joint '{jname}': continuous joints have no lower/upper (ignored)", target=jname,
fix='<limit effort="10" velocity="1"/> or use type=revolute'))
- mim = el.find("mimic")
- if mim is not None:
- src = (mim.get("joint") or "").strip()
- if not src:
- out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> without joint=", target=jname,
- fix='<mimic joint="runner_slide" multiplier="1" offset="0"/>'))
- elif src == jname:
- out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> names itself", target=jname))
- elif joint_names is not None and src not in joint_names:
- out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic joint=\"{src}\"> names no joint in this file",
- target=jname, fix=f"one of: {', '.join(sorted(joint_names))}"))
- if jtype == "fixed":
- out.append(_f(Severity.ERROR, f"joint '{jname}': a fixed joint has nothing to mimic", target=jname,
- fix="give it a type and a limit, or drop the <mimic>"))
- try:
- if abs(float(mim.get("multiplier", 1) or 1)) < 1e-12:
- out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic multiplier=\"0\"> — the joint cannot move",
- target=jname, fix="use type=fixed, or a non-zero multiplier"))
- except ValueError:
- out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> multiplier/offset must be numbers", target=jname))
# ------------------------------------------------------------------ model.py
diff --git a/harness/codeverse/spatial/joints_model.py b/harness/codeverse/spatial/joints_model.py
index 4751c6f7..9ba4a597 100644
--- a/harness/codeverse/spatial/joints_model.py
+++ b/harness/codeverse/spatial/joints_model.py
@@ -24,6 +24,8 @@ from pathlib import Path
import numpy as np
import trimesh
+from codeverse.contracts.common import MIMIC_MIN_MULTIPLIER, MimicIssue, MimicSpec, mimic_issues
+
MOVABLE_TYPES = ("revolute", "prismatic", "continuous")
JOINT_TYPES = MOVABLE_TYPES + ("fixed",)
#: link names that cannot become GLB nodes: glTF readers (trimesh) use ``world`` as the
@@ -324,12 +326,26 @@ def _joint_from_xml(el: ET.Element) -> Joint:
off = float(mim.get("offset", 0.0) or 0.0)
except ValueError as e:
raise UrdfError(f"joint {name}: <mimic> multiplier/offset must be numbers") from e
- if abs(mult) < 1e-12:
+ if abs(mult) < MIMIC_MIN_MULTIPLIER:
raise UrdfError(f"joint {name}: <mimic multiplier=\"0\"> — the joint cannot move; use type=fixed")
j.mimic = Mimic(joint=src, multiplier=mult, offset=off)
return j
+def _mimic_message(issue: MimicIssue, joints: dict[str, Joint]) -> str:
+ """A coupling rule broken by this URDF, in URDF words (rules: contracts.common)."""
+ j, t, kind = issue.joint, issue.target, issue.kind
+ if kind == "immobile":
+ return f"joint {j}: <mimic> on a {joints[j].type} joint has nothing to follow"
+ if kind == "zero_multiplier":
+ return f'joint {j}: <mimic multiplier="0"> — the joint cannot move; use type=fixed'
+ if kind == "unknown_target":
+ return f'joint {j}: <mimic joint="{t}"> names no joint; known: {sorted(joints)}'
+ if kind == "immobile_target":
+ return f"joint {j}: mimics {t!r}, which is {joints[t].type} and never moves"
+ return f"joint {j}: <mimic> chain is a cycle through {(issue.detail or j)!r}"
+
+
def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, load_meshes: bool = True) -> Robot:
"""Parse a URDF file into a :class:`Robot` (strict: raises ``UrdfError``).
@@ -366,26 +382,12 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, lo
if len(set(children)) != len(children):
dup = sorted({c for c in children if children.count(c) > 1})
raise UrdfError(f"links with more than one parent joint: {dup}")
- for j in joints.values():
- if j.mimic is None:
- continue
- if not j.movable:
- raise UrdfError(f"joint {j.name}: <mimic> on a {j.type} joint has nothing to follow")
- src = joints.get(j.mimic.joint)
- if src is None:
- raise UrdfError(f"joint {j.name}: <mimic joint=\"{j.mimic.joint}\"> names no joint; known: {sorted(joints)}")
- if not src.movable:
- raise UrdfError(f"joint {j.name}: mimics {src.name!r}, which is {src.type} and never moves")
- seen = {j.name}
- cur = src
- while cur.mimic is not None:
- if cur.name in seen:
- raise UrdfError(f"joint {j.name}: <mimic> chain is a cycle through {cur.name!r}")
- seen.add(cur.name)
- nxt = joints.get(cur.mimic.joint)
- if nxt is None:
- raise UrdfError(f"joint {cur.name}: <mimic joint=\"{cur.mimic.joint}\"> names no joint")
- cur = nxt
+ for issue in mimic_issues([
+ MimicSpec(key=j.name, name=j.name, movable=j.movable,
+ target=j.mimic.joint if j.mimic else None,
+ multiplier=j.mimic.multiplier if j.mimic else 1.0)
+ for j in joints.values()]):
+ raise UrdfError(_mimic_message(issue, joints))
roots = [n for n in links if n not in children]
if len(roots) != 1:
raise UrdfError(f"expected exactly one root link, found {roots}")
diff --git a/harness/tests/urdf_joints/test_mimic.py b/harness/tests/urdf_joints/test_mimic.py
index 152f73d3..f9354f21 100644
--- a/harness/tests/urdf_joints/test_mimic.py
+++ b/harness/tests/urdf_joints/test_mimic.py
@@ -217,3 +217,55 @@ def test_a_mimic_of_an_instanced_driver_follows_the_first_instance():
names = {ln.split('"')[1] for ln in urdf.splitlines() if "<joint name=" in ln}
refs = {ln.split('"')[1] for ln in urdf.splitlines() if "<mimic joint=" in ln}
assert refs <= names, f"dangling mimic reference: {refs - names}"
+
+
+# ------------------------------------------------------------------ one rule set, three layers
+def test_the_three_layers_reject_the_same_near_zero_multiplier(tmp_path):
+ """A multiplier of 1e-10 is a coupling that transmits nothing.
+
+ The plan validator refused it (< 1e-9) while the loader and the lint accepted it
+ (< 1e-12), so a coupling the planner could not write was one the URDF path took.
+ All three read ``MIMIC_MIN_MULTIPLIER`` now.
+ """
+ from codeverse.contracts.common import MIMIC_MIN_MULTIPLIER
+ from codeverse.workspace import Workspace
+
+ dead = 1e-10 # under the shared floor, over the 1e-12 the loader and the lint used
+ assert dead < MIMIC_MIN_MULTIPLIER
+ with pytest.raises(Exception, match="multiplier 0"):
+ ArticulatedPlan.model_validate(_plan(mimic={"joint": "DrawerSlide", "multiplier": dead}))
+
+ text = RIB.replace('multiplier="4"', f'multiplier="{dead}"')
+ with pytest.raises(UrdfError, match="cannot move"):
+ _robot(tmp_path, text)
+
+ ws = Workspace(tmp_path / "lint_ws").create()
+ (ws.src / "robot.urdf").write_text(text)
+ (ws.src / "model.py").write_text("import bpy\n")
+ assert [f for f in lint_workspace(ws).findings if "cannot move" in f.message]
+
+
+def test_the_lint_sees_a_cycle_the_per_joint_pass_could_not(tmp_path):
+ """``rib_a`` follows ``rib_b`` follows ``rib_a``: no single <mimic> element is wrong,
+ only the graph is. The lint checked one joint at a time and passed this file; the
+ loader then refused it, so the failure landed after the build instead of before."""
+ from codeverse.workspace import Workspace
+
+ ws = Workspace(tmp_path / "ws").create()
+ (ws.src / "robot.urdf").write_text(RIB.replace('<mimic joint="runner_slide" multiplier="4" offset="0"/>',
+ '<mimic joint="rib_b_hinge" multiplier="1" offset="0"/>'))
+ (ws.src / "model.py").write_text("import bpy\n")
+ cycles = [f for f in lint_workspace(ws).findings if "cycle" in f.message]
+ assert cycles and {f.target for f in cycles} == {"rib_a_hinge", "rib_b_hinge"}
+
+
+def test_an_unknown_target_is_reported_once_not_once_per_follower():
+ """The chain walk exists to find cycles. Every joint it walks through is itself in
+ the set and reports its own broken target, so the walk must not report it again."""
+ from codeverse.contracts.common import MimicSpec, mimic_issues
+
+ issues = mimic_issues([
+ MimicSpec(key="a", name="a", movable=True, target="ghost"),
+ MimicSpec(key="b", name="b", movable=True, target="a"),
+ ])
+ assert [(i.joint, i.kind) for i in issues] == [("a", "unknown_target")]