Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

mujoco: cover record(), the verdict and the scripts; fix six bugs they found

dee7c5c051c2f33
diff --git a/store/agents/mujoco/toolchain/harness_mujoco.py b/store/agents/mujoco/toolchain/harness_mujoco.py
index f3a891852..934308c45 100644
--- a/store/agents/mujoco/toolchain/harness_mujoco.py
+++ b/store/agents/mujoco/toolchain/harness_mujoco.py
@@ -12,7 +12,8 @@ physics, in the browser, where the user can push the robot, drive its actuators
- `rollout.qpos.json` — what the pane opens: the model's path, and per frame the time, `qpos`,
`qvel`, `ctrl` (and `act`). Written while the rollout runs (`"status": "recording"`), so the pane
- shows the run in progress, then `"status": "done"`. With `ctrl` recorded the pane re-simulates the
+ shows the run in progress, then `"status": "done"` (`"diverged"`; `"failed"`, with the `error`, when
+ the script raised mid-rollout). With `ctrl` recorded the pane re-simulates the
run live instead of only replaying it.
- `rollout.model.xml` — the compiled model as MJCF, when it was built or edited with `MjSpec`, so
the pane simulates the model you simulated and not the file it started from. Runtime edits to the
@@ -25,7 +26,7 @@ physics, in the browser, where the user can push the robot, drive its actuators
moves while the rollout runs.
"""
from __future__ import annotations
-import contextlib, io, json, os, sys, time, weakref
+import contextlib, io, json, math, os, sys, time, traceback, weakref
from pathlib import Path
from typing import Callable
@@ -156,7 +157,10 @@ def load_menagerie(robot: str, scene: str = "scene.xml", *, servos: tuple[float,
return load_xml(path)
kp, kv = servos
spec = mujoco.MjSpec.from_file(str(path))
- joint_range = {j.name: j.range.copy() for j in spec.joints}
+ # A servo's ctrl is the joint's own coordinate, radians for a hinge; the spec keeps a hinge's range
+ # in the MJCF's unit, which is degrees unless the file says <compiler angle="radian"/>.
+ degree = math.pi / 180 if spec.compiler.degree else 1.0
+ joint_range = {j.name: j.range * (degree if j.type == mujoco.mjtJoint.mjJNT_HINGE else 1.0) for j in spec.joints}
for act in spec.actuators:
if act.trntype != mujoco.mjtTrn.mjTRN_JOINT or act.target not in joint_range:
continue
@@ -167,6 +171,9 @@ def load_menagerie(robot: str, scene: str = "scene.xml", *, servos: tuple[float,
lo, hi = joint_range[act.target]
if hi > lo:
act.ctrlrange = [lo, hi]
+ else: # an unlimited joint: a torque rating is no angle to clamp to
+ act.ctrlrange = [0, 0]
+ act.ctrllimited = mujoco.mjtLimited.mjLIMITED_FALSE
if torque[1] > torque[0]:
act.forcerange = torque
model = spec.compile()
@@ -220,13 +227,11 @@ def _model_patch(model: mujoco.MjModel, reference: mujoco.MjModel) -> dict:
return patch
-def _compile_snapshot(xml: str, source_dir: Path | None) -> mujoco.MjModel:
+def _compile_snapshot(xml: str, source_dir: Path) -> mujoco.MjModel:
spec = mujoco.MjSpec.from_string(xml)
- if source_dir is not None:
- for attr in ("meshdir", "texturedir"):
- current = getattr(spec, attr, "") or ""
- if not os.path.isabs(current):
- setattr(spec, attr, str(source_dir / current))
+ for attr in ("meshdir", "texturedir"):
+ # Relative to the MJCF the model came from; an absolute dir stays itself (Path / "/x" is "/x").
+ setattr(spec, attr, str(source_dir / (getattr(spec, attr, "") or "")))
return _plain_compile(spec)
@@ -269,7 +274,7 @@ def _describe_model(model: mujoco.MjModel, source: str | None, out_dir: Path) ->
except Exception as error: # noqa: BLE001 — a spec MuJoCo cannot write back is still simulatable
print(f"note: could not save the compiled model for the pane ({error}); it will load {source}", file=sys.stderr)
snapshot.unlink(missing_ok=True)
- info["model_xml"] = None
+ info["model"], info["model_xml"] = source, None # never the snapshot just removed
else:
snapshot.unlink(missing_ok=True)
if reference is None and source_file is not None and source_file.exists():
@@ -286,6 +291,14 @@ def _describe_model(model: mujoco.MjModel, source: str | None, out_dir: Path) ->
return info
+_UNSTABLE = (mujoco.mjtWarning.mjWARN_BADQPOS, mujoco.mjtWarning.mjWARN_BADQVEL, mujoco.mjtWarning.mjWARN_BADQACC)
+
+
+def _unstable_warnings(data: mujoco.MjData) -> int:
+ """How many times MuJoCo has found this state NaN, infinite or huge (and reset it)."""
+ return sum(int(data.warning[int(w)].number) for w in _UNSTABLE)
+
+
def _write_json_atomic(path: Path, value: dict) -> None:
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(value, separators=(",", ":")) + "\n")
@@ -335,11 +348,14 @@ def record(model: mujoco.MjModel, data: mujoco.MjData, controller: Controller |
# The offscreen framebuffer is 640×480 unless the model says otherwise; a video wants more.
model.vis.global_.offwidth = max(int(model.vis.global_.offwidth), width)
model.vis.global_.offheight = max(int(model.vis.global_.offheight), height)
- renderer = mujoco.Renderer(model, height, width)
cam = mujoco.MjvCamera()
+ # An id of -1 is not an error until the first frame renders, and then MuJoCo exits the
+ # whole process mid-rollout: a name that is not in the model means no video, said now.
if isinstance(camera, str):
cam.type = mujoco.mjtCamera.mjCAMERA_FIXED
cam.fixedcamid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_CAMERA, camera)
+ if cam.fixedcamid < 0:
+ raise ValueError(f"no camera named {camera!r} in the model")
else:
mujoco.mjv_defaultFreeCamera(model, cam)
cam.distance = max(1.5, float(model.stat.extent) * 1.6)
@@ -348,6 +364,9 @@ def record(model: mujoco.MjModel, data: mujoco.MjData, controller: Controller |
if track:
cam.type = mujoco.mjtCamera.mjCAMERA_TRACKING
cam.trackbodyid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, track)
+ if cam.trackbodyid < 0:
+ raise ValueError(f"no body named {track!r} to track")
+ renderer = mujoco.Renderer(model, height, width)
writer = imageio.get_writer(str(out), fps=fps, codec="libx264", quality=8, macro_block_size=None)
video_path = out
except Exception as error: # noqa: BLE001 — no GL on this machine: the trajectory still works
@@ -375,9 +394,7 @@ def record(model: mujoco.MjModel, data: mujoco.MjData, controller: Controller |
if model.na:
rollout["act"].append([round(float(a), 5) for a in data.act])
- def publish(status: str) -> None:
- if not replayable:
- return
+ def publish(status: str) -> None: # only for a replayable rollout: every caller checks
rollout["status"] = status
rollout["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
_write_json_atomic(traj_path, rollout)
@@ -386,23 +403,21 @@ def record(model: mujoco.MjModel, data: mujoco.MjData, controller: Controller |
max_qvel = 0.0
t0 = time.time()
last_publish = 0.0
+ unstable = _unstable_warnings(data)
if replayable:
publish("recording")
_refresh_verdict()
try:
- for frame in range(frames + 1):
- ctrl_row: list[float] | None = None
- if frame == frames: # the final state has no step after it; its ctrl is the last one applied
- snapshot_state([round(float(c), 6) for c in data.ctrl])
- break
+ for _ in range(frames):
for step in range(steps_per_frame):
if controller is not None:
controller(model, data, data.time)
if step == 0:
- ctrl_row = [round(float(c), 6) for c in data.ctrl]
- snapshot_state(ctrl_row)
+ snapshot_state([round(float(c), 6) for c in data.ctrl])
mujoco.mj_step(model, data)
- if not np.all(np.isfinite(data.qpos)):
+ # MuJoCo resets a state that went NaN or huge (unless autoreset is disabled) and only warns,
+ # so a finite qpos proves nothing: the warning counter moving is the divergence.
+ if not np.all(np.isfinite(data.qpos)) or _unstable_warnings(data) > unstable:
nan = True
break
max_qvel = max(max_qvel, float(np.max(np.abs(data.qvel))) if model.nv else 0.0)
@@ -413,6 +428,16 @@ def record(model: mujoco.MjModel, data: mujoco.MjData, controller: Controller |
if replayable and now - last_publish > 0.5:
publish("recording")
last_publish = now
+ if not nan: # the final state has no step after it; its ctrl is the last one applied
+ snapshot_state([round(float(c), 6) for c in data.ctrl])
+ except BaseException as error:
+ # A controller that raised, or Ctrl-C: left at "recording", the pane and the header would
+ # wait for this rollout forever. What was recorded stays replayable.
+ if replayable:
+ rollout["error"] = traceback.format_exception_only(type(error), error)[-1].strip()
+ publish("failed")
+ _refresh_verdict()
+ raise
finally:
if writer is not None:
writer.close()
diff --git a/store/agents/mujoco/toolchain/install-training.sh b/store/agents/mujoco/toolchain/install-training.sh
index f12a82edd..26ce6935e 100755
--- a/store/agents/mujoco/toolchain/install-training.sh
+++ b/store/agents/mujoco/toolchain/install-training.sh
@@ -4,6 +4,9 @@
# for a real policy; a GPU machine in Harness's Machines menu is where a run belongs.
set -euo pipefail
cd "$(dirname "$0")/.."
-.venv/bin/python -m pip install --quiet "jax" "mujoco-mjx" "playground"
-.venv/bin/python -c 'import jax, mujoco_mjx if False else None' 2>/dev/null || true
+# shellcheck disable=SC1091
+. ./VERSIONS
+# MJX releases with MuJoCo, version for version: pinned both, so the extras never move the MuJoCo
+# setup.sh installed (an unpinned mujoco-mjx pulls the newest mujoco along with it).
+.venv/bin/python -m pip install --quiet "jax" "mujoco==${MUJOCO}" "mujoco-mjx==${MUJOCO}" "playground"
.venv/bin/python -c 'import jax; from mujoco import mjx; import mujoco_playground; print("ok jax", jax.__version__, "· mjx · playground", mujoco_playground.__version__, "· devices", jax.devices())'
diff --git a/store/agents/mujoco/toolchain/test_record.py b/store/agents/mujoco/toolchain/test_record.py
index b6e017a36..4dbc49e0e 100644
--- a/store/agents/mujoco/toolchain/test_record.py
+++ b/store/agents/mujoco/toolchain/test_record.py
@@ -2,18 +2,22 @@
"$MUJOCO_PYTHON" -m unittest toolchain/test_record.py
"""
-import importlib, json, os, sys, tempfile, unittest
+import contextlib, importlib, io, json, math, os, sys, tempfile, types, unittest
from pathlib import Path
+from unittest import mock
sys.path.insert(0, str(Path(__file__).parent))
try:
import mujoco # noqa: F401
+ import numpy as np
except ImportError: # the verdict tests run without mujoco; these cannot
mujoco = None
SCENE = """<mujoco model="cart">
<option timestep="0.002"/>
<worldbody>
+ <light pos="0 0 3"/>
+ <camera name="side" pos="0 -2 .4" xyaxes="1 0 0 0 0 1"/>
<geom type="plane" size="2 2 .1"/>
<body name="cart" pos="0 0 .1">
<joint name="slide" type="slide" axis="1 0 0"/>
@@ -25,12 +29,48 @@ SCENE = """<mujoco model="cart">
</mujoco>
"""
+# A Menagerie-shaped robot, in MuJoCo's default degrees: a hip hinge with a range and a torque motor,
+# a wheel with no range, a slide driven by a motor with no ctrlrange and by a servo, a tendon motor,
+# and a mesh under the robot's own meshdir.
+ROBOT = """<mujoco model="bot">
+ <compiler meshdir="assets"/>
+ <option timestep="0.002"/>
+ <asset><mesh name="tet" file="tet.obj"/></asset>
+ <worldbody>
+ <light pos="0 0 3"/>
+ <body name="base" pos="0 0 .5">
+ <joint name="hip" type="hinge" axis="0 1 0" range="-90 90"/>
+ <geom type="capsule" fromto="0 0 0 0 0 -.3" size=".04" mass="1"/>
+ <geom type="mesh" mesh="tet" mass=".05"/>
+ <body name="wheel" pos="0 0 -.3">
+ <joint name="spin" type="hinge" axis="0 1 0"/>
+ <geom type="cylinder" size=".05 .02" mass=".2"/>
+ </body>
+ <body name="slider" pos=".1 0 0">
+ <joint name="slide" type="slide" axis="1 0 0" range="-0.1 0.1"/>
+ <geom type="box" size=".02 .02 .02" mass=".1"/>
+ </body>
+ </body>
+ </worldbody>
+ <tendon><fixed name="hip_tendon"><joint joint="hip" coef="1"/></fixed></tendon>
+ <actuator>
+ <motor name="hip" joint="hip" ctrlrange="-20 20"/>
+ <motor name="spin" joint="spin" ctrlrange="-3 3"/>
+ <motor name="slide" joint="slide"/>
+ <position name="slide_servo" joint="slide" kp="30"/>
+ <motor name="pull" tendon="hip_tendon" ctrlrange="-1 1"/>
+ </actuator>
+ <keyframe><key name="home" qpos="0.4 0 0.05" ctrl="0.4 0 0 0.05 0.25"/></keyframe>
+</mujoco>
+"""
+TET = "v 0 0 0\nv .05 0 0\nv 0 .05 0\nv 0 0 .05\nf 1 3 2\nf 1 2 4\nf 1 4 3\nf 2 3 4\n"
+
@unittest.skipIf(mujoco is None, "mujoco is not installed in this interpreter")
class Record(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
- self.ws = Path(self.tmp.name)
+ self.ws = Path(self.tmp.name).resolve()
(self.ws / "scenes").mkdir()
(self.ws / "scenes" / "cart.xml").write_text(SCENE)
self.cwd = os.getcwd()
@@ -48,6 +88,16 @@ class Record(unittest.TestCase):
def rollout(self):
return json.loads((self.ws / "out" / "rollout.qpos.json").read_text())
+ def verdict(self):
+ return json.loads((self.ws / ".harness" / "verdict.json").read_text())
+
+ def quietly(self, fn, *args, **kwargs):
+ """Call fn with stdout and stderr captured; returns (result, stdout, stderr)."""
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ result = fn(*args, **kwargs)
+ return result, out.getvalue(), err.getvalue()
+
def test_the_trajectory_carries_state_and_controls_frame_by_frame(self):
model, data = self.hm.load_xml("scenes/cart.xml")
report = self.hm.record(model, data, lambda m, d, t: d.ctrl.__setitem__(0, 2.0 if t < 0.5 else -2.0), seconds=1.0, fps=25, video=False)
@@ -63,8 +113,9 @@ class Record(unittest.TestCase):
self.assertAlmostEqual(t["dt"], 20 * 0.002, msg="the frame period is whole steps, not 1/fps")
self.assertAlmostEqual(t["time"][1] - t["time"][0], t["dt"], places=6)
self.assertIsNone(t["video"])
+ self.assertNotIn("act", t, "no actuator dynamics, no act column")
self.assertEqual(report["trajectory"], "out/rollout.qpos.json")
- verdict = json.loads((self.ws / ".harness" / "verdict.json").read_text())
+ verdict = self.verdict()
self.assertTrue(verdict["ready"], "record() refreshes the verdict")
self.assertEqual(verdict["artifact"], "out/rollout.qpos.json")
@@ -108,9 +159,368 @@ class Record(unittest.TestCase):
def test_an_unknown_model_cannot_be_replayed_and_says_so(self):
model = mujoco.MjModel.from_xml_string(SCENE)
data = mujoco.MjData(model)
- report = self.hm.record(model, data, None, seconds=0.1, video=False)
+ report, printed, _ = self.quietly(self.hm.record, model, data, None, seconds=0.1, video=False)
self.assertIsNone(report["trajectory"])
self.assertFalse((self.ws / "out" / "rollout.qpos.json").exists())
+ self.assertIn("the pane cannot simulate this rollout", printed)
+
+ # ---- the video ------------------------------------------------------------------------------
+
+ def test_a_video_from_the_free_camera_following_a_body(self):
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ report, printed, _ = self.quietly(self.hm.record, model, data, None, seconds=0.1, fps=20, width=64, height=48, track="cart")
+ video = self.ws / "out" / "rollout.mp4"
+ self.assertGreater(video.stat().st_size, 0)
+ self.assertEqual(report["video"], "out/rollout.mp4")
+ t = self.rollout()
+ self.assertEqual((t["video"], t["track"], t["camera"]), ("out/rollout.mp4", "cart", None))
+ self.assertIn("video out/rollout.mp4", printed)
+
+ def test_a_video_from_a_named_camera(self):
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ report, _, _ = self.quietly(self.hm.record, model, data, None, seconds=0.1, fps=20, width=64, height=48, camera="side", out="out/side.mp4")
+ self.assertGreater((self.ws / "out" / "side.mp4").stat().st_size, 0)
+ self.assertEqual(self.rollout()["camera"], "side")
+ self.assertEqual(report["video"], "out/side.mp4")
+
+ def test_a_camera_or_body_the_model_does_not_have_means_no_video_not_a_dead_process(self):
+ # Before: MuJoCo exited the whole interpreter at the first frame ("fixed camera id is outside
+ # valid range"), leaving the trajectory at "recording" for good.
+ for kwargs, said in (({"camera": "front"}, "no camera named 'front'"), ({"track": "torso"}, "no body named 'torso'")):
+ with self.subTest(**kwargs):
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ report, _, err = self.quietly(self.hm.record, model, data, None, seconds=0.1, width=64, height=48, **kwargs)
+ self.assertIn(said, err)
+ self.assertIsNone(report["video"])
+ self.assertEqual(self.rollout()["status"], "done")
+
+ def test_no_gl_means_no_video_and_the_rollout_still_records(self):
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ with mock.patch.object(self.hm.mujoco, "Renderer", side_effect=RuntimeError("no OpenGL context")):
+ report, _, err = self.quietly(self.hm.record, model, data, None, seconds=0.1)
+ self.assertIn("note: no video (no OpenGL context)", err)
+ self.assertIsNone(report["video"])
+ self.assertEqual(self.rollout()["status"], "done")
+
+ def test_a_writer_that_cannot_start_closes_the_renderer(self):
+ import imageio.v2 as imageio
+ closed, alive = [], []
+
+ class Renderer(mujoco.Renderer):
+ def __init__(self, *args):
+ super().__init__(*args)
+ alive.append(self) # held here, so a close on garbage collection cannot stand in for record()'s
+
+ def close(self):
+ closed.append(True)
+ super().close()
+
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ with mock.patch.object(self.hm.mujoco, "Renderer", Renderer), mock.patch.object(imageio, "get_writer", side_effect=OSError("no ffmpeg")):
+ report, _, err = self.quietly(self.hm.record, model, data, None, seconds=0.1, width=64, height=48)
+ self.assertIn("no ffmpeg", err)
+ self.assertEqual(closed, [True])
+ self.assertIsNone(report["video"])
+
+ # ---- how a rollout ends ---------------------------------------------------------------------
+
+ def test_divergence_is_caught_although_mujoco_resets_the_state(self):
+ # MuJoCo puts a NaN state back to the initial one and only warns: before, qpos was finite
+ # again by the time record() looked, and a diverged rollout was reported stable and ready.
+ model, data = self.hm.load_xml("scenes/cart.xml")
+
+ def blow_up(m, d, t):
+ if t > 0.1:
+ d.qvel[0] = math.nan
+
+ report, printed, _ = self.quietly(self.hm.record, model, data, blow_up, seconds=1.0, video=False)
+ self.assertTrue(report["nan"])
+ self.assertIn("NaN — diverged", printed)
+ self.assertEqual(self.rollout()["status"], "diverged")
+ self.assertLess(len(self.rollout()["qpos"]), 31, "the rollout stops where it diverged")
+ verdict = self.verdict()
+ self.assertFalse(verdict["ready"])
+ self.assertEqual(verdict["phases"][1]["state"], "failed")
+
+ def test_divergence_without_autoreset_is_a_non_finite_qpos(self):
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_AUTORESET)
+ report, _, _ = self.quietly(self.hm.record, model, data, lambda m, d, t: d.qpos.__setitem__(0, math.inf), seconds=0.2, video=False)
+ self.assertTrue(report["nan"])
+
+ def test_a_controller_that_raises_ends_the_recording_as_failed(self):
+ # Before: the trajectory stayed "recording" and the header said "recording cart.xml" forever.
+ model, data = self.hm.load_xml("scenes/cart.xml")
+
+ def broken(m, d, t):
+ if t > 0.1:
+ raise RuntimeError("boom")
+
+ with self.assertRaises(RuntimeError), contextlib.redirect_stdout(io.StringIO()):
+ self.hm.record(model, data, broken, seconds=1.0, video=False)
+ t = self.rollout()
+ self.assertEqual((t["status"], t["error"]), ("failed", "RuntimeError: boom"))
+ self.assertGreater(len(t["qpos"]), 1, "what was recorded stays replayable")
+ verdict = self.verdict()
+ self.assertFalse(verdict["ready"])
+ self.assertEqual([p["state"] for p in verdict["phases"]], ["done", "failed", "pending"])
+ self.assertTrue(verdict["summary"].startswith("stopped cart.xml · "), verdict["summary"])
+ self.assertIn("RuntimeError: boom", verdict["findings"][0]["message"])
+
+ def test_an_unreplayable_rollout_that_raises_writes_nothing_for_the_pane(self):
+ model = mujoco.MjModel.from_xml_string(SCENE)
+ with self.assertRaises(KeyboardInterrupt):
+ self.hm.record(model, mujoco.MjData(model), lambda m, d, t: (_ for _ in ()).throw(KeyboardInterrupt()), seconds=0.1, video=False)
+ self.assertFalse((self.ws / "out" / "rollout.qpos.json").exists())
+
+ def test_actuator_dynamics_and_a_model_with_nothing_to_move(self):
+ (self.ws / "scenes" / "filter.xml").write_text(SCENE.replace(
+ '<motor name="push" joint="slide" gear="1" ctrlrange="-5 5"/>',
+ '<general name="push" joint="slide" dyntype="filter" dynprm=".05" ctrlrange="-5 5"/>').replace('ctrl="0"', 'ctrl="0" act="0"'))
+ model, data = self.hm.load_xml("scenes/filter.xml")
+ self.quietly(self.hm.record, model, data, lambda m, d, t: d.ctrl.__setitem__(0, 1.0), seconds=0.1, fps=50, video=False)
+ t = self.rollout()
+ self.assertEqual(t["na"], 1)
+ self.assertEqual(len(t["act"]), len(t["qpos"]))
+ self.assertGreater(t["act"][-1][0], 0.0, "the filter state moves toward the control")
+
+ (self.ws / "scenes" / "still.xml").write_text('<mujoco><worldbody><geom type="sphere" size=".1"/></worldbody></mujoco>')
+ model, data = self.hm.load_xml("scenes/still.xml")
+ report, _, _ = self.quietly(self.hm.record, model, data, None, seconds=0.1, fps=50, video=False)
+ self.assertEqual((report["max_qvel"], report["model"]["nv"], report["ctrl_recorded"]), (0.0, 0, False))
+ self.assertEqual(self.rollout()["qpos"][0], [])
+
+ # ---- the model the pane loads ---------------------------------------------------------------
+
+ def test_a_model_built_from_scratch_is_its_snapshot(self):
+ spec = mujoco.MjSpec()
+ body = spec.worldbody.add_body(name="ball", pos=[0, 0, 1])
+ body.add_freejoint()
+ body.add_geom(type=mujoco.mjtGeom.mjGEOM_SPHERE, size=[0.1, 0, 0])
+ model = spec.compile()
+ self.quietly(self.hm.record, model, mujoco.MjData(model), None, seconds=0.1, video=False)
+ t = self.rollout()
+ self.assertEqual((t["model"], t["model_xml"]), ("out/rollout.model.xml", "out/rollout.model.xml"))
+ self.assertTrue((self.ws / "out" / "rollout.model.xml").exists())
+
+ def test_a_snapshot_that_does_not_compile_is_never_named(self):
+ # Before: the model was left naming out/rollout.model.xml, the file just deleted.
+ spec = mujoco.MjSpec()
+ spec.worldbody.add_geom(type=mujoco.mjtGeom.mjGEOM_SPHERE, size=[0.1, 0, 0])
+ model = spec.compile()
+ with mock.patch.object(self.hm, "_compile_snapshot", side_effect=ValueError("mesh not found")):
+ report, _, err = self.quietly(self.hm.record, model, mujoco.MjData(model), None, seconds=0.1, video=False)
+ self.assertIn("could not save the compiled model for the pane (mesh not found)", err)
+ self.assertFalse((self.ws / "out" / "rollout.model.xml").exists())
+ self.assertIsNone(report["model_path"])
+ self.assertIsNone(report["trajectory"], "nothing the pane could load")
+
+ def test_a_spec_that_cannot_be_written_back_falls_back_to_its_file(self):
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ (self.ws / "out").mkdir()
+ (self.ws / "out" / "rollout.model.xml").write_text("<mujoco/>") # a stale snapshot of an older run
+
+ class Unwritable:
+ def to_xml(self):
+ raise RuntimeError("to_xml is not supported for this spec")
+
+ self.hm._MODEL_SPECS[model] = Unwritable()
+ _, _, err = self.quietly(self.hm.record, model, data, None, seconds=0.1, video=False)
+ self.assertIn("it will load scenes/cart.xml", err)
+ t = self.rollout()
+ self.assertEqual((t["model"], t["model_xml"]), ("scenes/cart.xml", None))
+ self.assertFalse((self.ws / "out" / "rollout.model.xml").exists())
+
+ def test_no_reference_to_compare_against_means_no_patch(self):
+ (self.ws / "scenes" / "broken.xml").write_text("<mujoco><worldbody><geom/></worldbody")
+ for path in ("scenes/missing.xml", "scenes/broken.xml"):
+ with self.subTest(model_path=path):
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ model.opt.timestep = 0.001
+ self.quietly(self.hm.record, model, data, None, seconds=0.05, video=False, model_path=path)
+ t = self.rollout()
+ self.assertEqual((t["model"], t["model_patch"]), (path, {}))
+ model, data = self.hm.load_xml("scenes/cart.xml")
+ model.opt.timestep = 0.001
+ with mock.patch.object(self.hm, "_model_patch", side_effect=ValueError("shapes")):
+ self.quietly(self.hm.record, model, data, None, seconds=0.05, video=False)
+ self.assertEqual(self.rollout()["model_patch"], {})
+
+ def test_patch_fields_this_mujoco_does_not_have_are_skipped(self):
+ model, _ = self.hm.load_xml("scenes/cart.xml")
+ reference, _ = self.hm.load_xml("scenes/cart.xml")
+ model.opt.gravity[2] = -1.6
+ model.dof_damping[0] = 2.0
+ with mock.patch.object(self.hm, "_PATCH_OPTION", ("gravity", "timestep", "warp_iterations")), \
+ mock.patch.object(self.hm, "_PATCH_FIELDS", ("dof_damping", "key_act", "geom_fluidcoef_v2")):
+ self.assertEqual(self.hm._model_patch(model, reference), {"opt.gravity": [0.0, 0.0, -1.6], "dof_damping": [2.0]})
+
+ # ---- Menagerie ------------------------------------------------------------------------------
+
+ def menagerie(self) -> Path:
+ root = self.ws.parent / f"{self.ws.name}-menagerie"
+ (root / "bot" / "assets").mkdir(parents=True)
+ (root / "bot" / "scene.xml").write_text(ROBOT)
+ (root / "bot" / "assets" / "tet.obj").write_text(TET)
+ (root / "notes").mkdir()
+ self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True))
+ patcher = mock.patch.object(self.hm, "MENAGERIE", root)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ return root
+
+ def test_servos_take_each_joint_range_in_radians_and_leave_unlimited_joints_unclamped(self):
+ self.menagerie()
+ model, data = self.hm.load_menagerie("bot", servos=(50, 5))
+ act = {mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_ACTUATOR, i): i for i in range(model.nu)}
+ affine = mujoco.mjtBias.mjBIAS_AFFINE
+ self.assertEqual([model.actuator_biastype[act[n]] == affine for n in ("hip", "spin", "slide", "slide_servo", "pull")],
+ [True, True, True, True, False], "every joint motor is a servo; a tendon motor is left alone")
+ self.assertEqual(model.actuator_gainprm[act["hip"], 0], 50)
+ self.assertEqual(model.actuator_gainprm[act["slide_servo"], 0], 30, "an existing servo keeps its gains")
+ # Before: [-90, 90], a degree range read as radians.
+ np.testing.assert_allclose(model.actuator_ctrlrange[act["hip"]], [-math.pi / 2, math.pi / 2])
+ np.testing.assert_allclose(model.actuator_ctrlrange[act["hip"]], model.jnt_range[0])
+ np.testing.assert_allclose(model.actuator_ctrlrange[act["slide"]], [-0.1, 0.1], err_msg="a slide's range is a length")
+ # Before: limited to [-3, 3], the wheel's torque rating as an angle.
+ self.assertFalse(model.actuator_ctrllimited[act["spin"]])
+ np.testing.assert_allclose(model.actuator_forcerange[act["hip"]], [-20, 20], err_msg="the torque rating limits the servo's force")
+ self.assertFalse(model.actuator_forcelimited[act["slide"]], "no rating, no force limit")
+ np.testing.assert_allclose(data.qpos, model.key_qpos[0])
+ self.assertEqual(self.hm.model_source(model), "menagerie/bot/scene.xml")
+
+ self.quietly(self.hm.record, model, data, None, seconds=0.05, video=False)
+ t = self.rollout()
+ self.assertEqual((t["model"], t["model_xml"]), ("menagerie/bot/scene.xml", "out/rollout.model.xml"),
+ "the snapshot compiles against the robot's own meshdir")
+ # MjSpec.to_xml writes five significant digits; the patch carries the exact radians back.
+ self.assertLessEqual(set(t["model_patch"]), {"jnt_range", "actuator_ctrlrange"})
+ np.testing.assert_allclose(t["model_patch"]["actuator_ctrlrange"][:2], [-math.pi / 2, math.pi / 2], rtol=0, atol=1e-8)
+
+ def test_a_radian_robot_is_not_converted(self):
+ root = self.menagerie()
+ robot = ROBOT.replace('<compiler meshdir="assets"/>', '<compiler meshdir="assets" angle="radian"/>').replace('range="-90 90"', 'range="-1 1"')
+ (root / "bot" / "scene.xml").write_text(robot.split("<keyframe>")[0] + "</mujoco>\n")
+ model, data = self.hm.load_menagerie("bot", servos=(50, 5))
+ np.testing.assert_allclose(model.actuator_ctrlrange[0], [-1, 1])
+ np.testing.assert_allclose(data.qpos, model.qpos0, err_msg="no keyframe: the model's reference pose")
+
+ def test_a_robot_as_shipped_and_one_that_is_not_there(self):
+ self.menagerie()
+ model, data = self.hm.load_menagerie("bot")
+ self.assertEqual(model.actuator_biastype[0], mujoco.mjtBias.mjBIAS_NONE, "no servos asked for, the motors stay")
+ self.assertEqual(self.hm.model_source(model), "menagerie/bot/scene.xml")
+ with self.assertRaises(FileNotFoundError) as caught:
+ self.hm.load_menagerie("unitree_go2")
+ self.assertIn("robots available: bot", str(caught.exception))
+
+ def test_pd_hold_drives_motors_and_hands_servos_and_tendons_their_keyframe(self):
+ self.menagerie()
+ model, data = self.hm.load_menagerie("bot")
+ hold = self.hm.pd_hold(kp=100, kd=1)
+ data.qpos[:] = [-0.4, 0.0, -0.5]
+ data.qvel[:] = 0
+ hold(model, data, 0.0)
+ self.assertEqual(data.ctrl[0], 20.0, "PD torque clipped to the motor's ctrlrange")
+ self.assertAlmostEqual(data.ctrl[2], 100 * (0.05 + 0.5), msg="no ctrlrange: the torque unclipped")
+ self.assertAlmostEqual(data.ctrl[3], 0.05, msg="a servo gets the keyframe's control")
+ self.assertAlmostEqual(data.ctrl[4], 0.25, msg="a tendon actuator gets the keyframe's control")
+
+ (self.ws / "scenes" / "nokey.xml").write_text(SCENE.replace('<keyframe><key name="rest" qpos="0" ctrl="0"/></keyframe>', ""))
+ model, data = self.hm.load_xml("scenes/nokey.xml")
+ data.ctrl[0] = 1.5
+ self.hm.pd_hold()(model, data, 0.0)
+ self.assertEqual(data.ctrl[0], 1.5, "no keyframe, nothing to hold")
+
+ # ---- where models come from -----------------------------------------------------------------
+
+ def test_viewer_paths(self):
+ root = self.menagerie()
+ self.assertEqual(self.hm.viewer_path(root / "bot" / "scene.xml"), "menagerie/bot/scene.xml")
+ self.assertEqual(self.hm.viewer_path("scenes/cart.xml"), "scenes/cart.xml")
+ with tempfile.TemporaryDirectory() as elsewhere:
+ self.assertIsNone(self.hm.viewer_path(Path(elsewhere) / "arm.xml"), "outside both, the pane cannot fetch it")
+ with mock.patch.object(self.hm, "MENAGERIE", Path("")):
+ self.assertIsNone(self.hm.viewer_path(root / "bot" / "scene.xml"), "no $MENAGERIE: not a Menagerie path")
+
+ def test_models_that_cannot_be_remembered(self):
+ model = mujoco.MjModel.from_xml_string(SCENE)
+ with tempfile.TemporaryDirectory() as elsewhere:
+ self.hm.remember_model(model, Path(elsewhere) / "cart.xml")
+ self.assertIsNone(self.hm.model_source(model))
+ self.hm.remember_model(42, "scenes/cart.xml") # not weak-referenceable: silently not remembered
+ self.assertIsNone(self.hm.model_source(42))
+ self.assertEqual(self.hm._describe_model(42, None, self.ws), {"model": None, "model_xml": None, "model_patch": {}})
+
+ def test_instrumenting_bindings_it_does_not_recognise_changes_nothing(self):
+ hm = self.hm
+
+ class NoCompile:
+ from_file = staticmethod(lambda filename: None)
+
+ with mock.patch.object(hm.mujoco, "MjSpec", NoCompile):
+ hm._instrument()
+ self.assertFalse(hasattr(NoCompile.from_file, "__wrapped_original__"))
+
+ class Frozen(type):
+ def __setattr__(cls, name, value):
+ raise TypeError("immutable type")
+
+ class Model(metaclass=Frozen):
+ from_xml_path = staticmethod(lambda filename: "model")
+
+ original = Model.from_xml_path
+ with mock.patch.object(hm.mujoco, "MjModel", Model):
+ hm._instrument()
+ self.assertIs(Model.from_xml_path, original)
+
+ def test_instrumented_loaders_return_what_mujoco_returned(self):
+ hm = self.hm
+ made = []
+
+ class Compiled: # weak-referenceable, as MjModel is
+ pass
+
+ class Spec:
+ def __init__(self, weak=True):
+ self.weak = weak
+
+ @staticmethod
+ def from_file(filename):
+ return Spec() if "cart" in str(filename) else 7 # 7: not weak-referenceable
+
+ def compile(self):
+ model = Compiled() if self.weak else 8
+ made.append(model)
+ return model
+
+ class Model:
+ @staticmethod
+ def from_xml_path(filename):
+ return Compiled()
+
+ with mock.patch.object(hm.mujoco, "MjSpec", Spec), mock.patch.object(hm.mujoco, "MjModel", Model):
+ hm._instrument()
+ loaded = Model.from_xml_path("scenes/cart.xml")
+ self.assertEqual(hm.model_source(loaded), "scenes/cart.xml")
+ self.assertEqual(Spec.from_file("scenes/other.xml"), 7)
+ spec = Spec.from_file("scenes/cart.xml")
+ model = spec.compile()
+ self.assertEqual(hm.model_source(model), "scenes/cart.xml")
+ self.assertIs(hm._MODEL_SPECS.get(model), spec)
+ self.assertIsInstance(Spec(weak=True).compile(), Compiled, "a spec from nowhere compiles, unremembered")
+ self.assertIsNone(hm.model_source(made[-1]))
+ self.assertEqual(Spec(weak=False).compile(), 8)
+
+ def test_a_verdict_that_fails_never_fails_the_script(self):
+ toolchain = str(Path(self.hm.__file__).resolve().parent)
+ broken = types.ModuleType("verdict")
+ broken.main = mock.Mock(side_effect=RuntimeError("verdict exploded"))
+ with mock.patch.dict(sys.modules, {"verdict": broken}):
+ before = sys.path.count(toolchain)
+ self.hm._refresh_verdict()
+ self.assertEqual(sys.path.count(toolchain), before, "the toolchain dir is taken back off sys.path")
+ broken.main.assert_called_once_with([])
if __name__ == "__main__":
diff --git a/store/agents/mujoco/toolchain/test_scripts.py b/store/agents/mujoco/toolchain/test_scripts.py
new file mode 100644
index 000000000..7ac3973b4
--- /dev/null
+++ b/store/agents/mujoco/toolchain/test_scripts.py
@@ -0,0 +1,270 @@
+"""setup.sh, doctor.sh, init-workspace.sh and install-training.sh, run for real against a scratch
+install whose PATH holds only stub commands (and the few coreutils the scripts use): every ok / miss /
+warn line is reached with no network, no pip and no MuJoCo on the machine.
+
+ python3 -m unittest toolchain/test_scripts.py
+"""
+import os, shutil, subprocess, tempfile, unittest
+from pathlib import Path
+
+PACKAGE = Path(__file__).resolve().parent.parent
+# A bash line tracer (BASH_ENV sourcing a DEBUG trap that appends to SHCOV_OUT) is passed through when set.
+TRACER = {k: os.environ[k] for k in ("BASH_ENV", "SHCOV_OUT") if k in os.environ}
+BASH = "/bin/bash"
+COREUTILS = ("dirname", "cat", "mkdir", "cp", "rm", "grep")
+VERSIONS = dict(line.split("=", 1) for line in (PACKAGE / "VERSIONS").read_text().split("\n") if "=" in line)
+MUJOCO = VERSIONS["MUJOCO"]
+COMMIT = VERSIONS["MENAGERIE_COMMIT"]
+ROBOTS = VERSIONS["MENAGERIE_ROBOTS"].strip('"').split()
+
+# The venv's python: pip succeeds unless told otherwise, `import mujoco` works, the training imports
+# only when TRAINING=1, and the heredoc render check "renders" when it is the script it should be.
+VENV_PYTHON = r'''
+case "$1" in
+ -m) case " $* " in
+ *" --upgrade pip "*) exit "${PIP_UPGRADE_EXIT:-0}" ;;
+ *) exit "${PIP_EXIT:-0}" ;;
+ esac ;;
+ -c) case "$2" in
+ *jax*) [ "${TRAINING:-0}" = 1 ] || exit 1
+ case "$2" in *print*) echo "ok jax 0.7.2 · mjx · playground 0.2.0 · devices [CpuDevice(id=0)]" ;; esac ;;
+ *__version__*) echo "$MUJOCO_VERSION" ;;
+ *) exit "${IMPORT_EXIT:-0}" ;;
+ esac ;;
+ -) cat > "$CALLS.stdin"
+ grep -q "mujoco.Renderer(m, 64, 64)" "$CALLS.stdin" && [ "${GL:-1}" = 1 ] || exit 1
+ echo "ok offscreen rendering works" ;;
+ *) echo "env PYTHONPATH=${PYTHONPATH-} MENAGERIE=${MENAGERIE-}" >> "$CALLS"; exit "${RUN_EXIT:-0}" ;;
+esac
+'''
+
+# A system python: passes the version probe unless PROBE_EXIT says otherwise, and makes a venv.
+SYSTEM_PYTHON = r'''
+case "$1" in
+ -c) exit "${PROBE_EXIT:-0}" ;;
+ --version) echo "Python ${VERSION:-3.12.4}" ;;
+ -m) mkdir -p "$3/bin" && cp "$VENV_TEMPLATE" "$3/bin/python" ;;
+esac
+'''
+
+# git, as far as setup.sh uses it: the sparse set is remembered, checkout lays those robots out.
+GIT = r'''
+case "$1" in
+ sparse-checkout) if [ "$2" = set ]; then shift 2; echo "$*" > .sparse; fi ;;
+ fetch) exit "${FETCH_EXIT:-0}" ;;
+ checkout) for r in $(cat .sparse); do
+ if [ "$r" != "${SKIP_ROBOT:-}" ]; then mkdir -p "$r"; echo "<mujoco/>" > "$r/scene.xml"; fi
+ done ;;
+esac
+'''
+
+
+class Sandbox:
+ """An install dir with the package's scripts, a bin/ of stubs as the whole PATH, and a log of
+ every stub call."""
+
+ def __init__(self, test: unittest.TestCase):
+ tmp = tempfile.TemporaryDirectory()
+ test.addCleanup(tmp.cleanup)
+ self.root = Path(tmp.name)
+ self.install = self.root / "install"
+ (self.install / "toolchain").mkdir(parents=True)
+ for script in PACKAGE.glob("toolchain/*.sh"):
+ (self.install / "toolchain" / script.name).symlink_to(script) # linked, not copied: a line tracer maps back to the source
+ shutil.copy(PACKAGE / "VERSIONS", self.install / "VERSIONS")
+ self.bin = self.root / "bin"
+ self.bin.mkdir()
+ self.calls = self.root / "calls.log"
+ self.calls.touch()
+ for name in COREUTILS:
+ real = next(p for p in (Path("/bin") / name, Path("/usr/bin") / name) if p.exists())
+ (self.bin / name).symlink_to(real)
+ self.venv_template = self.stub("python", VENV_PYTHON, where=self.root / "templates")
+
+ def stub(self, name: str, body: str = "", where: Path | None = None) -> Path:
+ path = (where or self.bin) / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(f'#!/bin/bash\necho "{name} $*" >> "$CALLS"\n{body}\n')
+ path.chmod(0o755)
+ return path
+
+ def venv(self) -> None:
+ (self.install / ".venv" / "bin").mkdir(parents=True)
+ shutil.copy(self.venv_template, self.install / ".venv" / "bin" / "python")
+
+ def menagerie(self, commit: str = COMMIT, robots=ROBOTS) -> None:
+ for robot in robots:
+ (self.install / "menagerie" / robot).mkdir(parents=True)
+ (self.install / "menagerie" / robot / "scene.xml").write_text("<mujoco/>")
+ (self.install / "menagerie" / ".harness-commit").write_text(commit + "\n")
+
+ def run(self, script: str, cwd: Path | None = None, **env: str) -> subprocess.CompletedProcess:
+ return subprocess.run([BASH, str(self.install / "toolchain" / script)], cwd=cwd or self.install,
+ env={"PATH": str(self.bin), "CALLS": str(self.calls), "VENV_TEMPLATE": str(self.venv_template),
+ "MUJOCO_VERSION": MUJOCO, **TRACER, **env},
+ capture_output=True, text=True, timeout=60)
+
+ def logged(self) -> list[str]:
+ return self.calls.read_text().splitlines()
+
+
+class Doctor(unittest.TestCase):
+ def test_ready_with_the_training_extras(self):
+ box = Sandbox(self)
+ box.venv()
+ box.menagerie()
+ r = box.run("doctor.sh", TRAINING="1")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(r.stdout.splitlines(), [f"ok mujoco {MUJOCO}", f"ok menagerie @ {COMMIT}", "ok training extras (jax, mjx, playground)"])
+
+ def test_ready_without_them_is_a_warning_only(self):
+ box = Sandbox(self)
+ box.venv()
+ box.menagerie()
+ r = box.run("doctor.sh")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(r.stdout.splitlines()[-1], "warn training extras not installed — toolchain/install-training.sh when a policy is wanted")
+
+ def test_nothing_installed(self):
+ r = Sandbox(self).run("doctor.sh")
+ self.assertEqual(r.returncode, 1)
+ self.assertEqual(r.stdout.splitlines(), ["miss .venv with mujoco — run toolchain/setup.sh", "miss menagerie — run toolchain/setup.sh",
+ "warn training extras not installed — toolchain/install-training.sh when a policy is wanted"])
+
+ def test_a_venv_that_cannot_import_mujoco_is_a_miss(self):
+ box = Sandbox(self)
+ box.venv()
+ box.menagerie()
+ r = box.run("doctor.sh", IMPORT_EXIT="1")
+ self.assertEqual(r.returncode, 1)
+ self.assertEqual(r.stdout.splitlines()[0], "miss .venv with mujoco — run toolchain/setup.sh")
+
+
+class Setup(unittest.TestCase):
+ def sandbox(self) -> Sandbox:
+ box = Sandbox(self)
+ box.stub("git", GIT)
+ return box
+
+ def test_a_fresh_install(self):
+ box = self.sandbox()
+ for name in ("python3", "python3.11", "python3.13"):
+ box.stub(name, SYSTEM_PYTHON)
+ # No python3.12: python3.11 comes next, before python3.13 and python3. A failing pip
+ # self-upgrade is not fatal.
+ r = box.run("setup.sh", VERSION="3.11.9", PIP_UPGRADE_EXIT="1")
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ self.assertEqual(r.stdout.splitlines(), [
+ "ok Python 3.11.9",
+ f" installing mujoco {MUJOCO}",
+ f"ok mujoco {MUJOCO}",
+ f" fetching MuJoCo Menagerie @ {COMMIT} ({' '.join(ROBOTS)})",
+ f"ok menagerie: {' '.join(ROBOTS)}",
+ " rendering check",
+ "ok offscreen rendering works",
+ ])
+ calls = box.logged()
+ self.assertIn("python3.11 -m venv .venv", calls)
+ self.assertIn(f'python -m pip install --quiet mujoco=={MUJOCO} numpy imageio[ffmpeg]', calls)
+ self.assertIn(f"git sparse-checkout set {' '.join(ROBOTS)}", calls)
+ self.assertIn(f"git fetch -q --depth 1 --filter=blob:none origin {COMMIT}", calls)
+ self.assertFalse(any(c.startswith("python3 ") for c in calls), "python3.11 is tried before python3")
+ self.assertEqual((box.install / "menagerie" / ".harness-commit").read_text().strip(), COMMIT)
+ for robot in ROBOTS:
+ self.assertTrue((box.install / "menagerie" / robot / "scene.xml").is_file())
+
+ def test_a_second_run_keeps_the_venv_and_the_menagerie(self):
+ box = self.sandbox()
+ box.stub("python3.12", SYSTEM_PYTHON)
+ box.venv()
+ box.menagerie()
+ r = box.run("setup.sh")
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ self.assertNotIn(" fetching", r.stdout)
+ calls = box.logged()
+ self.assertFalse(any(c.startswith("git ") for c in calls))
+ self.assertNotIn("python3.12 -m venv .venv", calls)
+
+ def test_a_menagerie_at_another_commit_is_fetched_again(self):
+ box = self.sandbox()
+ box.stub("python3.12", SYSTEM_PYTHON)
+ box.venv()
+ box.menagerie(commit="0" * 40, robots=["old_robot"])
+ r = box.run("setup.sh")
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ self.assertIn(f" fetching MuJoCo Menagerie @ {COMMIT}", r.stdout)
+ self.assertFalse((box.install / "menagerie" / "old_robot").exists(), "the old checkout is replaced, not added to")
+
+ def test_no_python_in_range_is_a_miss(self):
+ box = self.sandbox()
+ box.stub("python3", SYSTEM_PYTHON)
+ r = box.run("setup.sh", PROBE_EXIT="1")
+ self.assertEqual((r.returncode, r.stdout.strip()), (1, "miss python 3.10–3.13 (brew install [email protected])"))
+
+ def test_a_robot_the_checkout_did_not_bring_is_a_miss(self):
+ box = self.sandbox()
+ box.stub("python3.12", SYSTEM_PYTHON)
+ r = box.run("setup.sh", SKIP_ROBOT=ROBOTS[-1])
+ self.assertEqual(r.returncode, 1)
+ self.assertEqual(r.stdout.splitlines()[-1], f"miss menagerie/{ROBOTS[-1]}/scene.xml")
+
+ def test_failures_stop_setup(self):
+ for env, not_reached in (({"PIP_EXIT": "1"}, "ok mujoco"), ({"FETCH_EXIT": "128"}, "ok menagerie"), ({"GL": "0"}, "ok offscreen")):
+ with self.subTest(**env):
+ box = self.sandbox()
+ box.stub("python3.12", SYSTEM_PYTHON)
+ r = box.run("setup.sh", **env)
+ self.assertNotEqual(r.returncode, 0)
+ self.assertNotIn(not_reached, r.stdout)
+ if "FETCH_EXIT" in env:
+ self.assertFalse((box.install / "menagerie" / ".harness-commit").exists(), "a failed fetch is fetched again next time")
+
+
+class InstallTraining(unittest.TestCase):
+ def test_installs_mjx_pinned_to_the_mujoco_setup_installed(self):
+ box = Sandbox(self)
+ box.venv()
+ r = box.run("install-training.sh", TRAINING="1")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(r.stdout.splitlines(), ["ok jax 0.7.2 · mjx · playground 0.2.0 · devices [CpuDevice(id=0)]"])
+ # Before: an unpinned mujoco-mjx, which pulls the newest mujoco over the pinned one.
+ self.assertIn(f"python -m pip install --quiet jax mujoco=={MUJOCO} mujoco-mjx=={MUJOCO} playground", box.logged())
+
+ def test_a_failed_install_fails(self):
+ box = Sandbox(self)
+ box.venv()
+ r = box.run("install-training.sh", PIP_EXIT="1", TRAINING="1")
+ self.assertNotEqual(r.returncode, 0)
+ self.assertEqual(r.stdout, "")
+
+ def test_imports_that_do_not_work_after_install_fail(self):
+ box = Sandbox(self)
+ box.venv()
+ r = box.run("install-training.sh")
+ self.assertNotEqual(r.returncode, 0)
+
+
+class InitWorkspace(unittest.TestCase):
+ def test_a_first_rollout_and_the_verdict_even_when_both_fail(self):
+ box = Sandbox(self)
+ box.venv()
+ ws = box.root / "ws"
+ ws.mkdir()
+ r = box.run("init-workspace.sh", cwd=ws, HARNESS_DSH_DIR=str(box.install), RUN_EXIT="1")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertTrue((ws / ".harness").is_dir() and (ws / "out").is_dir())
+ toolchain = f"{box.install}/toolchain"
+ self.assertEqual(box.logged(), [
+ "python sim/hello.py", f"env PYTHONPATH={toolchain} MENAGERIE={box.install}/menagerie",
+ f"python {toolchain}/verdict.py", f"env PYTHONPATH={toolchain} MENAGERIE=",
+ ])
+
+ def test_needs_the_install_dir(self):
+ box = Sandbox(self)
+ r = box.run("init-workspace.sh", cwd=box.root)
+ self.assertNotEqual(r.returncode, 0)
+ self.assertIn("HARNESS_DSH_DIR", r.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/store/agents/mujoco/toolchain/test_verdict.py b/store/agents/mujoco/toolchain/test_verdict.py
index 4278052d6..75e83672e 100644
--- a/store/agents/mujoco/toolchain/test_verdict.py
+++ b/store/agents/mujoco/toolchain/test_verdict.py
@@ -1,11 +1,14 @@
-import json, os, sys, tempfile, unittest
+import contextlib, io, json, os, runpy, sys, tempfile, unittest
from pathlib import Path
+from unittest import mock
sys.path.insert(0, str(Path(__file__).parent))
import verdict
from verdict import judge
+HERE = Path(__file__).resolve().parent
STABLE = {"video": "out/rollout.mp4", "seconds": 4.0, "model": {"nbody": 18, "nu": 12}, "nan": False, "max_qvel": 12.0,
"model_path": "menagerie/unitree_go2/scene.xml", "trajectory": "out/rollout.qpos.json"}
+DONE = {"status": "done", "model": "menagerie/unitree_go2/scene.xml", "nu": 12, "qpos": [[0]], "ctrl": [[0] * 12]}
class Judge(unittest.TestCase):
@@ -23,6 +26,8 @@ class Judge(unittest.TestCase):
self.assertNotIn("mp4", v["summary"])
own = judge(True, {**STABLE, "model_path": "scenes/arm.xml"}, True, "out/rollout.qpos.json")
self.assertTrue(own["summary"].startswith("arm.xml · "))
+ nameless = judge(True, {"seconds": 1, "nan": False}, False, "out/rollout.qpos.json")
+ self.assertEqual(nameless["summary"], "1.0 s · ? bodies · ? actuators · stable")
def test_the_video_is_never_the_artifact(self):
without_trajectory = judge(True, STABLE, True, None)
@@ -48,43 +53,134 @@ class Judge(unittest.TestCase):
self.assertEqual(v["artifact"], "out/rollout.qpos.json")
self.assertEqual([p["state"] for p in v["phases"]], ["done", "active", "pending"])
self.assertEqual(v["summary"], "recording unitree_go2 · 2.0 / 5.0 s")
+ self.assertEqual(v["findings"], [])
+ anonymous = judge(True, None, False, None, recording={"qpos": []})
+ self.assertEqual(anonymous["summary"], "recording rollout · 0.0 / 0.0 s")
+
+ def test_a_rollout_the_script_stopped_mid_way_failed(self):
+ v = judge(True, STABLE, True, None, recording={"frames": 11, "dt": 0.05, "seconds": 4.0, "model": "scenes/arm.xml", "error": "RuntimeError: boom"})
+ self.assertFalse(v["ready"])
+ self.assertEqual([p["state"] for p in v["phases"]], ["done", "failed", "pending"])
+ self.assertEqual(v["summary"], "stopped arm.xml · 0.5 / 4.0 s")
+ self.assertEqual(v["findings"], [{"severity": "error", "kind": "simulate", "message": "the rollout stopped at 0.5 s: RuntimeError: boom"}])
+ self.assertEqual(v["artifact"], "out/rollout.qpos.json", "what was recorded still replays")
def test_divergence_fails_simulate(self):
v = judge(True, {"video": "out/rollout.mp4", "seconds": 1.0, "model": {}, "nan": True}, True)
self.assertFalse(v["ready"]); self.assertEqual(v["phases"][1]["state"], "failed"); self.assertEqual(v["findings"][0]["severity"], "error")
+ self.assertTrue(v["summary"].endswith("diverged"))
+
+ def test_exploding_velocities_are_a_warning(self):
+ v = judge(True, {**STABLE, "max_qvel": 950.4}, True, "out/rollout.qpos.json")
+ self.assertTrue(v["ready"])
+ self.assertEqual(v["findings"], [{"severity": "warning", "kind": "simulate", "message": "joint velocities reached 950 rad/s — the rollout is probably exploding"}])
def test_nothing_yet(self):
v = judge(False, None, False)
self.assertEqual([p["state"] for p in v["phases"]], ["active", "pending", "pending"])
self.assertIsNone(v["artifact"])
+ self.assertEqual(v["summary"], "no simulation yet")
+ self.assertEqual(judge(True, None, False)["summary"], "no rollout yet")
+
+ def test_a_report_without_a_model_on_disk(self):
+ v = judge(False, STABLE, False, "out/rollout.qpos.json")
+ self.assertEqual([p["state"] for p in v["phases"]], ["done", "done", "done"], "a report is proof enough of a model")
+
+
+class ModelName(unittest.TestCase):
+ def test_names(self):
+ self.assertEqual(verdict.model_name("menagerie/unitree_go2/scene.xml"), "unitree_go2")
+ self.assertEqual(verdict.model_name("menagerie/scene.xml"), "scene.xml")
+ self.assertEqual(verdict.model_name("scenes/arm.xml"), "arm.xml")
+ self.assertIsNone(verdict.model_name(None))
+ self.assertIsNone(verdict.model_name(""))
class Main(unittest.TestCase):
- """verdict.py on a workspace: what it reads, what it writes."""
+ """verdict.py on a workspace: what it reads, what it writes, what it prints and returns."""
- def run_in(self, files: dict) -> dict:
+ def run_main(self, files: dict) -> tuple[int, str, dict]:
with tempfile.TemporaryDirectory() as ws:
for rel, body in files.items():
path = Path(ws) / rel
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(body if isinstance(body, str) else json.dumps(body))
- verdict.WS = Path(ws)
- try:
- verdict.main([])
- finally:
- verdict.WS = Path(os.environ.get("HARNESS_WORKSPACE") or os.getcwd()).resolve()
- return json.loads((Path(ws) / ".harness" / "verdict.json").read_text())
+ if isinstance(body, bytes):
+ path.write_bytes(body)
+ else:
+ path.write_text(body if isinstance(body, str) else json.dumps(body))
+ printed = io.StringIO()
+ with mock.patch.object(verdict, "WS", Path(ws)), contextlib.redirect_stdout(printed):
+ code = verdict.main([])
+ self.assertFalse((Path(ws) / ".harness" / "verdict.json.tmp").exists(), "written atomically")
+ return code, printed.getvalue(), json.loads((Path(ws) / ".harness" / "verdict.json").read_text())
+
+ def run_in(self, files: dict) -> dict:
+ return self.run_main(files)[2]
def test_a_trajectory_mid_write_is_a_recording(self):
v = self.run_in({"sim/hello.py": "", "out/rollout.qpos.json": {"status": "recording", "model": "menagerie/unitree_go2/scene.xml", "dt": 0.034, "seconds": 4, "qpos": [[0]] * 30}})
self.assertEqual(v["phases"][1]["state"], "active")
self.assertTrue(v["summary"].startswith("recording unitree_go2"))
+ def test_a_trajectory_the_script_stopped_is_failed(self):
+ body = {"status": "failed", "error": "KeyboardInterrupt", "model": "scenes/arm.xml", "dt": 0.1, "seconds": 4, "qpos": [[0]] * 6}
+ code, printed, v = self.run_main({"scenes/arm.xml": "<mujoco/>", "out/rollout.json": STABLE, "out/rollout.qpos.json": body})
+ self.assertEqual(code, 1)
+ self.assertFalse(v["ready"], "the report of the run before is not this run's")
+ self.assertEqual(v["summary"], "stopped arm.xml · 0.5 / 4.0 s")
+ self.assertEqual(printed.splitlines(), ["not ready · stopped arm.xml · 0.5 / 4.0 s", " error the rollout stopped at 0.5 s: KeyboardInterrupt"])
+ v = self.run_in({"out/rollout.qpos.json": {**body, "error": None}})
+ self.assertIn("the script stopped", v["findings"][0]["message"])
+
def test_a_finished_rollout(self):
- v = self.run_in({"sim/hello.py": "", "out/rollout.json": STABLE,
- "out/rollout.qpos.json": {"status": "done", "model": "menagerie/unitree_go2/scene.xml", "nu": 12, "qpos": [[0]], "ctrl": [[0] * 12]}})
+ code, printed, v = self.run_main({"sim/hello.py": "", "out/rollout.json": STABLE, "out/rollout.qpos.json": DONE,
+ "out/rollout.mp4": b"\0" * 2000})
+ self.assertEqual(code, 0)
self.assertTrue(v["ready"])
self.assertEqual(v["artifact"], "out/rollout.qpos.json")
+ self.assertEqual(printed.splitlines(), ["ready · unitree_go2 · 4.0 s · 18 bodies · 12 actuators · stable"])
+
+ def test_the_video_is_optional_whatever_state_it_is_in(self):
+ for files in ({"out/rollout.mp4": b"\0" * 10}, {}, {"out/rollout.json": {**STABLE, "video": None}}):
+ with self.subTest(files=list(files)):
+ v = self.run_in({"scenes/arm.xml": "<mujoco/>", "out/rollout.json": STABLE, "out/rollout.qpos.json": DONE, **files})
+ self.assertTrue(v["ready"])
+
+ def test_controls_decide_whether_the_pane_can_resimulate(self):
+ old = {"status": "done", "model": "scenes/arm.xml", "qpos": [[0], [0]]}
+ v = self.run_in({"out/rollout.json": STABLE, "out/rollout.qpos.json": old})
+ self.assertEqual([f["kind"] for f in v["findings"]], ["replay"], "a trajectory written before controls were recorded")
+ passive = {"status": "done", "model": "scenes/ball.xml", "nu": 0, "qpos": [[0], [0]], "ctrl": [[], []]}
+ v = self.run_in({"out/rollout.json": STABLE, "out/rollout.qpos.json": passive})
+ self.assertEqual(v["findings"], [], "a model with no actuators has nothing to record")
+ v = self.run_in({"out/rollout.json": STABLE, "out/rollout.qpos.json": {**passive, "ctrl": []}})
+ self.assertEqual(v["findings"], [], "nor does an empty ctrl column matter when nu is 0")
+
+ def test_files_that_are_not_what_they_should_be_are_ignored(self):
+ code, printed, v = self.run_main({"scenes/arm.xml": "<mujoco/>", "out/rollout.json": "[1, 2]", "out/rollout.qpos.json": '{"status": "done", "qpos": 3}'})
+ self.assertEqual(code, 1)
+ self.assertEqual(v["summary"], "no rollout yet")
+ self.assertIsNone(v["artifact"])
+ self.assertEqual(printed, "not ready · no rollout yet\n")
+ v = self.run_in({"out/rollout.json": "{not json", "out/rollout.qpos.json": "[]"})
+ self.assertEqual(v["summary"], "no simulation yet")
+ # Before: a report that parsed to a list crashed the verdict (list has no .get) and wrote nothing.
+ v = self.run_in({"out/rollout.json": [STABLE]})
+ self.assertEqual(v["summary"], "no simulation yet")
+
+ def test_warnings_are_printed(self):
+ _, printed, _ = self.run_main({"out/rollout.json": STABLE})
+ self.assertEqual(printed.splitlines()[1][:10], " warning ")
+
+ def test_run_as_a_script(self):
+ with tempfile.TemporaryDirectory() as ws:
+ (Path(ws) / "sim").mkdir()
+ (Path(ws) / "sim" / "hello.py").write_text("")
+ with mock.patch.dict(os.environ, {"HARNESS_WORKSPACE": ws}), mock.patch.object(sys, "argv", ["verdict.py"]), contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaises(SystemExit) as exit_:
+ runpy.run_path(str(HERE / "verdict.py"), run_name="__main__")
+ self.assertEqual(exit_.exception.code, 1)
+ self.assertEqual(json.loads((Path(ws) / ".harness" / "verdict.json").read_text())["summary"], "no rollout yet")
if __name__ == "__main__": unittest.main()
diff --git a/store/agents/mujoco/toolchain/verdict.py b/store/agents/mujoco/toolchain/verdict.py
index a1b43b5a3..1814c7ef9 100755
--- a/store/agents/mujoco/toolchain/verdict.py
+++ b/store/agents/mujoco/toolchain/verdict.py
@@ -4,8 +4,9 @@
python toolchain/verdict.py # out/rollout.json + out/rollout.qpos.json
Phases: Model (a simulation script under sim/ or an MJCF under scenes/), Simulate (a rollout ran and
-did not diverge; active while `record` is still writing it), Record (the trajectory the pane runs is
-there, with its controls, so the pane can re-simulate it). Ready = simulated and recorded.
+did not diverge; active while `record` is still writing it, failed when the script stopped with an
+error mid-rollout), Record (the trajectory the pane runs is there, with its controls, so the pane can
+re-simulate it). Ready = simulated and recorded.
The artifact — what the pane opens — is the trajectory, `out/rollout.qpos.json`, and the pane opens
it as a live simulation. Before there is one it is the report, which still names the model. It is
@@ -34,15 +35,19 @@ def judge(has_model: bool, report: dict | None, video_ok: bool, trajectory: str
recording: dict | None = None, ctrl_recorded: bool = True) -> dict:
findings: list[dict] = []
if recording is not None:
+ # `error`: the script raised (or was stopped) mid-rollout; what was recorded still replays.
done = max(0, int(recording.get("frames", 0)) - 1) * float(recording.get("dt") or 0)
name = model_name(recording.get("model")) or "rollout"
+ error = recording.get("error")
phases = [
{"id": "model", "name": "Model", "state": "done"},
- {"id": "simulate", "name": "Simulate", "state": "active"},
+ {"id": "simulate", "name": "Simulate", "state": "failed" if error else "active"},
{"id": "record", "name": "Record", "state": "pending"},
]
- return {"spec": 1, "ready": False, "summary": f"recording {name} · {done:.1f} / {float(recording.get('seconds') or 0):.1f} s",
- "findings": [], "artifact": TRAJECTORY, "phases": phases,
+ if error:
+ findings.append({"severity": "error", "kind": "simulate", "message": f"the rollout stopped at {done:.1f} s: {error}"})
+ return {"spec": 1, "ready": False, "summary": f"{'stopped' if error else 'recording'} {name} · {done:.1f} / {float(recording.get('seconds') or 0):.1f} s",
+ "findings": findings, "artifact": TRAJECTORY, "phases": phases,
"updatedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
simulated = report is not None and not report.get("nan")
@@ -77,9 +82,10 @@ def judge(has_model: bool, report: dict | None, video_ok: bool, trajectory: str
def _read_json(path: Path) -> dict | None:
try:
- return json.loads(path.read_text())
+ value = json.loads(path.read_text())
except (OSError, ValueError):
return None
+ return value if isinstance(value, dict) else None # a list or a number is no report either
def main(argv: list[str]) -> int:
@@ -90,9 +96,11 @@ def main(argv: list[str]) -> int:
trajectory = None
ctrl_recorded = True
if trajectory_body and isinstance(trajectory_body.get("qpos"), list):
- if trajectory_body.get("status") == "recording":
+ if trajectory_body.get("status") in ("recording", "failed"):
recording = {"frames": len(trajectory_body["qpos"]), "dt": trajectory_body.get("dt"),
"seconds": trajectory_body.get("seconds"), "model": trajectory_body.get("model")}
+ if trajectory_body.get("status") == "failed":
+ recording["error"] = trajectory_body.get("error") or "the script stopped"
else:
trajectory = TRAJECTORY
ctrl_recorded = bool(trajectory_body.get("ctrl")) or not trajectory_body.get("nu", 1)