The first exam for code agents in the physical world: frozen robot tasks from many benchmark suites, each answered with a program and verified in a separate sandbox. Runs on Harbor.
Python ai-agentsbenchmarkcoding-agentsembodied-aievaluationharborllm-agentsrobot-learningroboticssimulation
AM-Bench: a first, privileged-only set of three aerial-manipulation tasks (placeholder) (#183)
Changhe Chen1e0a648c257c
diff --git a/docs/CUTOFFS.md b/docs/CUTOFFS.mdindex 498a640fb9..adfb29591a 100644--- a/docs/CUTOFFS.md+++ b/docs/CUTOFFS.md@@ -10,6 +10,7 @@ Every task gives the agent a fixed wall-clock time, its **cutoff**: Harbor's `[a| Benchmark | privileged | standard | standard-realtime | Tasks (P / S / RT) ||---|---|---|---|---|+| AM-Bench | 3600 s (60 min) | — | — | 3 / — / — || AutoBio | 3600 s (60 min) | 3600 s (60 min) | — | 9 / 9 / — || BEHAVIOR-1K | 7200 s (120 min) | 7200 s (120 min) | — | 100 / 100 / — || BiGym 2.0 | 3600 s (60 min) | 3600 s (60 min) | 3600 s (60 min) | 13 / 13 / 13 |@@ -39,7 +40,7 @@ Every task gives the agent a fixed wall-clock time, its **cutoff**: Harbor's `[a| VLABench | 1800 s (30 min) | 1800 s (30 min) | — | 36 / 36 / — || YAMLab | 3600 s (60 min) | 3600 s (60 min) | — | 10 / 10 / — |-1811 task directories. P / S / RT: privileged, standard, standard-realtime. A cutoff is a whole number of seconds, at most 14400 (PROTOCOL D8; no benchmark is excepted).+1814 task directories. P / S / RT: privileged, standard, standard-realtime. A cutoff is a whole number of seconds, at most 14400 (PROTOCOL D8; no benchmark is excepted).## Exceptions (per family, per task)@@ -117,3 +118,4 @@ The table started on 2026-10-11 with the number every task had on that day; each| 2026-10-13 | RoboTangle, privileged, standard | 7200 s -> (removed) | owner | removed: the benchmark is renamed RoboARC (next entry) and its Genesis tasks are deleted; RoboARC's MuJoCo release replaces them, and results recorded under this row are not carried over || 2026-10-13 | RoboARC, privileged, standard | (none) -> 10800 s | owner | new row: RoboARC, the MuJoCo release that replaces RoboTangle's Genesis tasks (prepared as RoboTangle-New, then RoboTangle; their entries, 0 -> 7200 on 2026-10-12 and 7200 -> 10800 on 2026-10-13, are folded into this one): 3 h wall clock for every family, within the default cap || 2026-10-14 | MyoSuite, standard-realtime | (none) -> 3600 s | owner (board 0112: a realtime twin's cutoff equals its standard twin's) | the first standard-realtime task (table_tennis): the standard twin's number |+| 2026-10-14 | AM-Bench, privileged | (none) -> 3600 s | proposal (D8 default) | the benchmark's first tasks (privileged only): the protocol's default; every Python process pays a few minutes of Isaac Sim start, which the hour includes |diff --git a/docs/benchmarks/ambench.md b/docs/benchmarks/ambench.mdnew file mode 100644index 0000000000..be24cc381c--- /dev/null+++ b/docs/benchmarks/ambench.md@@ -0,0 +1,152 @@+# AM-Bench++[AM-Bench](https://github.com/ambench/ambench) @ 60bf5b7 (Apache-2.0) on Isaac Lab @ f4aa17f / Isaac Sim 5.1.0: aerial+manipulation. The robot is AM-Bench's FA-Hexa, a fully actuated hexarotor (six tilted rotors: it can hold any attitude while+hovering) carrying a 4-joint arm (three pitch joints and a roll joint) with a two-finger gripper, driven by AM-Bench's own+whole-body controller (floating-base inverse kinematics with Pyroki, a PID for the airframe). `simulator = "ambench"`,+`robot = "ambench-fahexa"`.++**A first set (placeholder), privileged mode only.** Three families, three of AM-Bench's twelve tasks, one frozen instance+each:++| Family | AM-Bench environment | Task | Episode | Oracle: success at control step |+|---|---|---|---|---|+| `press_button_fahexa` | `PressButton-Am-FAHexa-Abs-PID-Direct-v0` | press a spring-loaded button on a (tilted) wall by ≥ 4 mm | 20 s | 1027 (end state `fcd4de9b…`) |+| `push_slider_fahexa` | `PushSlider-Am-FAHexa-Abs-PID-Direct-v0` | push a knob 0.95 m along a rail on a wall | 26 s | 1353 (end state `01a85d35…`) |+| `rotate_valve_fahexa` | `RotateValve-Am-FAHexa-Abs-PID-Direct-v0` | turn a valve wheel on a wall ≥ 170° clockwise | 20 s | 1002 (end state `1b976104…`) |++Task directories: `ambench-<task>-fahexa-i00-privileged`. **TossBall** (`TossBall-Am-FAHexa-Abs-PID-Direct-v0`: deliver the+held ball into a bin on the ground) was prepared too (`scripts/ambench/descr/toss_ball.json`) but has no reference solution+yet: AM-Bench's scripted expert, whose release timing and offsets it samples from torch's RNG, did not succeed on the seed-0+instance in 15 runs (with the cameras on: its own draw, then torch seeds 1-8; camera-free: its own draw, then seeds 1-5; every+one ran into the 10 s time-out), so it is left out of this set until that is understood. The standard twins+(`eai-standard/2.2`), more instances and the other tasks (doors, peg-in-hole, pick-and-place variants, perching) and robot+profiles (quadrotor, omnidirectional, the fully actuated hexa with a delta arm) are planned (Standard mode, below).++## Tasks and generator+- `python3 scripts/ambench/mk_tasks.py` writes every AM-Bench task dir from `scripts/ambench/` alone: `instances.json`+ (`modes`, and per task the frozen instance with its hashes and provenance), `frozen/<task>-iNN/` (`instance.json`,+ `oracle_actions.npy`), `descr/<task>.json` (what the task asks and exactly what its check tests, written from the+ task's code), `shared/rcb_ambench.py` (the tooling) and `template/privileged/`. Re-running it leaves `git diff tasks/`+ empty; `--check` only compares. `instances.json`'s `modes` is `["privileged"]` for now.+- Freezing (`scripts/ambench/freeze.py`, on a GPU host with the image): the instance is AM-Bench's seeded reset with seed 0+ (`cfg.seed = 0`, `env.reset(seed=0)`); AM-Bench draws the task's variation from it (where the wall, the button, the+ slider, the valve or the bin is; the button's size). `instance.json` holds the environment id, the seed and `initial_sha`+ (the sha256 of every articulation's and rigid object's root state, joint positions and velocities after the reset); every+ replay rebuilds the start and checks it (`instance_matches`).++## Success (AM-Bench's own)+Each task's `_get_success` (its `terminated` signal), unchanged except RotateValve's angle (below), evaluated after every control step; the episode ends at+the first step where it holds, or with AM-Bench's time-out (`episode_length_buf >= max_episode_length - 1`: control step+2399 / 3119 / 2399). No hold time is required. The privileged instructions give every threshold and the full scene:+PressButton `PlungerSlideJoint >= 0.004 m`; PushSlider `SliderJoint >= 0.45 m` (from -0.5 m); RotateValve+`base_to_shaft >= 17π/18` rad, on the joint's unwrapped angle. (TossBall's check, for when it joins: the ball ≥ 0.12 m from the tool tip, its centre inside+the bin's nominal 0.40 × 0.30 × 0.17 m box, and the airframe at x ≤ bin x − 0.7 m, at the same step; the third condition+already holds at the start, so it does not force a throw.)++**RotateValve: the unwrapped angle (2026-10-14, board 0110, before the first release).** `base_to_shaft` has no limits,+and omni.physx (107.3, Isaac Sim 5.1) creates an articulation's revolute joint without limits as a wrapped joint, whose+position PhysX reports in [-π, π] (omni.physx's own tests: "the joint without limits will be created as regular WRAPPED+joint"). AM-Bench's check `joint_pos >= 17π/18` on that value also passes a counter-clockwise turn of 190° (reported as++170°), while the task (and its instruction) is a clockwise turn of 170°. The tooling, the same file in the agent's+environment and in the grader, replaces RotateValve's `_get_success` with the same comparison on the unwrapped angle: the+sum of the joint's per-step changes since the reset, each wrapped into [-π, π) (the joint's velocity limit, 5 rad/s, moves it+at most 0.042 rad per 1/120 s step, so the sum is exact). Physics, states, `initial_sha` and the end-state hashes are+unchanged; for a clockwise turn below π the two readings agree, so the recorded oracle ends at the same step. The angle is+`s.valve_angle()` in the tooling. This is a correction of a wrap-around, not a stricter rule: the upstream threshold,+direction and timing stay as they are.++## Oracle (PROTOCOL §2.7)+`oracle = "full"`, 3/3. The reference solution of an instance is AM-Bench's scripted expert for the task+(`policies/scripted/<task>.py`, `inject_noise=False`), run in closed loop on the frozen instance by `freeze.py` (in a+camera-free Session, as the grader) and recorded as the rows the tooling executed, followed by 2 s of holding its last+command (`solution/oracle_actions.npy`); `solution/oracle.py` replays them through the agent's own tooling. The expert reads+the simulator's state between steps, so its own live episode is not the reference: two fresh-process replays with the+grader's CLI must both succeed and end in the same state before an instance is frozen. The hold is there because a replay+can lag the live episode (in the first, camera-on recording RotateValve's expert succeeded live at its 993rd row while a+replay of exactly those rows ended them short of 170°); rows after a replay's own success never run.++The experts are not in the image: the Dockerfile copies AM-Bench without `policies/scripted/`, `ambench_learn`, its scripts,+documentation and git history, blanks the task registrations' `scripted_policy_entry_point`, and fails if anything left+names them. `freeze.py` mounts the expert read-only from a checkout outside the image. AM-Bench is public on GitHub and+not on PyPI; the agent's egress is the model APIs and the package registries (`network_mode = "allowlist"`), so the+experts cannot be fetched during a trial.++## Tooling (`rcb_ambench.py`)+`Session` (frozen instance, reset, step, `hold_action`, status, `actions`, replay, `save_trajectory`), the privileged state+(`state()`: AM-Bench's own observation; `objects()`: every task object and fixture with pose, velocities and joint state;+`proprio()`: base and end-effector poses and velocities, gripper width, arm joints, the current command), the two onboard+cameras on request (`Session(cameras=True)`: `render_frame`, `start_video` / `stop_video`) and `env` (the Isaac Lab+environment itself). No motion primitives: reaching, pressing, pushing and turning are the agent's.+- **Actions**: AM-Bench's absolute end-effector pose action of the `Abs-PID` profile, 8 per control step: the ee_link+ target position (x, y, z, m, relative to the environment's origin), its orientation (qw, qx, qy, qz in AM-Bench's command+ frame of the end effector; `hold_action()` and `proprio()["command"]` give the current target in that convention) and the+ gripper (-1 closed .. +1 open). The tooling clips only the gripper to [-1, 1] and refuses a zero quaternion; it does not+ normalise the quaternion (that would change the float32 bits AM-Bench receives). 120 Hz control, one physics step of+ 1/120 s per action.+- **Cameras off by default.** A default Session does not build the robot profile's onboard cameras (`ee_camera`,+ `base_camera`; `cfg.robot_profile.*_camera = None`) and launches Isaac Sim without rendering; the task, its physics and+ its success check are AM-Bench's. Determinism, below, is why.+- **End state.** Isaac Lab resets an environment whose episode ended inside that very step (`DirectRLEnv.step` →+ `_reset_idx`), so after the last step the scene is already the next start. The tooling hashes the state just before that+ reset and reports it as the episode's `state_sha`.+- `reset()` runs in `torch.inference_mode`, as `step()` does (after a step Isaac Lab's buffers are inference tensors, and a+ reset outside that mode failed). The CLI and the recorder exit at once on an error: Isaac Sim can otherwise hang at exit.+- CLI: `replay` (one fresh-process replay, no cameras: the grader's), `film` (the rows with the cameras on, filmed: an+ illustration), `make-instance`, `run-actions`.++## Determinism (measured on Isaac Sim 5.1, GPU PhysX, RTX 4090, 2026-10-14)+- **Without the onboard cameras a fresh process replays the same rows bit for bit**: PressButton's rows, two fresh+ processes run side by side, the same state after 200 and 500 steps and the same end state (`fcd4de9b…`); every frozen+ instance's two fresh-process replays end in the same end state (Oracle).+- **With the cameras (Isaac renders every step) GPU PhysX becomes timing-dependent.** The same rows in fresh processes with+ the cameras on agreed after 200 steps and then parted: two runs ended in `7421b6ec…`, one in `fcd4de9b…` (all succeeded at+ step 1027). PhysX's enhanced determinism does not help (`7421b6ec…` again). Reading the camera images makes it worse: a+ replay that filmed both cameras every 4 steps ended without success. This is also why the expert's live episode (which+ reads the state between steps) ends elsewhere than the replays of its rows.+- So the grader, the reference recordings and the agent's default Session are camera-free; the cameras are for looking+ (`Session(cameras=True)`), and the instruction tells the agent to check every trajectory with the camera-free CLI.+- How it was missed at first: the first probes hashed the state after the last step, which Isaac Lab had already reset to+ the next start (End state, above); those hashes agreed while the end states did not.+- Only a process's first episode is guaranteed bit-identical; later resets in the same process need not be.+- The hashes are those of this GPU model; another GPU model may differ in the last bits (a trial is graded on the host it+ ran on; BUILD_ONLY "Check a build").++## Grading+Privileged: `tests/grade.py` replays `/app/output/trajectory.npz` twice, each in a fresh camera-free process+(`rcb_ambench.py replay`); success = AM-Bench's check held in both, the end states' hashes agree, and the rebuilt start+matches `initial_sha`. The verdict is written first; then a third process films the rows with the cameras on+(`/logs/verifier/replay.mp4`, an illustration: `video_episode_success`, never the reward). Whose failure a 0 is follows+YAMLab's grader: an unreadable deliverable is `bad_trajectory`, another task's file `wrong_task` (the agent's 0); a replay+without a result, a replay time-out or `instance_ok = 0` is `grader_error = infra_error = 1`. A replay process that ends+without a result (Isaac died; the CLI exits at once on an error instead of hanging) is run once more (`replay_retries`).+Each process has max(1800 s, 1500 s + runnable rows / 4), the runnable rows being the trajectory cut at the episode length;+`[verifier] timeout_sec = 9000` fits the three processes for PushSlider's 3120 rows plus one rerun. The first limits+(1200 s, 900 s + rows / 5) were too short: in the first PressButton oracle trial the verifier's first replay, a cold start+compiling its shaders on a host at load average ~100 with two other Isaac processes on the GPU, died in the scene build+("Failed to get DOF velocities from backend") and then hung until its limit (`infra_error`). The verifier runs with+`network_mode = "no-network"`: every web asset the scenes load is in the image (BUILD_ONLY, Data).++## Time budget (D8)+3600 s for every task (`scripts/task_cutoffs.toml`, the proposal's default; PROTOCOL §2.12), stated in each instruction's+closing `## Time limit` section. Every Python process pays ~2-6 min of Isaac Sim launch and scene build (the upper end with+other Isaac jobs on the GPU); stepping runs at about 9-15 control steps/s, so a full episode (20-26 s simulated) takes+3-5 min.++## Standard mode (planned)+Not in this set. Two things must be settled first: (1) a standard sidecar has to render the cameras for the agent's+observations, and rendering makes GPU PhysX timing-dependent (Determinism), so the live episode and fresh replays will+differ: the standard tasks would be graded by their live episode (PROTOCOL §4.8, as RoboDojo's non-reproducible tasks), or+the observations rendered by a second, camera-only process fed the physics state; (2) a `/kinematics` endpoint for a+floating-base arm.++## Declarations+- **Tooling: thin wrappers only.** The environment's own action, its state, its cameras, recording and replay. Task-level+ skills (reach, press, push, turn) are never added.+- **World-frame information (D7).** The privileged instructions give the full scene (the reset distributions and the+ frozen instance's state through the tooling).+- **Pointers to the reference solution.** The reference rows come from AM-Bench's public scripted experts; the image has+ none and the agent's egress cannot reach GitHub. `instance.json` names no expert (`mk_tasks.py` refuses one that does);+ the provenance is in `scripts/ambench/instances.json` only.+- **Upstream data.** Four of AM-Bench's USDs load files from NVIDIA's asset bucket by URL (the bin's geometry, the button's+ material, the robot's paint); the image holds copies and `images/ambench/localize_assets.py` rewrites the URLs to them.diff --git a/images/ambench/BUILD_ONLY b/images/ambench/BUILD_ONLYnew file mode 100644index 0000000000..7caa372e00--- /dev/null+++ b/images/ambench/BUILD_ONLY@@ -0,0 +1,71 @@+BUILD_ONLY: ghcr.io/mll-lab-nu/eai-ambench:<images/ambench/VERSION> is never pushed to a public registry (docs/PROTOCOL.md §2.4,+D5). Every evaluation host builds it locally; the AM-Bench tasks reference that tag and Harbor finds it in the local Docker+image store.++Why+ The image contains NVIDIA Isaac Sim 5.1 / Omniverse Kit and the pip wheels of the Isaac stack (from pypi.nvidia.com).+ NVIDIA licenses them for use, not for redistribution, so the built image may not be published. Everything else in it may+ be: AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0, including its robot and object USDs; a few files derived+ from Isaac Lab stay BSD-3-Clause, THIRD_PARTY_NOTICES.md in /opt/ambench), Isaac Lab (github.com/isaac-sim/IsaacLab+ @ f4aa17f, BSD-3-Clause), Pyroki (AM-Bench's fork github.com/ambench/pyroki @ 2eafc99, MIT) and acados+ (github.com/acados/acados @ fa0af20, BSD-2-Clause, built with qpOASES).++What the builder accepts+ - the NVIDIA Isaac Sim / Omniverse license agreement (the image sets OMNI_KIT_ACCEPT_EULA=YES and ACCEPT_EULA=Y, and every+ container that runs it accepts it again at launch);+ - NVIDIA's terms for the isaacsim wheels on pypi.nvidia.com and for the assets of NVIDIA's asset bucket listed in+ images/ambench/web_assets.txt;+ - the licences above (Apache-2.0, BSD-3-Clause, MIT, BSD-2-Clause).+ No account, key or token is needed: everything is downloaded anonymously.++What is left out on purpose+ AM-Bench's scripted experts (source/ambench/ambench/policies/scripted/: they solve the tasks; the task registrations'+ pointer to them is blanked), its policy-learning package (ambench_learn), its scripts, documentation and git history.+ The build fails if anything left in /opt/ambench/source still names them. The reference solutions live in the task+ directories' solution/ only (recorded by scripts/ambench/freeze.py with the expert mounted from a checkout outside the+ image).++Data+ The web assets the scenes would otherwise load from NVIDIA's asset bucket at run time are baked in under /opt/isaac-assets,+ mirroring the bucket's layout (images/ambench/web_assets.txt, each checked against its sha256): Isaac Lab's default+ ground, the wall's material, the TossBall bin's geometry (Container_B06, a payload: without it the bin has no collision)+ with its materials, the button's material and the robot's paint. The tooling points Isaac's asset root at the copies and+ localize_assets.py rewrites the URLs in four of AM-Bench's USDs to them. A task container has no general network access+ (the agent reaches only the model APIs and the package registries, the verifiers nothing), and Isaac Sim starts and+ renders offline. The frozen task instances live in the task directories.++Host+ Linux x86_64, Docker with the NVIDIA Container Toolkit, an RTX-class NVIDIA GPU with a driver Isaac Sim 5.1 supports (Isaac+ renders with RTX even headless, and AM-Bench runs PhysX on the GPU). Checked on an RTX 4090 (AMD Ryzen 9 7950X, driver+ 580.159). Build: ~60 GB of free disk during the build (the image is ~21.5 GB), network access to github.com, astral.sh,+ pypi.org, download.pytorch.org, pypi.nvidia.com and omniverse-content-production.s3*.amazonaws.com, about 30-45 min (acados+ compiles). Run: a camera-free simulator (the default, and the grader's replays) takes ~3 GB of host RAM and ~3 GB of GPU+ memory; with the two onboard cameras on (Session(cameras=True), the verifier's filmed illustration) ~13 GB and ~6.5 GB+ (Isaac's initialisation fails when the GPU runs out of memory: start fewer at once on a shared GPU). Physics runs on the+ GPU, so the recorded state hashes are those of this GPU model; another GPU model may need its own reference run (Check a+ build). Camera rendering makes GPU PhysX timing-dependent: only camera-free runs reproduce the hashes+ (docs/benchmarks/ambench.md, Determinism).++Build (from the repository root)+ docker build -f images/ambench/Dockerfile -t ghcr.io/mll-lab-nu/eai-ambench:$(cat images/ambench/VERSION) .+ The build follows AM-Bench's scripts/setup/install.sh (torch 2.7.0+cu128, Isaac Sim 5.1.0, Isaac Lab at YAMLab's commit,+ Pyroki with JAX 0.4.28 on the CPU, acados with qpOASES, AM-Bench), then sets every Python package to+ images/ambench/requirements.lock (the reference build's `uv pip freeze`) without resolving and fails unless the environment+ is exactly the lock.++Check a build+ The frozen instances must rebuild to their recorded state hashes, and a fresh-process replay of the reference trajectory+ must succeed and end in its recorded hash. With a task directory at hand:+ t=tasks/ambench-press-button-fahexa-i00-privileged+ docker run --rm --gpus all --shm-size 8g --network none -v $PWD/$t:/t ghcr.io/mll-lab-nu/eai-ambench:$(cat images/ambench/VERSION) \+ bash -c "cd /tmp && python /t/environment/rcb_ambench.py run-actions --instance /t/environment/instance.json \+ --actions /t/solution/oracle_actions.npy --out /tmp/t.npz && \+ python /t/environment/rcb_ambench.py replay --instance /t/environment/instance.json --traj /tmp/t.npz"+ expects instance_matches true, success true and, from the replay, the end state_sha of the task README's Verification+ section (the oracle's hash; both commands run camera-free). Or run `harbor run -p tasks/ambench-press-button-fahexa-i00-privileged -a oracle`.++On a CI machine (maintainers)+ A self-hosted runner with such a GPU builds the image with the command above when images/ambench/ changes, runs the check,+ and keeps the image in its local Docker store (or in a registry the organization keeps private), never on a public+ registry. Hosts of the same organization may copy a built image among themselves (docker save ... | zstd, docker load); a+ new VERSION means a rebuild on every host.diff --git a/images/ambench/Dockerfile b/images/ambench/Dockerfilenew file mode 100644index 0000000000..2b28450429--- /dev/null+++ b/images/ambench/Dockerfile@@ -0,0 +1,77 @@+# eai-ambench: AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0; aerial manipulation on Isaac Lab) on Isaac Sim 5.1.0 ++# Isaac Lab @ f4aa17f, torch 2.7.0+cu128, with AM-Bench's own controller dependencies at the commits its superproject pins+# (Pyroki @ 2eafc99 with JAX 0.4.28 on the CPU, acados @ fa0af20 built with qpOASES). What is left out on purpose: AM-Bench's+# scripted experts (source/ambench/ambench/policies/scripted/, the reference solutions; the task registrations' pointer to them is+# blanked), its policy-learning package (ambench_learn), its scripts, documentation and git history: nothing an agent can read+# here locates a solution (docs/PROTOCOL.md §2.7). The web assets the scenes load at run time (Isaac Lab's ground, the wall's+# material, the TossBall bin's geometry, the button's material, the robot's paint) are baked in under /opt/isaac-assets+# (images/ambench/web_assets.txt), mirroring the asset bucket's layout: the tasks run with closed egress.+# Tag = images/ambench/VERSION; build from the repo root (images/ambench/BUILD_ONLY has the command, licences and checks):+# docker build -f images/ambench/Dockerfile -t ghcr.io/mll-lab-nu/eai-ambench:$(cat images/ambench/VERSION) .+# Every Python package is pinned in images/ambench/requirements.lock (`uv pip freeze` of the reference build).+# BUILD_ONLY, never published: Isaac Sim 5.1 / Omniverse Kit may be installed and used but not redistributed.+# The layers up to Isaac Lab are YAMLab's (images/yamlab/Dockerfile), the same Isaac Sim / Isaac Lab stack.+FROM nvidia/cuda:12.8.1-base-ubuntu22.04+ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 UV_LINK_MODE=copy \+ NVIDIA_DRIVER_CAPABILITIES=all VK_DRIVER_FILES=/etc/vulkan/icd.d/nvidia_icd.json \+ OMNI_KIT_ACCEPT_EULA=YES ACCEPT_EULA=Y OMNI_KIT_ALLOW_ROOT=1 PRIVACY_CONSENT=N+RUN apt-get update && apt-get install -y --no-install-recommends \+ curl ca-certificates git git-lfs ffmpeg cmake build-essential \+ libvulkan1 libegl1 libgl1 libglvnd0 libglu1-mesa libx11-6 libxt6 libxext6 libxrender1 libxi6 libxrandr2 libxinerama1 \+ libxcursor1 libsm6 libice6 libgomp1 libglib2.0-0 libxkbcommon0 libxkbcommon-x11-0 libfontconfig1 libfreetype6 && \+ rm -rf /var/lib/apt/lists/* && mkdir -p /etc/vulkan/icd.d /etc/vulkan/implicit_layer.d /usr/share/glvnd/egl_vendor.d && \+ printf '{\n "file_format_version" : "1.0.0",\n "ICD" : {\n "library_path" : "libGLX_nvidia.so.0",\n "api_version" : "1.3.194"\n }\n}\n' > /etc/vulkan/icd.d/nvidia_icd.json && \+ printf '{\n "file_format_version" : "1.0.0",\n "layer": {\n "name": "VK_LAYER_NV_optimus",\n "type": "INSTANCE",\n "library_path": "libGLX_nvidia.so.0",\n "api_version" : "1.3.194",\n "implementation_version" : "1",\n "description" : "NVIDIA Optimus layer",\n "functions": {\n "vkGetInstanceProcAddr": "vk_optimusGetInstanceProcAddr",\n "vkGetDeviceProcAddr": "vk_optimusGetDeviceProcAddr"\n },\n "enable_environment": {\n "__NV_PRIME_RENDER_OFFLOAD": "1"\n },\n "disable_environment": {\n "DISABLE_LAYER_NV_OPTIMUS_1": ""\n }\n }\n}\n' > /etc/vulkan/implicit_layer.d/nvidia_layers.json && \+ printf '{\n "file_format_version" : "1.0.0",\n "ICD" : {\n "library_path" : "libEGL_nvidia.so.0"\n }\n}\n' > /usr/share/glvnd/egl_vendor.d/10_nvidia.json+RUN curl -LsSf https://astral.sh/uv/install.sh | sh+ENV PATH="/opt/venv/bin:/root/.local/bin:${PATH}" VIRTUAL_ENV=/opt/venv+RUN uv python install 3.11 && uv venv --seed -p 3.11 /opt/venv+# the GPU stack first (largest layers): torch 2.7.0+cu128, then Isaac Sim 5.1.0 from pypi.nvidia.com+RUN uv pip install torch==2.7.0 torchvision==0.22.0 --index-url https://download.pytorch.org/whl/cu128 && rm -rf /root/.cache/uv+RUN uv pip install "isaacsim[all,extscache]==5.1.0" --extra-index-url https://pypi.nvidia.com && rm -rf /root/.cache/uv+# Isaac Lab at YAMLab's pinned commit, its extensions only ("none": no RL frameworks)+RUN git clone -q https://github.com/isaac-sim/IsaacLab.git /opt/IsaacLab && cd /opt/IsaacLab && \+ git checkout -q f4aa17f87e2e5db5484f0b5974918573e8918ce2 && echo Yes | TERM=xterm ./isaaclab.sh --install none && rm -rf /root/.cache/pip /root/.cache/uv+# AM-Bench, scrubbed, with its Pyroki and acados submodules (the commits AM-Bench pins), installed as its scripts/setup/install.sh does+ARG AMBENCH_COMMIT=60bf5b73041df4eab571f7d9f0a297aeecbf2e0d+RUN git clone -q https://github.com/ambench/ambench.git /tmp/ambench && cd /tmp/ambench && git checkout -q "$AMBENCH_COMMIT" && \+ git submodule update -q --init --recursive ext/pyroki ext/acados && mkdir -p /opt/ambench/ext && \+ cp LICENSE THIRD_PARTY_NOTICES.md /opt/ambench/ && cp -r source /opt/ambench/source && \+ cp -r ext/pyroki ext/acados /opt/ambench/ext/ && cd / && rm -rf /tmp/ambench && \+ find /opt/ambench -name .git -prune -exec rm -rf {} + && \+ rm -rf /opt/ambench/source/ambench_learn /opt/ambench/source/ambench/ambench/policies/scripted && \+ find /opt/ambench/source -name "*.md" -delete && \+ sed -i -E 's/scripted_policy_entry_point="[^"]*"/scripted_policy_entry_point=""/' /opt/ambench/source/ambench/ambench/tasks/*/__init__.py && \+ if grep -rIn -e "policies.scripted" -e "policies/scripted" -e "ambench_learn" /opt/ambench/source; then echo "scrub incomplete"; exit 1; fi+RUN cd /opt/ambench && pip install --no-cache-dir -e ext/pyroki && pip install --no-cache-dir "numpy==1.26.0" "jax==0.4.28" "jaxlib==0.4.28" && \+ cmake -S ext/acados -B ext/acados/build -DACADOS_WITH_QPOASES=ON > /dev/null && \+ cmake --build ext/acados/build --target install --parallel 8 > /dev/null && \+ pip install --no-cache-dir -e ext/acados/interfaces/acados_template && pip install --no-cache-dir -e source/ambench+ENV JAX_PLATFORMS=cpu ACADOS_SOURCE_DIR=/opt/ambench/ext/acados \+ LD_LIBRARY_PATH=/opt/ambench/ext/acados/lib:/opt/ambench/ext/acados/build+# Web assets (each checked against its sha256), mirroring the bucket's layout: the tooling sets Isaac's asset root to+# /opt/isaac-assets/Assets/Isaac/5.1 (the ground, the wall's material), and localize_assets.py rewrites the URLs four of+# AM-Bench's USDs load from the bucket (the bin's geometry, the button's material, the robot's paint) to the copies. The USD+# rewrite uses a throwaway usd-core: Isaac Sim's own pxr loads only inside Kit.+COPY images/ambench/web_assets.txt images/ambench/localize_assets.py /opt/isaac-assets/+RUN set -e; grep -v '^#' /opt/isaac-assets/web_assets.txt | while read -r sha url dst; do \+ mkdir -p "$(dirname "$dst")"; curl -sSfL -o "$dst" "$url"; echo "$sha $dst" | sha256sum -c --quiet -; done; \+ A=/opt/ambench/source/ambench/ambench/assets; \+ python -m venv /tmp/usdv && /tmp/usdv/bin/pip install -q --no-cache-dir usd-core==25.5 && \+ /tmp/usdv/bin/python /opt/isaac-assets/localize_assets.py \+ https://omniverse-content-production.s3-us-west-2.amazonaws.com/=/opt/isaac-assets/ \+ https://omniverse-content-production.s3.us-west-2.amazonaws.com/=/opt/isaac-assets/ -- \+ $A/objects/container.usd $A/objects/push_button.usd \+ $A/robots/configuration/hexa_scorpion_base.usd $A/robots/configuration/end_effector_base.usd && \+ rm -rf /tmp/usdv+# Pin: the steps above follow AM-Bench's scripts/setup/install.sh; this one sets every package to the version of the reference+# build (images/ambench/requirements.lock, without resolving), and the build fails unless the result is exactly the lock+# (editable checkouts aside: Isaac Lab, Pyroki, acados_template and AM-Bench at the commits above).+COPY images/ambench/requirements.lock /opt/requirements.lock+RUN uv pip install --no-deps --index-strategy unsafe-best-match --extra-index-url https://download.pytorch.org/whl/cu128 \+ --extra-index-url https://pypi.nvidia.com -r /opt/requirements.lock && rm -rf /root/.cache/uv && \+ uv pip freeze --exclude-editable | diff - /opt/requirements.lock && echo "environment == requirements.lock"+# Kit caches (shaders, extension registry, user data) live under /cache so a task's compose can keep them in a volume+RUN mkdir -p /cache/ov-cache /cache/ov-data /cache/ov-logs /root/.cache /root/.local/share /root/.nvidia-omniverse /app/output && \+ ln -s /cache/ov-cache /root/.cache/ov && ln -s /cache/ov-data /root/.local/share/ov && ln -s /cache/ov-logs /root/.nvidia-omniverse/logs+WORKDIR /appdiff --git a/images/ambench/VERSION b/images/ambench/VERSIONnew file mode 100644index 0000000000..6e8bf73aa5--- /dev/null+++ b/images/ambench/VERSION@@ -0,0 +1 @@+0.1.0diff --git a/images/ambench/localize_assets.py b/images/ambench/localize_assets.pynew file mode 100644index 0000000000..c9e5898f67--- /dev/null+++ b/images/ambench/localize_assets.py@@ -0,0 +1,40 @@+"""Point AM-Bench's USDs at the image's copies of the web assets they load from NVIDIA's asset bucket (build step).++Four of AM-Bench's assets reference files on the bucket by URL: the TossBall bin (objects/container.usd payloads its geometry,+Container_B06), the button's material (objects/push_button.usd, Plastic_ABS.mdl) and the robot's paint (robots/configuration/+hexa_scorpion_base.usd and end_effector_base.usd, two vMaterials). The tasks run with closed egress, so the image bakes those+files in (images/ambench/web_assets.txt, sha256-checked, mirroring the bucket's layout under /opt/isaac-assets) and this script+rewrites the URLs in the USD layers to the local copies (the same files: the same scene). It writes each layer in its original+crate version and fails if any web asset path is left in a layer it was given. (images/robodojo/localize_assets.py's logic.)+ python localize_assets.py <remote prefix>=<local prefix> [...] -- <usd file>...+"""+import sys+from pxr import Sdf, UsdUtils++sep = sys.argv.index("--")+maps = [a.split("=", 1) for a in sys.argv[1:sep]]+files = sys.argv[sep + 1:]+changed = 0+for f in files:+ layer = Sdf.Layer.FindOrOpen(f)+ before = open(f, "rb").read(16)+ seen = []++ def fix(p):+ global changed+ for remote, local in maps:+ if p.startswith(remote):+ changed += 1+ return local + p[len(remote):]+ seen.append(p)+ return p+ UsdUtils.ModifyAssetPaths(layer, fix)+ layer.Save()+ after = open(f, "rb").read(16)+ left = [p for p in seen if p.startswith(("http://", "https://"))]+ print(f, "header", before[:12], "->", after[:12], "web paths left:", left)+ if left or before[:12] != after[:12]:+ sys.exit(f"{f}: web asset paths left {left} or crate version changed")+print("rewritten asset paths:", changed)+if not changed:+ sys.exit("nothing rewritten")diff --git a/images/ambench/requirements.lock b/images/ambench/requirements.locknew file mode 100644index 0000000000..28159a3d94--- /dev/null+++ b/images/ambench/requirements.lock@@ -0,0 +1,269 @@+absl-py==2.5.0+aioboto3==15.1.0+aiobotocore==2.24.0+aiodns==3.1.1+aiofiles==23.2.1+aiohappyeyeballs==2.4.4+aiohttp==3.11.11+aioitertools==0.11.0+aiosignal==1.3.2+annotated-types==0.8.0+antlr4-python3-runtime==4.9.3+anyio==4.14.2+anytree==2.13.0+asteval==1.0.6+asttokens==3.0.2+async-timeout==5.0.1+attrs==25.1.0+awscrt==0.23.8+azure-core==1.28.0+azure-identity==1.13.0+azure-storage-blob==12.17.0+boto3==1.39.11+botocore==1.39.11+casadi==3.8.1+certifi==2026.7.22+cffi==2.1.1+chardet==7.6.0+charset-normalizer==3.3.2+click==8.1.7+cloudpickle==3.1.2+cmeel==0.61.0+cmeel-assimp==5.4.3.1+cmeel-boost==1.83.0+cmeel-console-bridge==1.0.2.3+cmeel-octomap==1.10.0+cmeel-qhull==8.0.2.1+cmeel-tinyxml==2.6.2.3+cmeel-urdfdom==3.1.1.1+cmeel-zlib==1.3.2+colorlog==6.12.0+comm==0.2.3+contourpy==1.3.1+coverage==7.4.4+cryptography==44.0.0+cycler==0.11.0+cython==3.3.0+daqp==0.7.2+decorator==5.3.1+deprecated==1.3.1+dex-retargeting==0.4.6+docstring-parser==0.18.0+eigenpy==3.5.1+einops==0.8.2+embreex==4.4.0+executing==2.2.1+farama-notifications==0.0.6+fastapi==0.115.7+filelock==3.13.1+flaky==3.8.1+flatdict==4.0.0+fonttools==4.55.3+frozenlist==1.5.0+fsspec==2024.6.1+gitdb==4.0.12+gitpython==3.2.0+grpcio==1.84.0+gunicorn==23.0.0+gymnasium==1.2.1+h11==0.16.0+h5py==3.16.0+hf-xet==1.7.0+hidapi==0.14.0.post2+hpp-fcl==2.4.4+httpcore==1.0.9+httptools==0.6.1+httpx==0.28.1+huggingface-hub==0.36.2+hydra-core==1.3.7+idna==3.10+idna-ssl==1.1.0+imageio==2.37.0+imageio-ffmpeg==0.6.0+iniconfig==2.3.1+ipython==9.17.1+ipython-pygments-lexers==1.1.1+ipywidgets==8.1.5+isaacsim==5.1.0.0+isaacsim-app==5.1.0.0+isaacsim-asset==5.1.0.0+isaacsim-benchmark==5.1.0.0+isaacsim-code-editor==5.1.0.0+isaacsim-core==5.1.0.0+isaacsim-cortex==5.1.0.0+isaacsim-example==5.1.0.0+isaacsim-extscache-kit==5.1.0.0+isaacsim-extscache-kit-sdk==5.1.0.0+isaacsim-extscache-physics==5.1.0.0+isaacsim-gui==5.1.0.0+isaacsim-kernel==5.1.0.0+isaacsim-replicator==5.1.0.0+isaacsim-rl==5.1.0.0+isaacsim-robot==5.1.0.0+isaacsim-robot-motion==5.1.0.0+isaacsim-robot-setup==5.1.0.0+isaacsim-ros1==5.1.0.0+isaacsim-ros2==5.1.0.0+isaacsim-sensor==5.1.0.0+isaacsim-storage==5.1.0.0+isaacsim-template==5.1.0.0+isaacsim-test==5.1.0.0+isaacsim-utils==5.1.0.0+isodate==0.6.1+jax==0.4.28+jax-dataclasses==1.6.3+jaxlib==0.4.28+jaxlie==1.5.0+jaxls @ git+https://github.com/brentyi/jaxls.git@50a58be88c5ef74532f09e3f55268b4f02c490e3+jaxtyping==0.3.11+jedi==0.20.0+jinja2==3.1.6+jmespath==1.0.1+jsonschema==4.26.0+jsonschema-specifications==2025.9.1+junitparser==5.0.3+jupyterlab-widgets==3.0.17+kiwisolver==1.4.4+llvmlite==0.42.0+loguru==0.7.3+loop-rate-limiters==1.2.0+lxml==6.1.3+manifold3d==3.5.4+mapbox-earcut==2.1.0+markdown==3.11+markdown-it-py==4.2.0+markupsafe==2.1.3+matplotlib==3.10.3+matplotlib-inline==0.2.2+mdurl==0.1.2+ml-dtypes==0.5.4+moviepy==2.2.1+mpmath==1.3.0+msal==1.27.0+msal-extensions==1.0.0+msgspec==0.22.0+multidict==6.1.0+nest-asyncio==1.5.6+networkx==3.3+nlopt==2.7.1+numba==0.59.1+numpy==1.26.0+nvidia-cublas-cu12==12.8.3.14+nvidia-cuda-cupti-cu12==12.8.57+nvidia-cuda-nvrtc-cu12==12.8.61+nvidia-cuda-runtime-cu12==12.8.57+nvidia-cudnn-cu12==9.7.1.26+nvidia-cufft-cu12==11.3.3.41+nvidia-cufile-cu12==1.13.0.11+nvidia-curand-cu12==10.3.9.55+nvidia-cusolver-cu12==11.7.2.55+nvidia-cusparse-cu12==12.5.7.53+nvidia-cusparselt-cu12==0.6.3+nvidia-nccl-cu12==2.26.2+nvidia-nvjitlink-cu12==12.8.61+nvidia-nvtx-cu12==12.8.55+oauthlib==3.2.2+omegaconf==2.3.1+onnx==1.23.2+opencv-python-headless==4.11.0.86+opt-einsum==3.4.0+osqp==0.6.7.post3+packaging==23.0+parso==0.8.7+pexpect==4.9.0+pillow==11.3.0+pin==2.7.0+pin-pink==3.1.0+pint==0.20.1+pip==26.2.1+pluggy==1.6.0+portalocker==2.7.0+prettytable==3.3.0+proglog==0.1.12+prompt-toolkit==3.0.53+propcache==0.2.1+protobuf==7.36.2+psutil==7.2.2+ptyprocess==0.7.0+pure-eval==0.2.4+pycares==4.8.0+pycollada==0.9.3+pycparser==3.1+pydantic==2.11.10+pydantic-core==2.33.2+pyglet==1.5.31+pygments==2.21.0+pyjwt==2.15.1+pyliblzfse==0.4.1+pyparsing==3.0.9+pyperclip==1.8.0+pypng==0.20220715.0+pytest==9.1.1+pytest-mock==3.16.0+python-dateutil==2.9.0.post0+python-dotenv==1.2.4+python-multipart==0.0.20+pytransform3d==3.17.0+pytz==2024.1+pyyaml==6.0.2+qdldl==0.1.7.post5+qpsolvers==4.13.0+qrcode==7.4.2+quadprog==0.1.13+referencing==0.37.0+regex==2026.9.29+requests==2.32.3+requests-oauthlib==1.3.1+rich==14.3.4+robot-descriptions==3.3.0+rpds-py==2026.9.1+rtree==1.3.0+s3transfer==0.13.1+safetensors==0.8.0+scipy==1.15.3+sentry-sdk==2.29.1+setuptools==81.0.0+shapely==2.2.0+six==1.17.0+smmap==5.0.3+stack-data==0.6.3+starlette==0.49.1+svg-path==7.1+sympy==1.13.3+tensorboard==2.21.0+tensorboard-data-server==0.7.2+termcolor==3.3.0+tokenizers==0.22.2+toml==0.10.2+tomli==2.5.0+torch==2.7.0+cu128+torchaudio==2.7.0+torchvision==0.22.0+cu128+tornado==6.5.1+tqdm==4.70.1+traitlets==5.16.1+transformers==4.57.6+trimesh==4.5.1+triton==3.3.0+typeguard==4.6.0+typing-extensions==4.16.0+typing-inspection==0.4.2+tyro==1.0.16+urllib3==2.8.0+uvicorn==0.29.0+vhacdx==0.1.0+viser==1.1.1+wadler-lindig==0.1.7+warp-lang==1.18.0+watchdog==4.0.0+wcwidth==0.9.2+websockets==16.1.1+werkzeug==3.1.9+wheel==0.48.0+widgetsnbextension==4.0.16+wrapt==1.16.0+xatlas==0.0.11+xxhash==4.0.1+yarl==1.18.3+yourdfpy==0.0.60+zstandard==0.25.0diff --git a/images/ambench/web_assets.txt b/images/ambench/web_assets.txtnew file mode 100644index 0000000000..87d61847e5--- /dev/null+++ b/images/ambench/web_assets.txt@@ -0,0 +1,49 @@+# Web assets the AM-Bench scenes load at run time, baked into the image (images/ambench/Dockerfile): sha256, URL, path in the image.+# The tooling points Isaac's asset root (/persistent/isaac/asset_root/cloud) at /opt/isaac-assets/Assets/Isaac/5.1, which mirrors the bucket's layout.+# Isaac Lab's default ground (GroundPlaneCfg) and its textures; the wall material of AM-Bench's scenes (scenes/wall.py) and its textures:+8a21c317d638d33a4e6c20c958a7ed8f4d8c5195efd7e20f1b85178b4a15638a https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/Isaac/Environments/Grid/default_environment.usd /opt/isaac-assets/Assets/Isaac/5.1/Isaac/Environments/Grid/default_environment.usd+940b96ee8c8e53bd1acbc770d4ca0ac98bed9c96439ab386d1b27dbc9790cc4e https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/Isaac/Environments/Grid/Materials/Textures/Wireframe_blue.png /opt/isaac-assets/Assets/Isaac/5.1/Isaac/Environments/Grid/Materials/Textures/Wireframe_blue.png+deab39088eaf39ed7be951966c5e6bd5e58b90ab64743b0cdc8e5579fd5a99d9 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/Isaac/Environments/Grid/Materials/Textures/WireframeBlur_basecolor.png /opt/isaac-assets/Assets/Isaac/5.1/Isaac/Environments/Grid/Materials/Textures/WireframeBlur_basecolor.png+44fc0e82007bb0bd94631cd7ec45986a71ed74b9413899fbffac13efe151be4b https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/Isaac/Environments/Grid/Materials/Textures/WireframeBlur_blue.png /opt/isaac-assets/Assets/Isaac/5.1/Isaac/Environments/Grid/Materials/Textures/WireframeBlur_blue.png+74a1e02ff5f8357878613856e41ed3fab8ff38438d9e0201e7e611e9c7017f6e https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block.mdl /opt/isaac-assets/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block.mdl+d4fe6043d29eff01713e7f05bc94196c74a44111e2bf6cb498360d56ab24feac https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block/Concrete_Block_BaseColor.png /opt/isaac-assets/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block/Concrete_Block_BaseColor.png+7d656762be938870f0aefeb4fc063516bd3fbad725d2bcf4a190022a3c84925d https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block/Concrete_Block_Normal.png /opt/isaac-assets/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block/Concrete_Block_Normal.png+46dd082d557505452eca7b46c905b5a31843be2422552994be4420b8e0c3ea1e https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block/Concrete_Block_ORM.png /opt/isaac-assets/Assets/Isaac/5.1/NVIDIA/Materials/Base/Masonry/Concrete_Block/Concrete_Block_ORM.png+# The button's housing and plunger material (objects/push_button.usd; the URL is rewritten to this copy by localize_assets.py):+996caa235e62010e15fcf8c820ffdf502a3c276fc416d3f95298e325adf44616 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/5.1/NVIDIA/Materials/Base/Plastics/Plastic_ABS.mdl /opt/isaac-assets/Assets/Isaac/5.1/NVIDIA/Materials/Base/Plastics/Plastic_ABS.mdl+# The TossBall bin's geometry (objects/container.usd payloads it from the bucket by URL, rewritten to this copy: without it the bin has no collision), its+# material and the textures its shaders reference by relative path:+2a5688f81acce2315a2edd4d852d067ea3e25c6ea9fadddfcc4ef02b70bbfc1f https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Storage/Containers/Container_B/Container_B06_40x30x17cm_PR_V_NVD_01.usd /opt/isaac-assets/Assets/DigitalTwin/Assets/Warehouse/Storage/Containers/Container_B/Container_B06_40x30x17cm_PR_V_NVD_01.usd+8abe4a36ae566ed2fadbb8ec38c2bac8ad449f3671dccb9def6371b6293b9821 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Plastic_B.mdl /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Plastic_B.mdl+24eff6de7f41695ad77314c7f51b8f2a845af1ed44866aa16395c5d7390a1f32 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Black_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Black_A_Albedo.png+4d8e2f38c8c0cf1514fc8e11b7e52342259a3f8cf01f17b688a4d40340eefe2f https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Black_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Black_A_ORM.png+2b67ac657abb45ccd0fa3a94b59699972f8a2238e100ad558a5fe6f8a2474891 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Blue_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Blue_A_Albedo.png+46c623a21a7dd1f8dad4e959c39968dc853e7d4fb5d85b939bbb271d2ee0402d https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Blue_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Blue_A_ORM.png+85349c841faceec31214003b5acfabd10c42346e9c6c811613917b01fa4ebb3d https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Brown_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Brown_A_Albedo.png+3d1babfae258f5a473305b8bb3ec403e85f1dd6bb84954a81c2775d7a24a0670 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Brown_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Brown_A_ORM.png+6ff279d2b01dc468cbed8db880323f3915e310f3339e387f67ef575ec725a3b1 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Glossy_Black_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Glossy_Black_A_Albedo.png+d21ea9c313481bdd9422a6d386005506a46709e338d70d2becf851ea26aab3ed https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Glossy_Black_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Glossy_Black_A_ORM.png+45604d449bf31d0f956dfa990745da7bc54beb3bd017af0126f3abf5e7e065dd https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Gray_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Gray_A_Albedo.png+63e070b9c902612fe9af6d8d248f24decde3eceda288154217cc28c7c27e4b96 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Gray_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Gray_A_ORM.png+e9476e507d538b748c51216afa3f3286144edf1cf062309571cf9f2897651fb5 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Green_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Green_A_Albedo.png+63d636fc6668067c848c0b36d491d0d1c9d73bfcd8ee67e61c61fe582b4567be https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Green_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Green_A_ORM.png+017086a4fb5d697900eaa4f52a4918ad7d559405dc733e8af3b090efc5875300 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Normal_1k.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Normal_1k.png+08dac691bb6fe2248866a9f335280fed6233f9b7a1bc257a6ae5a11dc8da9f71 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Orange_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Orange_A_Albedo.png+47bf496092f8b3594966649e4e0168a9be461829919eabd34b955d272ccbcf0a https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Orange_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Orange_A_ORM.png+c0c44b42d69832fa25d0749a55d36e7d5aa1ceba445d1e48ff026f220bd0f28d https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_ORM_1k.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_ORM_1k.png+a2ec9e48b8d34257d1b59cbbc66ffd06877bda93b07f4c5a02c3e768442757b2 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Red_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Red_A_Albedo.png+be37c7a5204c0576f39a4d4ddbf39bdeb8501e2ac3237e92386acb8f025af175 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Red_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Red_A_ORM.png+a341d8082b299adfdd4d58cf8fa7836009e2f3f8a2f0fc581e80f48a876ca3cc https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Rough_Black_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Rough_Black_A_Albedo.png+8b9707920bb1be781509b280df8252d94e9503ae090955da37f15cc8e7afa924 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Rough_Black_A_Normal.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Rough_Black_A_Normal.png+db5525274146a6b6faa35521201760c443d995632b26c6c3afc371c8f20e7558 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Rough_Black_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Rough_Black_A_ORM.png+47c008cba92f2eb84f1315a99af191f7b26ac45018751e370b2adeab440be20a https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Violet_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Violet_A_Albedo.png+568ee54fe51eca439de5018a4e1e836cee94ed6b115abb5e4ab38ada5c88af65 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Violet_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Violet_A_ORM.png+8651c508aa80422f9e2b5581db259a59568acb2056b2d83517fa258cedb40be4 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_White_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_White_A_Albedo.png+9cce4d2e6ea569cd0efd01992d141abd0d9d82cf38f6b4caf36647db1765d6e9 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_White_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_White_A_ORM.png+4c06f981006f6774c5db34fd240d6a924d97c6c115af0b30ec0c47540e8fb193 https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Yellow_A_Albedo.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Yellow_A_Albedo.png+864426d2027461911904d07c3441276a9dc371bd1ace96ea581864dcf8b5959a https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Yellow_A_ORM.png /opt/isaac-assets/Assets/DigitalTwin/Materials/Base/Plastics/Textures/T_Plastic_Yellow_A_ORM.png+# The airframe's and the end effector's paint (robots/configuration/hexa_scorpion_base.usd, end_effector_base.usd; URLs rewritten):+bf0c306c067d0deceed98b5ef54a10086c5575f9244c4bdeaf84bfef9d37e018 https://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/2023_1/vMaterials_2/Paint/Carpaint/Carpaint_Metallic.mdl /opt/isaac-assets/Materials/2023_1/vMaterials_2/Paint/Carpaint/Carpaint_Metallic.mdl+00c226b573d873f241013ce76f2bb1fafe38e544719faae4b7c3494784563566 https://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/2023_1/vMaterials_2/Paint/Carpaint/textures/smudges_scratches_A_rough.jpg /opt/isaac-assets/Materials/2023_1/vMaterials_2/Paint/Carpaint/textures/smudges_scratches_A_rough.jpg+86b144bd3782c5f3aca93d79cb9ab9b7103d5ef478244719b78af8b43e1ac36c https://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/2023_1/vMaterials_2/Plastic/Polycarbonate_Opaque.mdl /opt/isaac-assets/Materials/2023_1/vMaterials_2/Plastic/Polycarbonate_Opaque.mdl+71d0318fab77b465e9b439071c55b9940aa5da133cb00855c29912a6b32d413b https://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/2023_1/vMaterials_2/Plastic/textures/plastic_smudges.jpg /opt/isaac-assets/Materials/2023_1/vMaterials_2/Plastic/textures/plastic_smudges.jpgdiff --git a/scripts/ambench/descr/press_button.json b/scripts/ambench/descr/press_button.jsonnew file mode 100644index 0000000000..e8d3a2f9a2--- /dev/null+++ b/scripts/ambench/descr/press_button.json@@ -0,0 +1,13 @@+{+ "task": "press_button",+ "env_id": "PressButton-Am-FAHexa-Abs-PID-Direct-v0",+ "title": "Press Button",+ "summary": "A wall stands in front of the hovering aerial manipulator, and a push button is mounted flat on the wall's front face, facing the robot: a red circular plunger in a dark-grey circular housing. Press the button, i.e. push its spring-loaded plunger into the housing, along the wall's normal, until it is depressed by at least 4 mm (40 % of its 10 mm travel).",+ "scene": "The ground is the world's z = 0 plane. In front of the robot stands an immovable (kinematic) wall: a slab 0.1 m thick, 2.0 m wide and 2.0 m tall with a concrete-block surface, its front face turned toward the robot. Its distance, its sideways offset and a small tilt (the top leaning toward or away from the robot) vary between instances. On the wall's front face sits a push button: a dark-grey circular housing, 12 mm thick, fixed flush to the wall, and in front of it a red circular plunger, 10 mm thick, whose face stands about 2 cm proud of the wall surface. The plunger is the only moving part: it slides along the wall's normal into the housing (10 mm of travel) and is spring-loaded, returning to its rest position when not pushed. Where the button sits on the central part of the wall varies between instances, and so does its face size (plunger diameter between 6 and 12 cm, housing proportionally 1.2 times wider). Nothing moves by itself. The robot starts hovering level and motionless, facing the wall, with its arm at its zero joint configuration (end effector a little ahead of and above the airframe) and the gripper closed.",+ "scene_privileged": "One environment; its origin is the world origin. Robot at every reset: base_link at (0, 0, 1.0) m with orientation (1, 0, 0, 0) wxyz (body +x is the world +x direction), zero velocity; arm_link1_pitch_joint = arm_link2_pitch_joint = arm_link3_pitch_joint = arm_link4_roll_joint = 0 rad; arm_lfinger_joint = arm_rfinger_joint = 0.001 m (their lower limit: gripper closed, gripper_width 0.002 m). By the robot's URDF kinematics this puts ee_link at about (0.227, 0, 1.124) m with identity orientation and the tool-tip point (ee_link origin + 0.18 m along the ee_link x axis) at about (0.407, 0, 1.124) m; the end-effector command is initialised to the current ee_link pose. Wall: kinematic cuboid 0.1 (x) x 2.0 (y) x 2.0 (z) m, nominal centre (2.0, 0.0, 1.0) m and orientation identity (front face the plane x = centre_x - 0.05, normal -x, toward the robot); friction 1.0 static / 1.0 dynamic, restitution 0; visual material NVIDIA Concrete_Block.mdl. At each reset (Isaac Lab mdp.reset_root_state_uniform) the centre becomes (2.0 + dx, 0.0 + dy, 1.0) with dx, dy ~ U(-0.2, 0.2) m independently, and the orientation becomes quat_from_euler_xyz(0, pitch, 0) with pitch ~ U(-0.2, 0.2) rad (a rotation about the world y axis through the wall centre; positive pitch tilts the top of the wall away from the robot, the front normal turning upward). Button: articulation push_button.usd with a fixed root (housing) and self-collisions disabled. At each reset, after the wall, its root is placed at wall_centre + R_wall (-0.05, by, bz) with by, bz ~ U(-0.3, 0.3) m independently (a point on the wall's front face, offset in the wall's own y-z plane) and given the wall's orientation, so the button's local +x is the wall normal pointing into the wall. Housing: cylinder along local x, radius 0.072 s, thickness 0.012 m (local x from -0.012 to 0), mass 0.5 kg, colour (0.1, 0.1, 0.1). Plunger (body 'plunger'; AM-Bench's goal_pos observation is its position): cylinder radius 0.06 s, thickness 0.01 m, authored at local x = -0.015 (its face about 2 cm in front of the wall surface), mass 0.02 kg, colour (0.9, 0.1, 0.1). Button physics material: static friction 0.6, dynamic 0.5, restitution 0.1. Prismatic joint PlungerSlideJoint along the button's local +x (positive = plunger pushed toward the wall), limits [0, 0.01] m, reset to 0 m with zero velocity every episode; Isaac Lab implicit actuator with stiffness 1000 N/m and damping 80 N s/m toward the target 0 m, effort limit 20 N, velocity limit 5 m/s. Scale s (applied to the button's local y and z only: face radius changes, thickness does not) ~ U(0.5, 1.0), drawn once when the environment is created (a prestartup event), not at each reset. Scene default physics material: friction 1.0 / 1.0, restitution 0.",+ "success": "Success when the button's prismatic joint PlungerSlideJoint has position >= 0.004 m (button_pressed_threshold; the joint ranges from 0 m, unpressed, to 0.01 m, fully pressed; positive = plunger pushed into the housing toward the wall). Evaluated after every control step (decimation 1, so after every 1/120 s physics step) on the simulated state; no hold time is required. The episode terminates at the first step where it holds. Otherwise it is truncated by the time limit: episode_length_s = 20 s, i.e. max_episode_length = 2400 control steps; AM-Bench raises the time-out when episode_length_buf >= max_episode_length - 1, i.e. at the 2399th step.",+ "failures": [],+ "goal_fixed": "",+ "difficulty_note": "The target is small (as little as 6 cm across), its place on the wall and the wall's tilt change per instance, and the plunger springs back: the 4 mm depression has to be produced by pushing along the (possibly tilted) wall normal from a free-flying, hovering base.",+ "standard_notes": "The button's pose and its pressed state are not given: the red disc on the concrete wall has to be found with the forward-looking onboard cameras and related to the robot through proprioception (base and end-effector poses). A press shows only as a few millimetres of plunger travel, and success is not reported during the episode."+}diff --git a/scripts/ambench/descr/push_slider.json b/scripts/ambench/descr/push_slider.jsonnew file mode 100644index 0000000000..76b6e368ba--- /dev/null+++ b/scripts/ambench/descr/push_slider.json@@ -0,0 +1,13 @@+{+ "task": "push_slider",+ "env_id": "PushSlider-Am-FAHexa-Abs-PID-Direct-v0",+ "title": "Push Slider",+ "summary": "A wall stands in front of the hovering aerial manipulator, with a horizontal slider mounted on its front face: a straight rail about 1 m long and a red knob that slides along it. The knob starts at the rail's left end (as seen from the robot facing the wall) and must be pushed along the rail until it is within 5 cm of the right end of its travel, i.e. at least 0.95 m along its 1 m travel.",+ "scene": "The ground is the world's z = 0 plane. In front of the robot stands an immovable (kinematic) wall: a slab 0.1 m thick, 2.0 m wide and 2.0 m tall with a concrete-block surface, its front face turned toward the robot. The wall is upright (no tilt in this task); its distance and sideways offset vary between instances. On its front face a slider fixture is mounted horizontally: a fixed rail 1.02 m long and 6 cm tall (a shallow channel standing about 3 cm out from the wall) and a red knob (a 4 x 4 x 6 cm block on a short stem, protruding about 7 cm from the wall surface) that slides along the rail over 1 m of travel. The fixture's height and sideways position on the wall vary between instances. The knob has no spring (it stays where it is left) but its motion is resisted by joint friction and damping. Nothing moves by itself. The robot starts hovering level and motionless, facing the wall, with its arm at its zero joint configuration (end effector a little ahead of and above the airframe) and the gripper closed.",+ "scene_privileged": "One environment; its origin is the world origin. Robot at every reset: base_link at (0, 0, 1.0) m with orientation (1, 0, 0, 0) wxyz (body +x is the world +x direction), zero velocity; arm_link1_pitch_joint = arm_link2_pitch_joint = arm_link3_pitch_joint = arm_link4_roll_joint = 0 rad; arm_lfinger_joint = arm_rfinger_joint = 0.001 m (their lower limit: gripper closed, gripper_width 0.002 m). By the robot's URDF kinematics this puts ee_link at about (0.227, 0, 1.124) m with identity orientation and the tool-tip point (ee_link origin + 0.18 m along the ee_link x axis) at about (0.407, 0, 1.124) m; the end-effector command is initialised to the current ee_link pose. Wall: kinematic cuboid 0.1 (x) x 2.0 (y) x 2.0 (z) m, nominal centre (2.0, 0.0, 1.0) m and orientation identity (front face the plane x = centre_x - 0.05, normal -x, toward the robot); friction 1.0 static / 1.0 dynamic, restitution 0; visual material NVIDIA Concrete_Block.mdl. At each reset (Isaac Lab mdp.reset_root_state_uniform) the centre becomes (2.0 + dx, 0.0 + dy, 1.0) with dx, dy ~ U(-0.2, 0.2) m independently; the configured pitch range is (-0, 0), so the wall keeps the identity orientation (upright, front normal -x). Slider: articulation slider_with_rail.usd with a fixed root body 'Rail' and self-collisions disabled. At each reset, after the wall, its root is placed at wall_centre + R_wall (-0.05, sy, sz) with sy, sz ~ U(-0.3, 0.3) m independently (on the wall's front face) and given the orientation R_wall composed with a 180 degree rotation about z, so the rail's local +x points toward the robot (world -x) and its local +y is world -y. Rail (rail frame, scaled 1.02 along y): base box 0.02 (x) x 1.02 (y) x 0.06 (z) m centred on the wall surface (half of it inside the wall), upper and lower edges 0.02 x 1.02 x 0.01 m at x = 0.02, z = +-0.025, edge covers 0.01 x 1.02 x 0.02 m at x = 0.025, z = +-0.018; mass 1 kg; no visual material bound. Knob (body 'Slider', gravity disabled, mass not authored so PhysX derives it from the collision shapes, colour (1, 0, 0)): a base plate 0.005 x 0.02 x 0.03 m at x = 0.017, a short connector cylinder, and a handle box 0.04 (x) x 0.04 (y) x 0.06 (z) m centred 0.052 m in front of the rail plane. Prismatic joint SliderJoint along the rail's local +y (world -y), limits [-0.5, 0.5] m, reset to -0.5 m with zero velocity every episode (knob at world y = root_y + 0.5, the robot's left end); positive motion moves the knob toward world -y. Isaac Lab implicit actuator (overriding the USD drive): stiffness 0, damping 5.0, joint friction 4.0 (static and dynamic), effort limit 1000, velocity limit 2.0 m/s. Scene default physics material: friction 1.0 / 1.0, restitution 0.",+ "success": "Success when the slider's prismatic joint SliderJoint has position >= 0.45 m (slider_pushed_threshold; the joint ranges from -0.5 m to 0.5 m and starts at -0.5 m), i.e. the knob has travelled at least 0.95 m from its start toward world -y (the robot's right). AM-Bench also reports a subtask criterion slider_engaged (joint position - start >= 0.05 x (0.45 - (-0.5)) = 0.0475 m); it is informational only. Evaluated after every control step (decimation 1, so after every 1/120 s physics step) on the simulated state; no hold time is required. The episode terminates at the first step where it holds. Otherwise it is truncated by the time limit: episode_length_s = 26 s, i.e. max_episode_length = 3120 control steps; AM-Bench raises the time-out when episode_length_buf >= max_episode_length - 1, i.e. at the 3119th step.",+ "failures": [],+ "goal_fixed": "",+ "difficulty_note": "The knob has to be driven 0.95 m, almost the whole length of the rail, in one direction against joint friction and damping, and the fixture's place on the wall changes per instance.",+ "standard_notes": "The fixture's pose and the knob's position along the rail are not given: the red knob and the rail on the concrete wall have to be located with the onboard cameras, and progress is visible only as the knob's position along the rail. Left and right refer to the robot's view of the wall at reset."+}diff --git a/scripts/ambench/descr/rotate_valve.json b/scripts/ambench/descr/rotate_valve.jsonnew file mode 100644index 0000000000..c9a6c3118b--- /dev/null+++ b/scripts/ambench/descr/rotate_valve.json@@ -0,0 +1,13 @@+{+ "task": "rotate_valve",+ "env_id": "RotateValve-Am-FAHexa-Abs-PID-Direct-v0",+ "title": "Rotate Valve",+ "summary": "A valve is mounted on the front face of a wall in front of the hovering aerial manipulator: a large red wheel disc on a short shaft, with a handle bar sticking out of the disc's face toward the robot. Turn the valve: rotate the wheel clockwise, as seen from the robot's side of the wall, by at least 170 degrees from its starting angle.",+ "scene": "The ground is the world's z = 0 plane. In front of the robot stands an immovable (kinematic) wall: a slab 0.1 m thick, 2.0 m wide and 2.0 m tall with a concrete-block surface, its front face turned toward the robot. The wall is upright (no tilt in this task); its distance and sideways offset vary between instances. A valve is mounted on the wall's front face with its axis perpendicular to the wall: a dark-blue circular base plate (about 47 cm across) fixed just in front of the wall, a short shaft, and a red disc of the same size that turns with the shaft. On the disc's robot-facing side, off the axis, is a handle bar (square cross-section about 6 cm, 16 cm long, parallel to the axis); at reset it sits directly below the hub (the 6 o'clock position), and it can also spin freely about its own long axis. The valve's height and sideways position on the wall vary between instances. The shaft has no spring and no end stops: it stays at whatever angle it is left, its motion resisted by damping and friction. Nothing moves by itself. The robot starts hovering level and motionless, facing the wall, with its arm at its zero joint configuration (end effector a little ahead of and above the airframe) and the gripper closed.",+ "scene_privileged": "One environment; its origin is the world origin. Robot at every reset: base_link at (0, 0, 1.0) m with orientation (1, 0, 0, 0) wxyz (body +x is the world +x direction), zero velocity; arm_link1_pitch_joint = arm_link2_pitch_joint = arm_link3_pitch_joint = arm_link4_roll_joint = 0 rad; arm_lfinger_joint = arm_rfinger_joint = 0.001 m (their lower limit: gripper closed, gripper_width 0.002 m). By the robot's URDF kinematics this puts ee_link at about (0.227, 0, 1.124) m with identity orientation and the tool-tip point (ee_link origin + 0.18 m along the ee_link x axis) at about (0.407, 0, 1.124) m; the end-effector command is initialised to the current ee_link pose. Wall: kinematic cuboid 0.1 (x) x 2.0 (y) x 2.0 (z) m, nominal centre (2.0, 0.0, 1.0) m and orientation identity (front face the plane x = centre_x - 0.05, normal -x, toward the robot); friction 1.0 static / 1.0 dynamic, restitution 0; visual material NVIDIA Concrete_Block.mdl. At each reset (Isaac Lab mdp.reset_root_state_uniform) the centre becomes (2.0 + dx, 0.0 + dy, 1.0) with dx, dy ~ U(-0.2, 0.2) m independently; the configured pitch range is (0, 0), so the wall keeps the identity orientation (upright, front normal -x). Valve: articulation valve.usd with a fixed root body base_link, self-collisions disabled, solver iterations 16 position / 4 velocity, spawned with scale (1.8, 1.0, 1.8) in the asset's own frame (radial dimensions x1.8, axial dimensions unchanged), mass_props mass = 0.05 kg set on each of the valve's rigid links (the USD authors 0.01 kg per link, 0.005 kg for the handle), contact offset 0.005 m, rest offset 0. At each reset, after the wall, base_link is placed at wall_centre + R_wall (-0.06, vy, vz) with vy, vz ~ U(-0.2, 0.2) m independently (the base-plate centre 0.01 m in front of the wall surface) with orientation R_wall composed with (0.5, 0.5, 0.5, 0.5) wxyz, so the shaft axis (base_link local +z) is world +x, pointing into the wall. Along the axis toward the robot, from the base-plate centre: blue base plate radius 0.234 m, thickness 0.015 m, colour (0.018, 0.115, 0.232); shaft radius 0.108 m from 0.0075 to 0.0475 m; red disc radius 0.234 m from 0.048 to 0.058 m (OmniPBR diffuse tint (0.99, 0.01, 0.01)); handle bar (body handle_link, 0.063 x 0.063 m cross-section, 0.16 m long along the axis) on the robot-facing side of the disc, below the hub at reset (the USD authors its centre 0.135 m out along the axis and 0.144 m below it after scaling, but its joint anchor on the disc is authored elsewhere, so the simulated pose follows the joint: read handle_link's position, which is AM-Bench's goal_pos observation). Joints: base_to_shaft, revolute about base_link +z (world +x), no position limits, reset to 0 rad with zero velocity every episode, Isaac Lab implicit actuator stiffness 0, damping 15.0, friction 0.2 (static and dynamic), effort limit 20, velocity limit 5.0 rad/s; shaft_to_disk fixed; disk_to_handle, revolute about the handle's long axis, unlimited, reset to 0, stiffness 0, damping 10.0, friction 0.1, effort limit 20, velocity limit 5.0 rad/s. Physics material on base plate, shaft and disc: static and dynamic friction 10000; the handle uses the scene default (friction 1.0 / 1.0, restitution 0).",+ "success": "Success when the valve has turned clockwise by at least 17/18 pi = 2.96706 rad (170 degrees; valve_target_angle): the unwrapped angle of the revolute joint base_to_shaft, counted from its 0 rad at the reset, is >= 2.96706 rad. Positive is the right-hand rotation about the shaft axis base_link +z, which points into the wall (world +x): clockwise when viewed from the robot's side, so a handle starting straight below the hub first moves toward world +y (the robot's left) and at 170 degrees is 10 degrees short of straight up. The joint has no limits, and PhysX reports its position wrapped into [-pi, pi] (s.objects() shows that raw value): AM-Bench's check compares that raw value, which a counter-clockwise turn of 190 degrees would also bring to +170 degrees, so the tooling (and the grader, with the same tooling) gives the check the unwrapped angle instead, the sum of the joint's per-step changes since the reset, readable as s.valve_angle() (rad). Only a clockwise turn counts; turning the wheel back counter-clockwise subtracts. AM-Bench also reports a subtask criterion valve_engaged (joint position >= 0.05 x 17/18 pi = 0.1484 rad); it is informational only. Evaluated after every control step (decimation 1, so after every 1/120 s physics step) on the simulated state; no hold time is required. The episode terminates at the first step where it holds. Otherwise it is truncated by the time limit: episode_length_s = 20 s, i.e. max_episode_length = 2400 control steps; AM-Bench raises the time-out when episode_length_buf >= max_episode_length - 1, i.e. at the 2399th step.",+ "failures": [],+ "goal_fixed": "",+ "difficulty_note": "The wheel has to be turned through nearly half a revolution in one direction against joint damping and friction, in front of a wall, and the valve's place on the wall changes per instance.",+ "standard_notes": "The valve's pose and angle are not given: the red disc, the blue base plate and the handle have to be located with the onboard cameras, and the turned angle can only be judged from the handle's position around the hub. Clockwise refers to the view from the robot's side of the wall."+}diff --git a/scripts/ambench/descr/toss_ball.json b/scripts/ambench/descr/toss_ball.jsonnew file mode 100644index 0000000000..0d8e23d835--- /dev/null+++ b/scripts/ambench/descr/toss_ball.json@@ -0,0 +1,13 @@+{+ "task": "toss_ball",+ "env_id": "TossBall-Am-FAHexa-Abs-PID-Direct-v0",+ "title": "Toss Ball",+ "summary": "The hovering aerial manipulator starts with a small red ball held between its gripper fingers, and an open-top grey storage bin stands on the ground some distance ahead of it. Deliver the ball into the bin: at some control step the ball must be inside the bin's volume and clear of the gripper while the robot's airframe is at least 0.7 m short of the bin's centre along the robot's initial forward direction.",+ "scene": "The ground is the world's z = 0 plane; there is no wall or other fixture. Ahead of the robot an immovable (kinematic) grey plastic storage container, an open-top tote 40 x 30 x 17 cm, rests on the ground; its forward distance and sideways offset vary between instances. A red ball, 8 cm in diameter, is a free rigid body: at every reset it is placed at the gripper's tool tip between the fingers and the gripper is commanded closed, so the robot starts holding it; once let go it falls under gravity. Nothing else moves by itself. The robot starts hovering level and motionless, facing the bin, with its arm at its zero joint configuration (end effector a little ahead of and above the airframe) and the gripper closed.",+ "scene_privileged": "One environment; its origin is the world origin. Robot at every reset: base_link at (0, 0, 1.0) m with orientation (1, 0, 0, 0) wxyz (body +x is the world +x direction), zero velocity; arm_link1_pitch_joint = arm_link2_pitch_joint = arm_link3_pitch_joint = arm_link4_roll_joint = 0 rad; arm_lfinger_joint = arm_rfinger_joint = 0.001 m (their lower limit: gripper closed, gripper_width 0.002 m). By the robot's URDF kinematics this puts ee_link at about (0.227, 0, 1.124) m with identity orientation and the tool-tip point (ee_link origin + 0.18 m along the ee_link x axis) at about (0.407, 0, 1.124) m; the end-effector command is initialised to the current ee_link pose. Container: container.usd, whose geometry is a payload (NVIDIA warehouse asset Container_B06_40x30x17cm, 'Gray' variant, convex-decomposition collision) referenced from NVIDIA's Omniverse content server; kinematic rigid body, scale (1, 1, 1) (container_size (0.4, 0.3, 0.17) m divided by the nominal size (0.4, 0.3, 0.17) m). At each reset (mdp.reset_root_state_uniform) its root is placed at (2.3 + cx', 0.0 + cy', 0.0) m with cx', cy' ~ U(-0.5, 0.5) m independently, orientation identity, zero velocity. Ball: sphere radius 0.04 m, mass 0.01 kg, colour (0.95, 0.05, 0.05), default rigid-body properties (gravity on), scene default physics material (friction 1.0 / 1.0, restitution 0). At each reset, after the robot has been reset, the ball is placed at the tool-tip point (ee_link origin + R(ee_link) (0.18, 0, 0)) with the ee_link orientation and zero velocity, and the gripper target is set to closed (-1, the finger joints' lower limit, 0.001 m per the URDF); the FA-Hexa defines no object-width converter, so the finger joints are not preset to the ball's width.",+ "success": "Success at a control step when all three hold at once: (1) ball_released: the distance from the ball centre to the gripper tool-tip point (ee_link position + R(ee_link) (0.18, 0, 0)) is >= 0.12 m; (2) the ball centre is inside (bounds inclusive) the world-axis-aligned box x in [cx - 0.20, cx + 0.20], y in [cy - 0.15, cy + 0.15], z in [cz, cz + 0.17], where (cx, cy, cz) is the container's root position (cz = 0), i.e. the full nominal 0.40 (x) x 0.30 (y) x 0.17 (z) m container size above its root; (3) robot_behind_bin: base_link x <= cx - 0.7. The ball need not come to rest: being inside the box at one step is enough. AM-Bench reports ball_released and ball_delivered as subtask criteria. Evaluated after every control step (decimation 1, so after every 1/120 s physics step) on the simulated state; no hold time is required. The episode terminates at the first step where it holds. Otherwise it is truncated by the time limit: episode_length_s = 10 s, i.e. max_episode_length = 1200 control steps; AM-Bench raises the time-out when episode_length_buf >= max_episode_length - 1, i.e. at the 1199th step.",+ "failures": [],+ "goal_fixed": "",+ "difficulty_note": "The airframe must stay at least 0.7 m short of the bin centre (along x) at the moment the ball is in the bin, the bin's position changes per instance, and the episode lasts only 10 s.",+ "standard_notes": "Neither the bin's position nor the ball's state is given: the bin has to be found with the forward-looking onboard cameras (the held ball sits just in front of the end-effector camera), and whether the ball got in can only be judged visually. The airframe's distance to the bin must be estimated from the images together with the base pose from proprioception."+}diff --git a/scripts/ambench/freeze.py b/scripts/ambench/freeze.pynew file mode 100755index 0000000000..5e62ee92c3--- /dev/null+++ b/scripts/ambench/freeze.py@@ -0,0 +1,183 @@+#!/usr/bin/env python3+"""Freeze one AM-Bench instance and record its reference rows (docs/benchmarks/ambench.md). Run on a host with docker, an+NVIDIA GPU and the image built (images/ambench/BUILD_ONLY); writes scripts/ambench/frozen/<task>-iNN/ and the task's entry+in scripts/ambench/instances.json.++ python3 scripts/ambench/freeze.py --task press_button --env-id PressButton-Am-FAHexa-Abs-PID-Direct-v0 --seed 0 --id 0 \\+ --expert <an AM-Bench checkout at the image's commit>/source/ambench/ambench/policies++1. record (in the image, --network none): the tooling's Session builds the instance (AM-Bench's seeded reset) and AM-Bench's+ scripted expert for the task, mounted read-only from the checkout OUTSIDE the image (the image has none: PROTOCOL §2.7),+ drives it in closed loop (no injected noise) until the episode ends; its rows are what the tooling executed, followed+ by --pad-s (2 s) of holding its last command. Writes instance.json (environment id, seed, the start's state hash) and+ oracle_actions.npy.+2. verify (in the image, no expert mounted): two replays with the grader's own CLI (`rcb_ambench.py replay`), each in a fresh+ process; both must succeed and end in the same state. `--verify-only` runs this step alone on the frozen rows (after a+ change of the tooling) and updates the hashes in instances.json.+The recording process's own episode need not be bit-identical to the replays (the expert reads the state in between); the+fresh-process replays are what the grader runs, so they decide.+"""+from __future__ import annotations+import argparse, json, os, pathlib, subprocess, sys, time++_ME = pathlib.Path(__file__).resolve()+ROOT = _ME.parents[2] if len(_ME.parents) > 2 else _ME.parent # (inside the image the script is /freeze/freeze.py)+HERE = ROOT / "scripts/ambench"+EXPERTS = {"PressButton": ("ambench.policies.scripted.press_button", "PressButtonPolicy"),+ "PushSlider": ("ambench.policies.scripted.push_slider", "PushSliderPolicy"),+ "RotateValve": ("ambench.policies.scripted.rotate_valve", "RotateValvePolicy"),+ "TossBall": ("ambench.policies.scripted.toss_ball", "TossBallPolicy")}+++def inside_record(env_id: str, seed: int, out: str, npz: str, pad_s: float, tries: int) -> int:+ """In the image: build the instance with the tooling, run the expert mounted at /expert, save its executed rows."""+ sys.path.insert(0, "/opt/tools")+ import importlib+ import numpy as np+ import rcb_ambench as R+ s = R.Session({"env_id": env_id, "seed": seed})+ import torch+ import ambench.policies as P+ P.__path__.append("/expert") # the expert, read-only, from outside the image+ mod, cls = EXPERTS[env_id.split("-")[0]]+ t0 = time.time()+ # Some experts sample their waypoints and timings from torch's RNG (TossBall's release); try k > 0 seeds that RNG with k+ # before the expert plans, on the same frozen instance, until one succeeds live (the replays decide afterwards)+ for k in range(tries):+ if k:+ s.reset(); torch.manual_seed(k)+ policy = getattr(importlib.import_module(mod), cls)(env=s.env, inject_noise=False)+ with torch.inference_mode():+ while not s.done:+ s.step(policy.advance(s.obs, 0).detach().cpu().numpy().reshape(-1))+ print("TRY " + json.dumps({"try": k, "success": s.succeeded, "control_steps": s.n_steps}), flush=True)+ if s.succeeded:+ break+ inst = {"env_id": env_id, "seed": seed, "task": env_id.split("-")[0], "action_dim": R.ACTION_DIM,+ "control_hz": R.CONTROL_HZ, "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha}+ o = pathlib.Path(out); o.mkdir(parents=True, exist_ok=True)+ (o / "instance.json").write_text(json.dumps(inst, indent=1) + "\n")+ rows = s.actions()+ # the expert's rows end where its live episode succeeded; a replay can be a step or two behind (the live episode's state+ # reads change its numerics), so the reference holds the last command a little longer: rows after the replay's own+ # success never run+ rows = np.vstack([rows, np.repeat(rows[-1:], int(round(pad_s * R.CONTROL_HZ)), axis=0)])+ np.save(o / "oracle_actions.npy", rows)+ np.savez(npz, task=np.array(env_id), actions=rows) # the same rows as a trajectory file, for the replays+ st = o.stat() # the files belong to the directory's (the host user's) owner+ for f in (o / "instance.json", o / "oracle_actions.npy", pathlib.Path(npz)):+ os.chown(f, st.st_uid, st.st_gid)+ print("RECORD " + json.dumps({**s.status(), "expert_try": k, "clipped": s.n_clipped, "wall_s": round(time.time() - t0, 1)}), flush=True)+ os._exit(0)+++def docker(args: list[str], mounts: dict[str, str], log: pathlib.Path, timeout: float = 2400.0, gpu: bool = True) -> str:+ """One container run; a run that hangs (Isaac can hang at exit after an error, e.g. out of GPU memory) is killed."""+ image = f"ghcr.io/mll-lab-nu/eai-ambench:{(ROOT / 'images/ambench/VERSION').read_text().strip()}"+ name = f"ambench-freeze-{log.stem}-{os.getpid()}"+ cmd = ["docker", "run", "--rm", "--name", name] + (["--gpus", "all"] if gpu else []) + ["--network", "none", "--shm-size", "8g",+ "-v", "rcb_ambench_freeze_cache:/cache"]+ for src, dst in mounts.items():+ cmd += ["-v", f"{src}:{dst}"]+ try:+ out = subprocess.run(cmd + [image] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=timeout).stdout+ except subprocess.TimeoutExpired as exc:+ subprocess.run(["docker", "kill", name], capture_output=True)+ out = (exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")) + "\n[freeze] killed: timeout\n"+ log.write_text(out)+ return out+++def last_json(text: str, prefix: str = "") -> dict:+ v = {}+ for line in text.splitlines():+ if line.startswith(prefix + "{"):+ try:+ v = json.loads(line[len(prefix):])+ except ValueError:+ pass+ return v+++def record(a, fz: pathlib.Path, logs: pathlib.Path, tools: dict) -> dict:+ """Step 1 in the image, with the expert mounted read-only from outside it."""+ out = docker(["python", "/freeze/freeze.py", "--inside-record", "--task", a.task, "--env-id", a.env_id, "--seed", str(a.seed),+ "--out", "/w", "--npz", f"/l/{a.task}-oracle.npz", "--pad-s", str(a.pad_s), "--tries", str(a.tries)],+ {**tools, str(pathlib.Path(a.expert).resolve()): "/expert:ro", str(fz.resolve()): "/w", str(logs.resolve()): "/l"},+ logs / f"{a.task}-record.log")+ rec = last_json(out, "RECORD ")+ print("record:", json.dumps(rec), flush=True)+ return rec+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--task", required=True); ap.add_argument("--env-id", required=True)+ ap.add_argument("--seed", type=int, default=0); ap.add_argument("--id", type=int, default=0)+ ap.add_argument("--expert", help="AM-Bench's policies/ directory (outside the image)")+ ap.add_argument("--logs", default="/tmp/ambench-freeze-logs")+ ap.add_argument("--pad-s", type=float, default=2.0, help="seconds of holding the expert's last command after its rows")+ ap.add_argument("--tries", type=int, default=1, help="expert runs (try k > 0 seeds torch's RNG with k) until one succeeds live")+ ap.add_argument("--verify-only", action="store_true",+ help="no recording: replay the frozen rows (step 2) and update the task's hashes in instances.json")+ ap.add_argument("--inside-record", action="store_true", help=argparse.SUPPRESS)+ ap.add_argument("--out", help=argparse.SUPPRESS); ap.add_argument("--npz", help=argparse.SUPPRESS)+ a = ap.parse_args()+ if a.inside_record:+ try:+ return inside_record(a.env_id, a.seed, a.out, a.npz, a.pad_s, a.tries)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error+ import traceback+ traceback.print_exc(); sys.stdout.flush(); sys.stderr.flush(); os._exit(1)+ fz = HERE / "frozen" / f"{a.task}-i{a.id:02d}"+ logs = pathlib.Path(a.logs); logs.mkdir(parents=True, exist_ok=True); fz.mkdir(parents=True, exist_ok=True)+ tools = {str(HERE / "shared"): "/opt/tools:ro", str(pathlib.Path(__file__).resolve().parent): "/freeze:ro"}+ if a.verify_only:+ rec: dict = {}+ # the frozen rows as a trajectory file (numpy is in the image, not necessarily on the host)+ docker(["python", "-c", "import numpy as np, os, sys; p = '/l/' + sys.argv[1] + '-oracle.npz'; "+ "np.savez(p, task=np.array(sys.argv[2]), actions=np.load('/w/oracle_actions.npy')); st = os.stat('/l'); "+ "os.chown(p, st.st_uid, st.st_gid)", a.task, a.env_id],+ {str(fz.resolve()): "/w:ro", str(logs.resolve()): "/l"}, logs / f"{a.task}-npz.log", gpu=False)+ else:+ if not a.expert:+ ap.error("--expert is required (or --verify-only)")+ rec = record(a, fz, logs, tools)+ if not rec.get("success"):+ print(f"the expert did not succeed (log {logs}/{a.task}-record.log)"); return 1+ reps = []+ for i in (1, 2):+ o = docker(["python", "/opt/tools/rcb_ambench.py", "replay", "--instance", "/w/instance.json", "--traj", f"/l/{a.task}-oracle.npz"],+ {**tools, str(fz.resolve()): "/w:ro", str(logs.resolve()): "/l:ro"}, logs / f"{a.task}-replay{i}.log")+ r = last_json(o); reps.append(r)+ print(f"replay {i}:", json.dumps(r), flush=True)+ outs = [(r.get("replays") or [{}])[0] for r in reps]+ ok = all(r.get("instance_matches") for r in reps) and all(o.get("success") for o in outs) and len({o.get("state_sha") for o in outs}) == 1+ if not ok:+ print("the fresh-process replays do not both succeed in the same state: not frozen"); return 1+ import fcntl+ reg_p = HERE / "instances.json"+ lock = open(HERE / ".instances.lock", "w"); fcntl.flock(lock, fcntl.LOCK_EX) # parallel freezes+ reg = json.loads(reg_p.read_text()) if reg_p.exists() else {"modes": ["privileged"], "tasks": {}}+ inst = json.loads((fz / "instance.json").read_text())+ entry = reg["tasks"].get(a.task, {}) if a.verify_only else {+ "provenance": "AM-Bench's scripted expert for the task (policies/scripted, no injected noise), run in closed loop on "+ "this instance by scripts/ambench/freeze.py"+ + (f" (expert try {rec['expert_try']}: torch's RNG seeded with {rec['expert_try']} before it planned; the "+ "earlier tries did not succeed live)" if rec.get("expert_try") else "")+ + f", followed by {a.pad_s:g} s of holding its last command",+ "recorded": time.strftime("%Y-%m-%d")}+ reg["tasks"][a.task] = {"id": a.id, "env_id": a.env_id, "seed": a.seed, "initial_sha": inst["initial_sha"],+ "oracle_rows": int(outs[0]["executed_rows"]), "oracle_final_sha": outs[0]["state_sha"],+ "provenance": entry.get("provenance", ""), "recorded": entry.get("recorded", ""),+ "verified": time.strftime("%Y-%m-%d") + ": two fresh-process replays with the grader's CLI succeed "+ "at control step %d and end in the same state" % int(outs[0]["executed_rows"])}+ reg["tasks"] = dict(sorted(reg["tasks"].items()))+ reg_p.write_text(json.dumps(reg, indent=1) + "\n")+ fcntl.flock(lock, fcntl.LOCK_UN); lock.close(); (HERE / ".instances.lock").unlink(missing_ok=True)+ print(f"frozen {fz.relative_to(ROOT)}: success at row {outs[0]['executed_rows']}, end state {outs[0]['state_sha'][:16]}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/ambench/frozen/press_button-i00/instance.json b/scripts/ambench/frozen/press_button-i00/instance.jsonnew file mode 100644index 0000000000..f10d0c326a--- /dev/null+++ b/scripts/ambench/frozen/press_button-i00/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "PressButton-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "PressButton",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 20.0,+ "initial_sha": "c125ec8a4fdd266248f2224493e8e50fd06b6648f7a21ca8568d8dd84267acd8"+}diff --git a/scripts/ambench/frozen/press_button-i00/oracle_actions.npy b/scripts/ambench/frozen/press_button-i00/oracle_actions.npynew file mode 100644index 0000000000..67efe0cd51Binary files /dev/null and b/scripts/ambench/frozen/press_button-i00/oracle_actions.npy differdiff --git a/scripts/ambench/frozen/push_slider-i00/instance.json b/scripts/ambench/frozen/push_slider-i00/instance.jsonnew file mode 100644index 0000000000..9f8b869b25--- /dev/null+++ b/scripts/ambench/frozen/push_slider-i00/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "PushSlider-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "PushSlider",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 26.0,+ "initial_sha": "9bd26bad8cd1cd81a7fcc11043a996206a0550e7e00f2a74253efe1822ced584"+}diff --git a/scripts/ambench/frozen/push_slider-i00/oracle_actions.npy b/scripts/ambench/frozen/push_slider-i00/oracle_actions.npynew file mode 100644index 0000000000..d986cbad88Binary files /dev/null and b/scripts/ambench/frozen/push_slider-i00/oracle_actions.npy differdiff --git a/scripts/ambench/frozen/rotate_valve-i00/instance.json b/scripts/ambench/frozen/rotate_valve-i00/instance.jsonnew file mode 100644index 0000000000..b8a814fc56--- /dev/null+++ b/scripts/ambench/frozen/rotate_valve-i00/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "RotateValve-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "RotateValve",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 20.0,+ "initial_sha": "5bfceb57120de994dca306348115910883573b611ba46d353754ebd5911772d4"+}diff --git a/scripts/ambench/frozen/rotate_valve-i00/oracle_actions.npy b/scripts/ambench/frozen/rotate_valve-i00/oracle_actions.npynew file mode 100644index 0000000000..bf350d9841Binary files /dev/null and b/scripts/ambench/frozen/rotate_valve-i00/oracle_actions.npy differdiff --git a/scripts/ambench/instances.json b/scripts/ambench/instances.jsonnew file mode 100644index 0000000000..dd06e08457--- /dev/null+++ b/scripts/ambench/instances.json@@ -0,0 +1,40 @@+{+ "modes": [+ "privileged"+ ],+ "tasks": {+ "press_button": {+ "id": 0,+ "env_id": "PressButton-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "initial_sha": "c125ec8a4fdd266248f2224493e8e50fd06b6648f7a21ca8568d8dd84267acd8",+ "oracle_rows": 1027,+ "oracle_final_sha": "fcd4de9b60a77009d4e58851b0984a81c9de0cd5407c99d84d0fba593a56d278",+ "provenance": "AM-Bench's scripted expert for the task (policies/scripted, no injected noise), run in closed loop on this instance by scripts/ambench/freeze.py, followed by 2 s of holding its last command",+ "recorded": "2026-10-14",+ "verified": "2026-10-14: two fresh-process replays with the grader's CLI succeed at control step 1027 and end in the same state"+ },+ "push_slider": {+ "id": 0,+ "env_id": "PushSlider-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "initial_sha": "9bd26bad8cd1cd81a7fcc11043a996206a0550e7e00f2a74253efe1822ced584",+ "oracle_rows": 1353,+ "oracle_final_sha": "01a85d356fead490fb2deb77025673bc0b11df3f13613f21af945eea16ca470c",+ "provenance": "AM-Bench's scripted expert for the task (policies/scripted, no injected noise), run in closed loop on this instance by scripts/ambench/freeze.py, followed by 2 s of holding its last command",+ "recorded": "2026-10-14",+ "verified": "2026-10-14: two fresh-process replays with the grader's CLI succeed at control step 1353 and end in the same state"+ },+ "rotate_valve": {+ "id": 0,+ "env_id": "RotateValve-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "initial_sha": "5bfceb57120de994dca306348115910883573b611ba46d353754ebd5911772d4",+ "oracle_rows": 1002,+ "oracle_final_sha": "1b976104a88384d6d7c889a32d307a7f6f91f2563660710c4b4ab3ef3cfadc1e",+ "provenance": "AM-Bench's scripted expert for the task (policies/scripted, no injected noise), run in closed loop on this instance by scripts/ambench/freeze.py, followed by 2 s of holding its last command",+ "recorded": "2026-10-14",+ "verified": "2026-10-14: two fresh-process replays with the grader's CLI succeed at control step 1002 and end in the same state"+ }+ }+}diff --git a/scripts/ambench/mk_tasks.py b/scripts/ambench/mk_tasks.pynew file mode 100644index 0000000000..bd2e2f3a8d--- /dev/null+++ b/scripts/ambench/mk_tasks.py@@ -0,0 +1,196 @@+#!/usr/bin/env python3+"""Generate the AM-Bench tasks: tasks/ambench-<task>-fahexa-iNN-<mode> for every frozen instance in scripts/ambench/instances.json+and every mode its `modes` lists (for now `privileged`; a standard twin needs template/standard/; docs/benchmarks/ambench.md).++ python3 scripts/ambench/mk_tasks.py # (re)write every AM-Bench task dir; `git diff tasks/` stays empty+ python3 scripts/ambench/mk_tasks.py --check # write nothing; exit 1 if a task dir differs from the generator's+Then `cd tasks && harbor add --scan .` when a digest changed. Needs only Python 3 (no simulator).++Inputs, all in the repository:+ scripts/ambench/instances.json per task: the frozen instance (id NN = task iNN), its hashes and its provenance+ scripts/ambench/frozen/<task>-iNN/ instance.json (the environment id, the seed, the start's state hash) and+ oracle_actions.npy (the expert's recorded rows, one per control step)+ scripts/ambench/descr/<task>.json what the task asks and exactly what its check tests, written from the task's code+ (summary / scene: both modes; scene_privileged: privileged mode only)+ scripts/ambench/shared/rcb_ambench.py the tooling (privileged environment/ + tests/, standard environment/sim/)+ scripts/ambench/template/<mode>/ every other task file; a *.tmpl file is filled with the instance's values (@@KEY@@)+ scripts/eai_standard/ the eai-standard/2.2 layer, copied unchanged, and the standard client (client.env)+ images/ambench/VERSION the base image tag+Both twins are written to a scratch directory, passed through scripts/task_conventions.py's normalize() and synced into+tasks/: a task dir holds exactly what the generator writes."""+from __future__ import annotations+import argparse, json, os, pathlib, re, sys, tempfile++ROOT = pathlib.Path(__file__).resolve().parents[2]+HERE = ROOT / "scripts/ambench"+LAYER = ROOT / "scripts/eai_standard"+REGISTRY = "ghcr.io/mll-lab-nu"+CLIENT = dict(l.split("=", 1) for l in (LAYER / "client.env").read_text().splitlines() if "=" in l and not l.startswith("#"))+MODES = ("privileged", "standard")+COORD = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def toml_str(s: str) -> str:+ return s.replace("\\", "\\\\").replace('"', '\\"')+++def base(task: str, i: int) -> str:+ return f"ambench-{task.replace('_', '-')}-fahexa-i{i:02d}"+++def normalizer():+ sys.path.insert(0, str(ROOT / "scripts"))+ from task_conventions import normalize+ return normalize+++def agent_timeout(mode: str) -> int:+ sys.path.insert(0, str(ROOT / "scripts"))+ from task_conventions import cutoff_sec+ return cutoff_sec("AM-Bench", mode)+++def fill(text: str, values: dict) -> str:+ for k, v in values.items():+ text = text.replace(f"@@{k}@@", v)+ if "@@" in text:+ raise RuntimeError(f"unfilled placeholder near {text[text.index('@@'):][:40]!r}")+ return text+++def num(v) -> str:+ return f"{v:g}" if isinstance(v, float) else str(v)+++def plan_instance(task: str, R: dict, version: str, modes) -> dict[str, dict[str, tuple[bytes, int]]]:+ i = int(R["id"])+ D = json.loads((HERE / "descr" / f"{task}.json").read_text())+ fz = HERE / "frozen" / f"{task}-i{i:02d}"+ inst_b = (fz / "instance.json").read_bytes(); I = json.loads(inst_b)+ oracle_b = (fz / "oracle_actions.npy").read_bytes()+ if I["env_id"] != D["env_id"] or I.get("initial_sha") != R["initial_sha"] or int(I["seed"]) != int(R["seed"]):+ raise RuntimeError(f"{fz}: instance.json does not match descr / instances.json (env_id, seed, initial_sha)")+ if any(k in I for k in ("provenance", "expert", "source")) or re.search(rb"scripted|expert|policies", inst_b, re.I):+ raise RuntimeError(f"{fz}: instance.json names its source; provenance belongs in instances.json only (PROTOCOL §2.7)")+ for key in ("summary", "scene", "standard_notes"):+ hits = [m.group(0) for m in COORD.finditer(D[key])]+ if hits:+ raise RuntimeError(f"descr/{task}.json {key}: a world coordinate {hits[:2]} in a text standard mode shows")+ tool = (HERE / "shared/rcb_ambench.py").read_bytes()+ image = f"{REGISTRY}/eai-ambench:{version}"+ ep = float(I["episode_length_s"])+ fails = "".join(f"- {f}\n" for f in D.get("failures") or [])+ fails = ("\nIt also ends, as a failure, when:\n" + fails) if fails else ""+ goals = f"\n**Goal geometry.** {D['goal_fixed']}\n" if D.get("goal_fixed") else ""+ common = {"TITLE": D["title"], "INST": f"i{i:02d}", "PRIV": f"{base(task, i)}-privileged", "STD": f"{base(task, i)}-standard",+ "ENV_ID": I["env_id"], "IMAGE": image, "CLIENT_IMAGE": CLIENT["CLIENT_IMAGE"].strip(), "SEED": str(int(I["seed"])),+ "FAMILY": f"{task}_fahexa", "GOAL_TOML": toml_str("Task: " + D["summary"]), "SUMMARY": D["summary"], "SCENE": D["scene"],+ "GOALS": goals, "SUCCESS": D["success"], "EPISODE_S": num(ep), "EPISODE_ROWS": str(int(round(ep * 120)) - 1),+ "FAILURES": fails, "README_GOAL": D["summary"], "DIFFICULTY": D["difficulty_note"], "N_ORACLE": str(R["oracle_rows"]),+ "ORACLE_SIM_S": num(round(R["oracle_rows"] / 120, 3)), "ORACLE_SHA": R["oracle_final_sha"][:16],+ "INITIAL_SHA_SHORT": I["initial_sha"][:16], "FROZEN": f"{task}-i{i:02d}", "STANDARD_NOTES": D["standard_notes"]}+ texts = {"task_text": f"{D['title']}: {D['summary']} Success: {D['success']}" + (f" Goal geometry: {D['goal_fixed']}" if D.get("goal_fixed") else ""),+ "episode": (f"one episode, no reset: it ends at the first control step where AM-Bench's success check holds, when the task's "+ f"episode length of {num(ep)} s of simulated time runs out (AM-Bench's time-out, at control step {int(round(ep * 120)) - 1}), when your time is up, "+ f"or on a simulator error; the simulated clock advances only with the control steps you run")}+ out: dict[str, dict[str, tuple[bytes, int]]] = {}+ for mode in modes:+ common["AGENT_TIMEOUT_S"] = str(agent_timeout(mode))+ extra = {"SCENE_PRIVILEGED": D["scene_privileged"]} if mode == "privileged" else {}+ files: dict[str, tuple[bytes, int]] = {}+ tdir = HERE / "template" / mode+ for p in sorted(tdir.rglob("*")):+ if not p.is_file() or "__pycache__" in p.parts:+ continue+ rel = p.relative_to(tdir).as_posix()+ if rel.endswith(".tmpl"):+ rel = rel[:-5]; data = fill(p.read_text(), {**common, **extra}).encode()+ else:+ data = p.read_bytes()+ files[rel] = (data, 0o755 if rel.endswith(".sh") else 0o644)+ if mode == "privileged":+ for rel in ("environment/rcb_ambench.py", "tests/rcb_ambench.py"):+ files[rel] = (tool, 0o644)+ for rel in ("environment/instance.json", "tests/instance.json"):+ files[rel] = (inst_b, 0o644)+ files["solution/oracle_actions.npy"] = (oracle_b, 0o644)+ else:+ files["environment/sim/rcb_ambench.py"] = (tool, 0o644)+ files["environment/sim/instance.json"] = (inst_b, 0o644)+ files["environment/sim/texts.json"] = ((json.dumps(texts, indent=1, ensure_ascii=False) + "\n").encode(), 0o644)+ for rel, src in (("environment/rcb_client.py", "rcb_client.py"), ("environment/rcb1.py", "rcb1.py"),+ ("environment/sim/rcb_limited.py", "rcb_limited.py"), ("environment/sim/rcb1.py", "rcb1.py"),+ ("environment/sim/run.sh", "run.sh")):+ files[rel] = ((LAYER / src).read_bytes(), 0o755 if rel.endswith(".sh") else 0o644)+ req = CLIENT.get("CLIENT_REQUIREMENTS", "client-requirements.txt").strip()+ files["environment/client-requirements.txt"] = ((LAYER / req).read_bytes(), 0o644)+ files["solution/oracle_qpos.npy"] = (oracle_b, 0o644)+ files["solution/oracle_meta.json"] = (json.dumps({"K": 1, "interpolate": "hold", "source": "the privileged oracle's rows"}, indent=1).encode() + b"\n", 0o644)+ out[f"{base(task, i)}-{mode}"] = files+ return out+++def normalized(planned, normalize):+ out = {}+ with tempfile.TemporaryDirectory(prefix="ambench_mk_") as td:+ for name, files in planned.items():+ for rel, (data, mode) in files.items():+ p = pathlib.Path(td) / name / rel; p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(data)+ os.chmod(p, 0o755 if mode & 0o100 else 0o644)+ for name in planned:+ normalize(pathlib.Path(td) / name)+ for name in planned:+ t = pathlib.Path(td) / name+ out[name] = {p.relative_to(t).as_posix(): (p.read_bytes(), 0o755 if p.stat().st_mode & 0o100 else 0o644)+ for p in sorted(t.rglob("*")) if p.is_file() and "__pycache__" not in p.parts}+ return out+++def sync(task: pathlib.Path, files: dict, check: bool) -> list[str]:+ diffs = []+ have = {p.relative_to(task).as_posix() for p in task.rglob("*") if p.is_file() or p.is_symlink()} if task.exists() else set()+ have = {h for h in have if "__pycache__" not in h.split("/")}+ for rel in sorted(have - set(files)):+ diffs.append(f"remove {task.name}/{rel}")+ if not check:+ (task / rel).unlink()+ for rel, (data, mode) in sorted(files.items()):+ p = task / rel+ same = p.is_file() and not p.is_symlink() and p.read_bytes() == data and bool(p.stat().st_mode & 0o100) == bool(mode & 0o100)+ if not same:+ diffs.append(f"write {task.name}/{rel}")+ if not check:+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_bytes(data)+ m = p.stat().st_mode & 0o777+ os.chmod(p, m | 0o111 if mode & 0o100 else m & ~0o111)+ if not check and task.exists():+ for d in sorted((p for p in task.rglob("*") if p.is_dir()), key=lambda p: -len(p.parts)):+ if not any(d.iterdir()):+ d.rmdir()+ return diffs+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--check", action="store_true")+ a = ap.parse_args()+ reg = json.loads((HERE / "instances.json").read_text())+ modes = tuple(reg.get("modes", MODES))+ version = (ROOT / "images/ambench/VERSION").read_text().strip()+ normalize = normalizer()+ diffs, made = [], set()+ for task in sorted(reg["tasks"]):+ for name, files in normalized(plan_instance(task, reg["tasks"][task], version, modes), normalize).items():+ made.add(name); diffs += sync(ROOT / "tasks" / name, files, a.check)+ for t in sorted((ROOT / "tasks").glob("ambench-*")):+ if t.is_dir() and t.name not in made:+ diffs.append(f"stale {t.name} (not in instances.json)")+ for d in diffs:+ print(d)+ print(f"{'checked' if a.check else 'generated'} {len(made)} AM-Bench task dirs: {len(diffs)} difference(s)")+ return 1 if (a.check and diffs) else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/ambench/shared/rcb_ambench.py b/scripts/ambench/shared/rcb_ambench.pynew file mode 100644index 0000000000..623d3522c8--- /dev/null+++ b/scripts/ambench/shared/rcb_ambench.py@@ -0,0 +1,451 @@+"""+rcb_ambench.py — task-local tooling for AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0: aerial manipulation on+Isaac Lab / Isaac Sim 5.1): frozen task instance, privileged state, action recording, fresh-process replay. Same shape as+the other benchmarks' rcb_<bench>.py.++Concepts+--------+instance : one AM-Bench environment (a task with one robot and controller profile, e.g.+ PressButton-Am-FAHexa-Abs-PID-Direct-v0) and the seed of its reset (instance.json). AM-Bench draws the task's+ variation (where the button, the slider, the valve or the ball is) from the seeded reset; `initial_sha` is the+ hash of the start it builds, which every replay checks (`instance_matches`).+trajectory : the (T, 8) actions handed to the environment, one row per control step (120 Hz: one physics step of 1/120 s):+ the absolute end-effector target, position x y z (m, world frame, relative to the environment's origin),+ orientation as a unit quaternion w x y z, and the gripper command (-1 = closed .. +1 = open). AM-Bench's own+ low-level controller (the profile's PID) and floating-base inverse kinematics turn it into rotor thrusts and arm+ joint targets inside every step. Physics is PhysX on the GPU: a fresh process replays the same rows to the+ same state (the first episode of a process; later resets in the same process need not be bit-identical)+ WITHOUT the onboard cameras. With them (`Session(cameras=True)`), the per-step rendering makes PhysX's results+ depend on timing (measured: two fresh replays of the same rows part after a few hundred steps), so the+ grader, the reference recordings and a default Session run without them; cameras are for looking only.+success : AM-Bench's own `_get_success` of the task (its `terminated` signal); the episode ends at the first control step+ where it holds, or at the task's episode length (a time-out, not a success). Rows after the end never run.+ Isaac Lab resets the scene inside the step that ends an episode; the tooling keeps the end state's hash+ (taken just before that reset) as the episode's `state_sha`.+ RotateValve: the valve's `base_to_shaft` joint has no limits, and PhysX reports an articulation's unlimited+ revolute joint wrapped into [-pi, pi] (omni.physx 107.3, Isaac Sim 5.1), so AM-Bench's check `joint_pos >=+ 17/18 pi` would also pass a counter-clockwise turn of 190 degrees. The tooling gives that task's+ `_get_success` the unwrapped angle instead: the sum of the joint's per-step changes since the reset (one+ physics step moves it at most 5 rad/s / 120 Hz, far less than pi), so only the clockwise turn the+ instruction asks for counts. Physics, states and hashes are unchanged; the episode just does not end on a+ wrapped reading.++CLI+---+ python rcb_ambench.py replay --instance instance.json --traj traj.npz # one fresh-process replay (the grader's, no cameras)+ python rcb_ambench.py film --instance instance.json --traj traj.npz --video replay.mp4 # the same rows with the cameras on,+ filmed: an illustration only (camera rendering changes the numerics; never a verdict)+ python rcb_ambench.py make-instance --env-id <id> --seed 0 --out instance.json+ python rcb_ambench.py run-actions --instance instance.json --actions actions.npy --out traj.npz+"""+from __future__ import annotations++import os+for _k, _v in (("OMNI_KIT_ACCEPT_EULA", "YES"), ("ACCEPT_EULA", "Y"), ("OMNI_KIT_ALLOW_ROOT", "1"), ("PYTHONUNBUFFERED", "1"),+ ("JAX_PLATFORMS", "cpu")):+ os.environ.setdefault(_k, _v)++import argparse+import hashlib+import json+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++ACTION_DIM = 8+CONTROL_HZ = 120+MAX_STEPS = 8000 # a technical cap above every task's episode length (at most 60 s = 7200 steps)+ASSET_ROOT = "/opt/isaac-assets/Assets/Isaac/5.1" # baked web assets (images/ambench/web_assets.txt)+CAMERAS = ("ee_camera", "base_camera") # the robot profile's onboard cameras (384 x 384 RGB), only with Session(cameras=True)+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")+_APP = None+_APP_CAMERAS = False+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG) or ".", exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ev": ev, "t": round(time.time(), 3), "pid": os.getpid(), **kw}) + "\n")+ except OSError:+ pass+++def _launch_app(cameras: bool = False):+ """Isaac Sim, headless, the asset root pointed at the baked copies (no network needed); rendering only with cameras.+ Once per process: the first Session decides."""+ global _APP, _APP_CAMERAS+ if _APP is not None and cameras != _APP_CAMERAS:+ raise RuntimeError(f"this process launched Isaac Sim with cameras={_APP_CAMERAS}: one Session (one setting) per process")+ if _APP is None:+ _APP_CAMERAS = cameras+ from isaaclab.app import AppLauncher+ ns = argparse.Namespace()+ p = argparse.ArgumentParser(); AppLauncher.add_app_launcher_args(p)+ ns = p.parse_args([])+ ns.headless = True; ns.enable_cameras = bool(cameras); ns.device = "cuda:0"+ ns.kit_args = f"--/persistent/isaac/asset_root/cloud={ASSET_ROOT}"+ _APP = AppLauncher(ns).app+ return _APP+++def load_instance(instance) -> dict:+ return instance if isinstance(instance, dict) else json.loads(Path(instance).read_text())+++def _np(x) -> np.ndarray:+ return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)+++class Session:+ """One AM-Bench environment of one frozen instance. One per process (Isaac Sim runs once per process)."""++ def __init__(self, instance="/app/instance.json", *, strict: bool = False, cameras: bool = False):+ _launch_app(cameras)+ self.cameras = bool(cameras)+ import gymnasium as gym+ import torch+ import ambench.tasks # noqa: F401 (registers the environments)+ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg+ self.torch = torch+ self.instance = load_instance(instance)+ I = self.instance+ self.env_id, self.seed = I["env_id"], int(I["seed"])+ cfg = parse_env_cfg(self.env_id, device="cuda:0", num_envs=1)+ cfg.seed = self.seed+ if not self.cameras: # the robot profile's onboard cameras (and any scene camera) are not built: no rendering+ cfg.robot_profile.ee_camera = None; cfg.robot_profile.base_camera = None; cfg.scene_camera_cfg = None+ self.env = gym.make(self.env_id, cfg=cfg).unwrapped+ # Isaac Lab resets an environment whose episode ended INSIDE that step (DirectRLEnv.step -> _reset_idx), so after the+ # last step the scene is already the next episode's start: keep the end state's hash, taken just before that reset+ self._in_step = False; self.end_sha = None+ _reset_idx = self.env._reset_idx++ def _keep_end_state(env_ids, _reset_idx=_reset_idx):+ if self._in_step:+ self.end_sha = self.state_sha()+ return _reset_idx(env_ids)+ self.env._reset_idx = _keep_end_state+ self._valve = None+ if self.env_id.startswith("RotateValve-"):+ self._unwrap_valve_angle()+ self.n_resets = 0; self.n_steps_total = 0; self.n_clipped = 0+ self._video = None+ self.reset()+ self.initial_sha = self.state_sha()+ want = I.get("initial_sha")+ self.instance_matches = want is None or want == self.initial_sha+ if strict and not self.instance_matches:+ raise RuntimeError(f"the rebuilt scene differs from the frozen instance: {self.initial_sha} != {want}")+ _slog("session_start", env_id=self.env_id, instance_matches=self.instance_matches, cameras=self.cameras)++ # ------------------------------------------------------------------ episode+ def reset(self) -> None:+ """Back to the frozen instance (the seeded reset). Only the first episode of a process is guaranteed bit-identical+ to a fresh process's: check a trajectory with the `replay` CLI."""+ with self.torch.inference_mode(): # as step(): after a step Isaac Lab's buffers are inference tensors+ self.obs, _ = self.env.reset(seed=self.seed)+ self.end_sha = None+ if self._valve is not None:+ self._valve.update(prev=None, angle=None) # the joint is back at 0 rad: count from here+ self.rows: list[np.ndarray] = []+ self.done = False; self.succeeded = False; self.timed_out = False+ self.n_resets += 1+ if self.n_resets > 1:+ _slog("reset", env_id=self.env_id)++ def _unwrap_valve_angle(self) -> None:+ """RotateValve's success on the valve's unwrapped angle (see the module docstring): AM-Bench's `_get_success`, with+ the joint position PhysX reports in [-pi, pi] replaced by the sum of its per-step changes since the reset."""+ env, torch, v = self.env, self.torch, {"prev": None, "angle": None}+ self._valve = v+ two_pi = 2.0 * float(np.pi)++ def _get_success():+ q = env.valve_object.data.joint_pos[:, env.valve_joint_idx].clone()+ if v["prev"] is None: # the first step after a reset, from 0 rad (|q| < 0.05 rad here)+ angle = q+ else:+ angle = v["angle"] + torch.remainder(q - v["prev"] + np.pi, two_pi) - np.pi+ v.update(prev=q, angle=angle)+ target = env.cfg.valve_target_angle+ rotated = angle >= target+ return rotated, {"valve_engaged": angle >= env.cfg.valve_engagement_ratio * target, "valve_rotated": rotated}+ env._get_success = _get_success++ def valve_angle(self) -> float | None:+ """RotateValve: the valve's unwrapped angle in rad since the reset (positive = clockwise from the robot's side),+ what the success check reads; None in other tasks or before the first step."""+ if self._valve is None or self._valve["angle"] is None:+ return None+ return float(_np(self._valve["angle"]).reshape(-1)[0])++ @property+ def n_steps(self) -> int:+ return len(self.rows)++ def clip(self, row) -> tuple[np.ndarray, int]:+ a = np.asarray(row, dtype=np.float64).reshape(-1).copy()+ if a.size != ACTION_DIM or not np.all(np.isfinite(a)):+ raise ValueError(f"an action row has {ACTION_DIM} finite values (x y z qw qx qy qz gripper), got {a.size}")+ n = 0+ g = float(np.clip(a[7], -1.0, 1.0)); n += int(g != a[7]); a[7] = g+ if float(np.linalg.norm(a[3:7])) < 1e-9: # passed on as it is (AM-Bench's controller takes the quaternion it gets)+ raise ValueError("the action's quaternion has zero length")+ return a, n++ def step(self, row) -> bool:+ """One control step (1/120 s). Returns True when the episode is over; a step after that executes nothing."""+ if self.done:+ return True+ a, n = self.clip(row)+ self.n_clipped += n+ t = self.torch.as_tensor(a, dtype=self.torch.float32, device=self.env.device).reshape(1, ACTION_DIM)+ self._in_step = True+ try:+ with self.torch.inference_mode():+ self.obs, _, term, trunc, _ = self.env.step(t)+ finally:+ self._in_step = False+ self.rows.append(a)+ self.n_steps_total += 1+ self.succeeded = bool(_np(term).reshape(-1)[0])+ self.timed_out = bool(_np(trunc).reshape(-1)[0]) and not self.succeeded+ self.done = self.succeeded or self.timed_out or self.n_steps >= MAX_STEPS+ if self._video is not None:+ self._video_add()+ return self.done++ def success(self) -> bool:+ return self.succeeded++ def end_reason(self) -> str | None:+ if self.succeeded:+ return "success"+ if self.timed_out:+ return "timeout"+ return "step_cap" if self.done else None++ def hold_action(self) -> np.ndarray:+ """A row that keeps the current end-effector target and gripper command."""+ cp = self.env.control_pipeline+ pos = _np(cp.ee_cmd_pos_w[0] - self.env.scene.env_origins[0]).astype(np.float64)+ quat = _np(cp.ee_cmd_quat_w[0]).astype(np.float64)+ g = self.rows[-1][7] if self.rows else 1.0+ return np.r_[pos, quat, g]++ def status(self) -> dict[str, Any]:+ # state_sha: the episode's end state once it is over (taken before Isaac Lab's reset), else the current state+ return {"success": self.succeeded, "done": self.done, "end_reason": self.end_reason(), "control_steps": self.n_steps,+ "sim_time_s": round(self.n_steps / CONTROL_HZ, 4), "episode_length_s": float(self.env.cfg.episode_length_s),+ "resets": self.n_resets, "state_sha": self.end_sha if (self.done and self.end_sha) else self.state_sha()}++ def actions(self) -> np.ndarray:+ return np.asarray(self.rows, dtype=np.float64).reshape(-1, ACTION_DIM)++ def record_start(self) -> None:+ self.reset()++ def record_stop(self) -> np.ndarray:+ return self.actions()++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ self.reset()+ for row in A:+ if self.step(row):+ break+ _slog("replay", env_id=self.env_id, rows=int(len(A)), executed=self.n_steps)+ return {**self.status(), "executed_rows": self.n_steps}++ def save_trajectory(self, actions, path="/app/output/trajectory.npz", meta: dict | None = None) -> None:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, task=np.array(self.env_id), actions=A, meta=np.array(json.dumps(meta or {})))++ # ------------------------------------------------------------------ state (privileged)+ def state_sha(self) -> str:+ """sha256 over every articulation's and rigid object's root state, joint positions and velocities."""+ m = hashlib.sha256()+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name in sorted(group):+ d = group[name].data+ for t in (d.root_state_w, getattr(d, "joint_pos", None), getattr(d, "joint_vel", None)):+ if t is not None:+ m.update(name.encode()); m.update(_np(t).tobytes())+ return m.hexdigest()++ def state(self) -> dict[str, Any]:+ """Privileged observation of the task (AM-Bench's own `policy` observation: robot, end effector, task objects and+ goal positions, relative to the environment's origin)."""+ obs = self.obs["policy"][0] if isinstance(self.obs.get("policy"), list) else self.obs.get("policy")+ return {k: _np(v).reshape(-1).tolist() for k, v in (obs.items() if isinstance(obs, dict) else [])}++ def objects(self) -> dict[str, dict]:+ """Every articulation (but the robot) and rigid object of the scene: root pose (wxyz) and velocities, joint state."""+ out, o = {}, _np(self.env.scene.env_origins[0])+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name, obj in group.items():+ if name == "robot":+ continue+ rs = _np(obj.data.root_state_w[0])+ ent = {"position": (rs[:3] - o).tolist(), "orientation_wxyz": rs[3:7].tolist(), "velocity": rs[7:10].tolist(),+ "angular_velocity": rs[10:13].tolist()}+ if getattr(obj.data, "joint_pos", None) is not None:+ ent["joint_pos"] = _np(obj.data.joint_pos[0]).tolist(); ent["joint_names"] = list(obj.joint_names)+ out[name] = ent+ return out++ def proprio(self) -> dict[str, Any]:+ """The robot's own state: base and end-effector poses (world, relative to the env origin; wxyz) and velocities, the+ gripper opening and the arm joints, the current end-effector command."""+ e = self.env; o = _np(e.scene.env_origins[0])+ base = _np(e.robot.data.body_link_state_w[0, e.base_link_idx]); ee = _np(e.robot.data.body_link_state_w[0, e.ee_link_idx])+ jp = _np(e.robot.data.joint_pos[0]); jv = _np(e.robot.data.joint_vel[0])+ return {"base_pose": np.r_[base[:3] - o, base[3:7]].tolist(), "base_vel": base[7:13].tolist(),+ "ee_pose": np.r_[ee[:3] - o, ee[3:7]].tolist(), "ee_vel": ee[7:13].tolist(),+ "gripper_width": float(np.sum(jp[e.gripper_joint_ids])),+ "arm_joint_pos": jp[e.arm_joint_ids].tolist(), "arm_joint_vel": jv[e.arm_joint_ids].tolist(),+ "command": self.hold_action().tolist()}++ # ------------------------------------------------------------------ cameras+ def render_frame(self, camera: str = "ee_camera") -> np.ndarray:+ """RGB uint8 (384, 384, 3) of the robot's onboard camera `ee_camera` (at the end effector) or `base_camera` (on the+ airframe, looking forward), as of the last step. Only in a Session(cameras=True): the cameras render every step+ and that makes the physics timing-dependent, so check what you find there with the replay CLI (no cameras)."""+ if not self.cameras:+ raise RuntimeError("no cameras in this Session: start the process with Session(..., cameras=True) to look "+ "(its numerics differ from the grader's camera-free replay; check trajectories with the CLI)")+ cam = getattr(self.env, camera, None)+ if cam is None:+ raise KeyError(f"no camera {camera!r}; cameras: {[c for c in CAMERAS if getattr(self.env, c, None) is not None]}")+ return _np(cam.data.output["rgb"][0])[..., :3].astype(np.uint8)++ def start_video(self, path, fps: int = 30, camera: str = "ee_camera") -> None:+ import imageio.v2 as imageio+ self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),+ "every": max(1, round(CONTROL_HZ / fps)), "camera": camera, "path": str(path)}+ self._video_add(force=True)++ def _video_add(self, force: bool = False) -> None:+ v = self._video+ if force or self.n_steps % v["every"] == 0 or self.done:+ frames = [self.render_frame(c) for c in CAMERAS if getattr(self.env, c, None) is not None]+ v["w"].append_data(np.concatenate(frames, axis=1))++ def stop_video(self):+ v, self._video = self._video, None+ if v:+ v["w"].close()+ return v["path"]++ def close(self) -> None:+ _slog("session_end", env_id=self.env_id, sim_steps=self.n_steps_total, resets=self.n_resets)+ try:+ self.env.close()+ except Exception: # noqa: BLE001+ pass+++def load_trajectory(path, env_id: str) -> np.ndarray:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != env_id:+ raise ValueError(f"trajectory is for {str(d['task'])!r}, not {env_id!r}")+ A = np.asarray(d["actions"], dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != ACTION_DIM or A.shape[0] > MAX_STEPS or not np.all(np.isfinite(A)):+ raise ValueError(f"actions must be a finite (T, {ACTION_DIM}) array with T <= {MAX_STEPS}, got {list(A.shape)}")+ return A+++def _replay_rows(s: "Session", A: np.ndarray) -> dict:+ for row in A: # the process's first episode+ if s.step(row):+ break+ res = s.status()+ return {**{k: res[k] for k in ("success", "state_sha", "end_reason", "control_steps", "sim_time_s")}, "executed_rows": s.n_steps}+++def _cli_replay(a) -> int:+ """The grader's replay: a fresh process, no cameras (bit-reproducible), the process's first episode."""+ t0 = time.time()+ s = Session(a.instance)+ out: dict[str, Any] = {"task": s.env_id, "instance_matches": bool(s.instance_matches), "initial_sha": s.initial_sha}+ try:+ A = load_trajectory(a.traj, s.env_id)+ except Exception as exc: # noqa: BLE001+ out["error"] = f"bad trajectory: {exc!r}"[:300]; print(json.dumps(out), flush=True); return 2+ out["replays"] = [_replay_rows(s, A)]+ out["n_actions"] = int(len(A)); out["replay_wall_s"] = round(time.time() - t0, 2)+ print(json.dumps(out), flush=True)+ s.close()+ return 0+++def _cli_film(a) -> int:+ """An illustration, never a verdict: the rows with the onboard cameras on, filmed (both cameras side by side) plus the+ last end-effector frame. Camera rendering makes the physics timing-dependent, so this episode may end differently."""+ t0 = time.time()+ s = Session(a.instance, cameras=True)+ A = load_trajectory(a.traj, s.env_id)+ s.start_video(a.video, fps=a.fps)+ res = _replay_rows(s, A)+ s.stop_video()+ from PIL import Image+ Image.fromarray(s.render_frame("ee_camera")).save(str(Path(a.video).with_suffix(".last.png")))+ print(json.dumps({"task": s.env_id, "film": res, "video": a.video, "film_wall_s": round(time.time() - t0, 2)}), flush=True)+ s.close()+ return 0+++def _cli_make_instance(a) -> int:+ inst = {"env_id": a.env_id, "seed": int(a.seed)}+ s = Session(inst)+ inst.update({"task": a.env_id.split("-")[0], "action_dim": ACTION_DIM, "control_hz": CONTROL_HZ,+ "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha})+ Path(a.out).write_text(json.dumps(inst, indent=1) + "\n")+ print(json.dumps({"env_id": a.env_id, "initial_sha": s.initial_sha}), flush=True)+ s.close()+ return 0+++def _cli_run_actions(a) -> int:+ s = Session(a.instance, strict=True)+ for row in np.load(a.actions): # the process's first episode (no second reset), as the grader's+ if s.step(row):+ break+ res = {**s.status(), "executed_rows": s.n_steps}+ s.save_trajectory(s.actions(), a.out, meta={"source": "reference rows"})+ print(json.dumps({k: res[k] for k in ("success", "end_reason", "state_sha", "control_steps", "executed_rows", "sim_time_s")}), flush=True)+ s.close()+ return 0+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay"); r.add_argument("--instance", required=True); r.add_argument("--traj", required=True)+ f = sub.add_parser("film"); f.add_argument("--instance", required=True); f.add_argument("--traj", required=True)+ f.add_argument("--video", required=True); f.add_argument("--fps", type=int, default=30)+ m = sub.add_parser("make-instance"); m.add_argument("--env-id", required=True); m.add_argument("--seed", type=int, default=0); m.add_argument("--out", required=True)+ x = sub.add_parser("run-actions"); x.add_argument("--instance", required=True); x.add_argument("--actions", required=True); x.add_argument("--out", required=True)+ a = ap.parse_args(argv)+ global SESSION_LOG+ SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "") # the CLI logs nothing unless asked+ try:+ rc = {"replay": _cli_replay, "film": _cli_film, "make-instance": _cli_make_instance, "run-actions": _cli_run_actions}[a.cmd](a)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error: report it and leave at once+ import traceback+ traceback.print_exc(); rc = 3+ sys.stdout.flush(); sys.stderr.flush()+ os._exit(rc) # Isaac Sim's shutdown can hang or crash after the result line; the result is printed+++if __name__ == "__main__":+ main()diff --git a/scripts/ambench/template/privileged/README.md.tmpl b/scripts/ambench/template/privileged/README.md.tmplnew file mode 100644index 0000000000..1b7121106a--- /dev/null+++ b/scripts/ambench/template/privileged/README.md.tmpl@@ -0,0 +1,52 @@+# @@PRIV@@++| | |+|---|---|+| Benchmark | AM-Bench |+| Mode | privileged |+| Twin | none yet: the standard twin `@@STD@@` is planned (`docs/benchmarks/ambench.md`) |+| Simulator / robot | `ambench` / `ambench-fahexa` |+| Family / instance | `@@FAMILY@@` / @@INST@@ (seed @@SEED@@) |+| Oracle | `full` |+| Agent time budget | @@AGENT_TIMEOUT_S@@ s; tokens: protocol default (PROTOCOL §5) |+| Base image | `@@IMAGE@@` |++## Task+@@README_GOAL@@ AM-Bench environment `@@ENV_ID@@` (the fully actuated hexarotor with the 4-joint arm, AM-Bench's PID+controller), its seeded reset with seed @@SEED@@. The deliverable is one replayable trajectory of AM-Bench's absolute+end-effector pose actions at 120 Hz (`/app/output/trajectory.npz`), graded by AM-Bench's own success check within the+task's episode length of @@EPISODE_S@@ s.++## Difficulty+@@DIFFICULTY@@ Privileged mode gives the full simulator state, unlimited resets and self-replay; the tooling offers only the+environment's own action, its state and its cameras.++## Reference solution+`solution/oracle_actions.npy` (run by `solution/oracle.py` through the agent's own tooling): AM-Bench's scripted expert+for this task, run on this instance (it reads the simulator's state in closed loop) and recorded, followed by 2 s of+holding its last command (a replay may succeed a step later than the live run; rows after success never run). The image+has no expert (`images/ambench/Dockerfile` removes them), and the agent's network reaches only the+model APIs and the package registries.++## Verification+`tests/grade.py` in a separate sandbox: two replays, each in a fresh process, from the verifier's own copy of the instance+(`tests/instance.json`; the rebuilt start is checked against its hash); pass iff AM-Bench's success check holds in both+and both end in the same state (`deterministic`); the replays run without the onboard cameras (camera rendering makes+GPU PhysX timing-dependent). `/logs/verifier/replay.mp4` (both onboard cameras) is filmed by a third process after the+verdict, an illustration only. Oracle:+success at control step @@N_ORACLE@@ (@@ORACLE_SIM_S@@ s simulated) in both fresh-process replays, which end in the same+state (hash `@@ORACLE_SHA@@`). `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | AM-Bench @ 60bf5b7 (Apache-2.0) on Isaac Lab @ f4aa17f / Isaac Sim 5.1.0; Pyroki @ 2eafc99, acados @ fa0af20 |+| Instance | `@@ENV_ID@@`, seed @@SEED@@, the start's state hash in `environment/instance.json` (`initial_sha` @@INITIAL_SHA_SHORT@@) |+| Actions | 8 per control step (1/120 s): end-effector target x y z (m), quaternion w x y z (command frame), gripper (-1 closed .. +1 open) |+| Physics | PhysX on the GPU (dt 1/120 s, one physics step per action); bit-reproducible in a fresh process without the onboard cameras, which the tooling builds only on request (`Session(cameras=True)`) |+| Image | built locally on every host (`images/ambench/BUILD_ONLY`: it contains Isaac Sim); needs an RTX-class NVIDIA GPU (`environment/docker-compose.yaml`) |+| Budget | the agent's cutoff is the `Agent time budget` row above (`scripts/task_cutoffs.toml`); out of it, every Python process pays ~2-6 min of Isaac Sim launch + scene build |++### Provenance+Generated by `scripts/ambench/mk_tasks.py` from `scripts/ambench/descr/@@FAMILY@@.json` and `scripts/ambench/frozen/@@FROZEN@@/`+(the expert's rows recorded with `scripts/ambench/freeze.py` in `@@IMAGE@@`; provenance in `scripts/ambench/instances.json`).diff --git a/scripts/ambench/template/privileged/environment/Dockerfile.tmpl b/scripts/ambench/template/privileged/environment/Dockerfile.tmplnew file mode 100644index 0000000000..1744b4d94b--- /dev/null+++ b/scripts/ambench/template/privileged/environment/Dockerfile.tmpl@@ -0,0 +1,8 @@+# Base image = AM-Bench (scrubbed: no scripted experts) + Isaac Lab / Isaac Sim 5.1 + the baked web assets (see+# images/ambench/; BUILD_ONLY). Everything task-specific is copied here; no reference solution is in the image.+FROM @@IMAGE@@+COPY instance.json /app/instance.json+COPY rcb_ambench.py /opt/tools/rcb_ambench.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/scripts/ambench/template/privileged/environment/docker-compose.yaml b/scripts/ambench/template/privileged/environment/docker-compose.yamlnew file mode 100644index 0000000000..fe6b5f544e--- /dev/null+++ b/scripts/ambench/template/privileged/environment/docker-compose.yaml@@ -0,0 +1,18 @@+# Isaac Sim needs an RTX-class NVIDIA GPU even headless. Harbor's local docker sandbox rejects [environment].gpus, but+# merging this onto the main service passes the device through. Isaac's shader/extension cache gets a volume for the+# trial, named after the trial's compose project (no fixed name: side-by-side trials must not share it; Harbor's+# teardown, `compose down --volumes`, deletes it): every trial compiles its shaders once (~2 min).+services:+ main:+ shm_size: "8gb"+ volumes:+ - rcb_ambench_cache:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+volumes:+ rcb_ambench_cache:diff --git a/scripts/ambench/template/privileged/instruction.md.tmpl b/scripts/ambench/template/privileged/instruction.md.tmplnew file mode 100644index 0000000000..a1c259d3e7--- /dev/null+++ b/scripts/ambench/template/privileged/instruction.md.tmpl@@ -0,0 +1,76 @@+# AM-Bench · @@TITLE@@ — frozen instance @@INST@@++You control a simulated **aerial manipulator**: a fully actuated hexarotor (six tilted rotors, so it can hold any attitude+while hovering) carrying a small arm (four joints: three pitch joints and a roll joint) with a two-finger gripper, in+AM-Bench on Isaac Lab / Isaac Sim 5.1 (PhysX), via Python. **Task:** @@SUMMARY@@++This is a *fixed scene instance*: the scene and the robot start the same way after every reset, and you may reset and+retry as many times as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a+general policy.++## Scene+@@SCENE@@++Exactly (privileged information, also readable through the tooling): @@SCENE_PRIVILEGED@@+@@GOALS@@+## Success (AM-Bench's own check)+@@SUCCESS@@+The episode **ends by itself** at the first control step where the check holds (success; rows after it are never+executed), or when the task's episode length of **@@EPISODE_S@@ s** runs out (a failure: AM-Bench's time-out ends the episode+at control step @@EPISODE_ROWS@@). Isaac Lab resets the scene inside the step that ends an episode, so after it `s.state()`,+`s.objects()` and the cameras show the start again; `s.status()` keeps the outcome and the end state's hash.+@@FAILURES@@+## Deliverable+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed+open-loop from the same initial state in two fresh processes and scored 1 if the task succeeds in both replays and both+end in the same state, else 0. Also leave the script that produced it at `/app/output/gen.py`. Save a working trajectory+as soon as you have one and overwrite it as you improve it: whatever is in `/app/output/` when the time is up is graded.+The file holds `task` and `actions`, a (T, 8) float array of at most **8,000 rows** (one per control step); anything else+(another shape, NaN, more rows, a file that is not such an npz) scores 0.++## Tooling (already installed; run `python` from any directory)+```python+from rcb_ambench import Session+s = Session(instance="/app/instance.json") # ~2-6 min: launches Isaac Sim, builds the scene, resets to the frozen instance+ # (no cameras, as the grader; Session(..., cameras=True) to look: see below)+s.reset() # back to the frozen instance (the seeded reset; as often as you like)+s.step(row) # one control step (1/120 s): row = 8 values (below); True once the episode is over+s.hold_action() # a row that keeps the current end-effector target and gripper command+s.status() # {'success', 'done', 'end_reason', 'control_steps', 'sim_time_s', 'episode_length_s', 'state_sha', ...}+s.state() # privileged: AM-Bench's own observation of the task (robot, end effector, task objects, goal)+s.objects() # every task object and fixture: pose (xyz + quaternion wxyz), velocities, joint state+s.proprio() # the robot: base and end-effector poses and velocities, gripper width, arm joints, current command+s.actions() # (T, 8) rows executed since the last reset: the trajectory of this episode+s.replay(actions) # reset, run the rows open-loop until the episode ends, return status (+ executed_rows)+s.save_trajectory(actions, "/app/output/trajectory.npz")+s.render_frame("ee_camera") # cameras=True only: RGB uint8 (384, 384, 3) at the end effector, or "base_camera" (on the airframe, looking forward)+s.start_video("/app/output/try.mp4"); ...; s.stop_video() # cameras=True only: film the steps in between (both cameras side by side)+s.env # the Isaac Lab environment itself (AM-Bench's source is in /opt/ambench: read-only reference)+```+The tooling is deliberately thin: the environment's own action, its state and its cameras. Reaching, pressing, pushing,+turning and throwing are yours to build. Isaac Sim runs once per process, and only the first episode of a process is+guaranteed to be bit-identical to a fresh process's: after changes, check your trajectory with the grader's CLI.+**Cameras.** The robot's two onboard cameras exist only in a `Session(..., cameras=True)` (decided once per process). With+them, Isaac renders every step and that makes PhysX's results depend on timing: two runs of the same rows can part after a+few hundred steps. The grader replays without cameras, where a fresh process reproduces a trajectory bit for bit, so use+the cameras to look and check every trajectory with the CLI below.++The grader replays in two fresh processes; each is exactly this CLI (a fresh process, so run it to self-check):+`python /opt/tools/rcb_ambench.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`+(`... film --instance ... --traj ... --video out.mp4` films the rows with the cameras on: an illustration, not a verdict).++## Conventions+- World frame: metres, z up, the ground is the plane z = 0; positions are relative to the environment's origin (the+ tooling and the actions use the same origin); quaternions are **wxyz**.+- Action row (8 values per control step), AM-Bench's absolute end-effector pose action: the target position of the+ end-effector link (x, y, z, m) and its target orientation (qw, qx, qy, qz, in AM-Bench's command frame of the end+ effector: `s.proprio()["command"]` and `hold_action()` give the current target in the same convention), then the gripper+ command (-1 = closed .. +1 = open). Every step, AM-Bench's floating-base inverse kinematics turns the target into an+ airframe pose and arm joint targets, its PID controller turns the airframe pose into the six rotor thrusts, and the arm+ joints track their targets.+- Control and physics run at 120 Hz (one physics step per row). There is no step budget: the time limit (`## Time limit`)+ is your only budget; an episode lasts at most @@EPISODE_S@@ s of simulated time.+- One `Session` per process (Isaac Sim launches once, then the scene builds: ~2-6 min, the upper end on a busy host).+ Physics is PhysX on the **GPU** (about 10-15 control steps per second of wall time). One Isaac process takes up to+ ~13 GiB of memory and ~6.5 GiB of GPU memory: run at most two at once. Do not call `s.close()` before writing every+ output.diff --git a/scripts/ambench/template/privileged/solution/oracle.py b/scripts/ambench/template/privileged/solution/oracle.pynew file mode 100644index 0000000000..b695ebf3dc--- /dev/null+++ b/scripts/ambench/template/privileged/solution/oracle.py@@ -0,0 +1,15 @@+"""Oracle (privileged): run the reference rows on the frozen instance with the agent's tooling, stopping at the end of+the episode, and save the rows that ran as /app/output/trajectory.npz."""+import json, os+import numpy as np+from rcb_ambench import Session+HERE = os.path.dirname(os.path.abspath(__file__))+s = Session(instance="/app/instance.json", strict=True)+for row in np.load(os.path.join(HERE, "oracle_actions.npy")).astype(np.float64): # the process's first episode, as the grader's+ if s.step(row):+ break+st = {**s.status(), "executed_rows": s.n_steps}+s.save_trajectory(s.actions(), "/app/output/trajectory.npz", meta={"source": "reference rows"})+print(json.dumps({k: st[k] for k in ("success", "end_reason", "executed_rows", "sim_time_s", "state_sha")}), flush=True)+s.close()+os._exit(0 if st["success"] else 1)diff --git a/scripts/ambench/template/privileged/solution/solve.sh b/scripts/ambench/template/privileged/solution/solve.shnew file mode 100644index 0000000000..365611c270--- /dev/null+++ b/scripts/ambench/template/privileged/solution/solve.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Oracle: replay the reference rows (solution/oracle_actions.npy: AM-Bench's scripted expert for this task, run on this+# instance and recorded, then 2 s of holding its last command; the expert reads the simulator's true state) through the+# agent's own tooling, and save the trajectory. The rows live in solution/ only (never in the agent image, which has no+# expert).+set -e+mkdir -p /app/output+cp /solution/oracle.py /app/output/gen.py+python /solution/oracle.pydiff --git a/scripts/ambench/template/privileged/task.toml.tmpl b/scripts/ambench/template/privileged/task.toml.tmplnew file mode 100644index 0000000000..fdb787c562--- /dev/null+++ b/scripts/ambench/template/privileged/task.toml.tmpl@@ -0,0 +1,47 @@+# Generated by scripts/ambench/mk_tasks.py -- edit the template or scripts/ambench/descr/, not this.+schema_version = "1.3"+artifacts = ["/app/output/"]++[task]+name = "robot-coding-bench/@@PRIV@@"+description = "AM-Bench @@ENV_ID@@ (a fully actuated hexarotor with a 4-joint arm and a two-finger gripper, Isaac Lab / Isaac Sim 5.1): produce one replayable trajectory of AM-Bench's absolute end-effector pose actions at 120 Hz. @@GOAL_TOML@@ Frozen scene instance: AM-Bench's seeded reset, seed @@SEED@@; graded by AM-Bench's own success check in two fresh-process replays."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "ambench", "aerial-manipulation", "isaac-lab", "isaac-sim", "hexarotor", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "ambench" # AM-Bench @ 60bf5b7 on Isaac Lab @ f4aa17f / Isaac Sim 5.1 (PhysX on the GPU, RTX rendering)+robot = "ambench-fahexa"+family = "@@FAMILY@@"+mode = "privileged"+oracle = "full"+instance_seed = @@SEED@@+expert_time_estimate_hours = 2.0++[verifier]+timeout_sec = 9000.0 # tests/grade.py's limits for the longest episode (3120 rows: 1500 s + 3120 / 4 = 2280 s per+ # process): two fresh-process replays (no cameras), one rerun of a replay that died early,+ # and the filmed illustration (cameras on; its time-out only costs the video); measured:+ # 1.5-6 min of Isaac start, the verifier's first one compiling its shaders, + 9-12 control+ # steps/s+environment_mode = "separate" # verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then+network_mode = "no-network" # Isaac Sim starts and renders offline: every asset is in the image (images/ambench/web_assets.txt)++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 8+memory_mb = 24576++[agent]+timeout_sec = @@AGENT_TIMEOUT_S@@.0 # the agent's cutoff: scripts/task_cutoffs.toml, the one table (written by normalize, PROTOCOL §2.12)+# AM-Bench's scripted experts and its datasets are public upstream, so the agent reaches the model APIs and the package+# registries, nothing else (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com", "pypi.org", "files.pythonhosted.org", "deb.debian.org", "security.debian.org", "archive.ubuntu.com", "security.ubuntu.com", "snapshot.ubuntu.com"]++[environment]+build_timeout_sec = 3600.0+cpus = 8+memory_mb = 24576diff --git a/scripts/ambench/template/privileged/tests/Dockerfile.tmpl b/scripts/ambench/template/privileged/tests/Dockerfile.tmplnew file mode 100644index 0000000000..aee2dcd272--- /dev/null+++ b/scripts/ambench/template/privileged/tests/Dockerfile.tmpl@@ -0,0 +1,9 @@+# Separate verifier sandbox (PROTOCOL §4): the same simulator image with the verifier's own copies of the tooling and the+# frozen instance baked in. Nothing the agent did in its container reaches this one -- Harbor uploads only the declared+# artifacts (/app/output/), so a patched success check or a swapped interpreter in the agent container cannot influence+# the verdict.+FROM @@IMAGE@@+COPY grade.py instance.json rcb_ambench.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/scripts/ambench/template/privileged/tests/docker-compose.yaml b/scripts/ambench/template/privileged/tests/docker-compose.yamlnew file mode 100644index 0000000000..eaf78d197a--- /dev/null+++ b/scripts/ambench/template/privileged/tests/docker-compose.yaml@@ -0,0 +1,16 @@+# The verifier replays in Isaac Sim, which needs the GPU. Its Kit cache is a TRUSTED volume: Isaac keeps generated+# Python there that Kit imports at startup, so a cache the agent could write must never reach the grader.+services:+ main:+ shm_size: "8gb"+ volumes:+ - rcb_ambench_cache_trusted:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+volumes:+ rcb_ambench_cache_trusted:diff --git a/scripts/ambench/template/privileged/tests/grade.py b/scripts/ambench/template/privileged/tests/grade.pynew file mode 100644index 0000000000..580b28b5aa--- /dev/null+++ b/scripts/ambench/template/privileged/tests/grade.py@@ -0,0 +1,177 @@+"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2++Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a+human-viewable video /logs/verifier/replay.mp4 (the robot's two onboard cameras) plus replay.last.png, filmed AFTER the+verdict by a third process (`rcb_ambench.py film`) with the cameras on: camera rendering makes the physics timing-dependent,+so the verdict replays run without cameras and the video is an illustration that never enters the reward.+Replays `--repeat` times, each in its own FRESH process (`rcb_ambench.py replay`, no cameras), so fresh process == fresh+process is the determinism check. Success requires every replay to complete the task (AM-Bench's own `_get_success`) AND all+final-state hashes to agree, so a lucky non-deterministic run cannot pass. The frozen scene rebuilt here from+tests/instance.json must also match the recorded one (`instance_ok`: the exact state hash of the seeded reset).++Whose failure a 0 is (every path writes a reward; `deterministic`, `grader_error` and `infra_error` are always present):+- the agent's: no file (`missing_trajectory`), another task's trajectory (`wrong_task`), a file that is not a+ trajectory (`bad_trajectory`: not an npz, no `task` / `actions` entry, pickled or object arrays, the wrong shape, NaN/inf,+ more than MAX_STEPS rows), or a replay that does not complete the task or is not deterministic;+- the verifier's (`grader_error` = 1, with `infra_error` = 1: no verdict on the agent): a replay process that ends+ without a result (Isaac died) or runs out of its time limit (`replay_timed_out`), the rebuilt frozen scene not matching+ the recorded instance (`instance_ok` = 0: the host, not the trajectory), or any other error in this script.+"""+from __future__ import annotations+import argparse, json, os, subprocess, sys, time, traceback+import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+# Wall-clock limit of ONE replay process, scaled with the rows that can run (time limits only; the verdict rules do not+# depend on them). The grader accepts up to MAX_STEPS rows, but the episode ends at the task's own episode length (10-26 s+# here: at most 3119 control steps), so later rows never run. Measured on an RTX 4090 host: Isaac start + scene build+# 1.5-6 min (the upper end with other Isaac jobs on the GPU; the verifier's first start also compiles the shaders into its+# fresh Kit cache), then about 12 control steps/s (the onboard cameras render every step). The allowance is REPLAY_STARTUP_S for the start plus the runnable rows at REPLAY_MIN_RATE control steps/s+# (the same for the filming process, whose time-out only ends the video), never below REPLAY_FLOOR_S; task.toml's+# [verifier] timeout_sec fits the three processes of the longest episode, so a replay that is too slow ends here with a+# written reward (`replay_timed_out`), never with Harbor killing the verifier.+REPLAY_FLOOR_S, REPLAY_STARTUP_S, REPLAY_MIN_RATE = 1800.0, 1500.0, 4.0+++def replay_timeout(n_steps: int) -> float:+ return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_steps / REPLAY_MIN_RATE)+++def load_trajectory(path: str, family: str, action_dim: int, max_steps: int):+ """(actions, None), or (None, reward fields) when the file is not a gradable trajectory of this task. Everything+ here is the agent's deliverable: a file that cannot be read is the agent's 0 (`bad_trajectory`), not a grader error."""+ try:+ d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...+ task = str(d["task"]) # no `task` entry: KeyError; an object array: ValueError+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable trajectory: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if task != family:+ return None, {"wrong_task": 1}+ try:+ acts = np.asarray(d["actions"], dtype=np.float32)+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable actions: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if acts.ndim != 2 or acts.shape[1] != action_dim or acts.shape[0] > max_steps or not np.all(np.isfinite(acts)):+ return None, {"bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0}+ return acts, None+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)+ ap.add_argument("--no-video", action="store_true"); ap.add_argument("--video-fps", type=int, default=30)+ a = ap.parse_args()+ # Agent interaction cost from the tooling's append-only log (whole debugging history, not just the deliverable).+ # The log lives in the agent's container, so these fields are SELF-REPORTED cost accounting, not evidence+ # (agent_cost_self_reported = 1); the parser must survive any content the agent may have written there.+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ try:+ with open("/app/output/rcb_session_log.jsonl") as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000: break+ try:+ e = json.loads(line); ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start": cost["agent_sessions"] += 1+ elif ev == "reset": cost["agent_resets"] += 1+ elif ev == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ elif ev == "record": cost["agent_records"] += 1+ elif ev == "replay": cost["agent_replays"] += 1+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict+ continue+ except Exception: # noqa: BLE001+ pass+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions must not be counted+ ZERO = {"success": 0, "deterministic": 0, "grader_error": 0, "infra_error": 0} # an early exit: the agent's 0+ ERR = {"success": 0, "deterministic": 0, "grader_error": 1, "infra_error": 1} # no verdict on the agent+ if not os.path.isfile(a.traj):+ write(False, {**ZERO, "missing_trajectory": 1, **cost}); return 0+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling+ from rcb_ambench import MAX_STEPS, ACTION_DIM+ inst = json.load(open(a.instance)); env_id = inst["env_id"]+ acts, bad = load_trajectory(a.traj, env_id, ACTION_DIM, MAX_STEPS)+ if bad is not None:+ write(False, {**ZERO, **bad, **cost}); return 0+ tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_ambench.py")+ runnable = min(int(acts.shape[0]), int(round(float(inst["episode_length_s"]) * int(inst["control_hz"]))))+ t0 = time.time(); runs = []+ attempts = []+ for i in range(a.repeat):+ limit = replay_timeout(runnable)+ for attempt in (1, 2): # a process that died without a result (Isaac) is run once more+ cmd = [sys.executable, tool, "replay", "--instance", a.instance, "--traj", a.traj]+ try:+ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})+ stdout, run = p.stdout, {"error": f"replay process rc={p.returncode}"}+ except subprocess.TimeoutExpired as exc:+ print(f"[grade] replay {i + 1} exceeded its {limit:.0f} s limit ({len(acts)} rows)", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_timed_out": 1, "replay_timeout_s": round(limit, 1), "n_actions": int(len(acts)),+ "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ for line in stdout.splitlines(): # the last JSON object the CLI printed (Isaac writes to stdout too)+ if line.startswith("{"):+ try:+ v = json.loads(line)+ except ValueError:+ continue+ if isinstance(v, dict): run = v+ print(f"[grade] replay {i + 1}: {json.dumps(run)[:800]}", file=sys.stderr, flush=True)+ attempts.append(attempt)+ if "replays" in run or attempt == 2:+ break+ print(f"[grade] replay {i + 1} gave no result ({run.get('error')}): running it once more", file=sys.stderr, flush=True)+ runs.append(run)+ outs = [(r.get("replays") or [{}])[0] for r in runs]+ if any("error" in r or not o for r, o in zip(runs, outs)):+ print(f"[grade] a replay process gave no result: {[r.get('error') for r in runs]}", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_failed": 1, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ replay_wall = round(time.time() - t0, 1)+ all_success = all(o.get("success") for o in outs)+ deterministic = len({o.get("state_sha") for o in outs}) == 1+ instance_ok = all(bool(r.get("instance_matches")) for r in runs)+ ok = all_success and deterministic and instance_ok+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "replays": len(outs),+ "sim_steps": int(outs[0].get("control_steps") or 0), "sim_time_s": float(outs[0].get("sim_time_s") or 0.0),+ "timed_out": int(outs[-1].get("end_reason") == "timeout"),+ "replay_wall_s": replay_wall, "replay_timeout_s": round(limit, 1),+ # the rebuilt frozen scene is not the recorded one: this host, not the trajectory (no verdict on the agent)+ "grader_error": int(not instance_ok), "infra_error": int(not instance_ok),+ "replay_retries": int(sum(x - 1 for x in attempts)), **cost}+ write(ok, out) # the verdict is written before the illustration is filmed+ film = {}+ if not a.no_video: # an illustration after the verdict: never part of the reward+ try:+ p = subprocess.run([sys.executable, tool, "film", "--instance", a.instance, "--traj", a.traj, "--video",+ os.path.join(LOG_DIR, "replay.mp4"), "--fps", str(a.video_fps)], stdout=subprocess.PIPE,+ stderr=sys.stderr, text=True, timeout=replay_timeout(runnable), env={**os.environ, "RCB_SESSION_LOG": ""})+ for line in p.stdout.splitlines():+ if line.startswith("{"):+ try:+ film = json.loads(line).get("film") or {}+ except (ValueError, AttributeError):+ pass+ except Exception as exc: # noqa: BLE001 — a time-out or a crash only costs the video+ print(f"[grade] filming failed: {exc!r}"[:300], file=sys.stderr, flush=True)+ out.update(video_rendered=int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))),+ video_episode_success=int(bool(film.get("success"))))+ write(ok, out)+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {**ERR, **cost})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/ambench/template/privileged/tests/test.sh.tmpl b/scripts/ambench/template/privileged/tests/test.sh.tmplnew file mode 100644index 0000000000..fa780cb16d--- /dev/null+++ b/scripts/ambench/template/privileged/tests/test.sh.tmpl@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, see docs/PROTOCOL.md).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \+ 2> /logs/verifier/grade.logdiff --git a/scripts/task_cutoffs.toml b/scripts/task_cutoffs.tomlindex 4eb623ec8a..fc6c7ffa57 100644--- a/scripts/task_cutoffs.toml+++ b/scripts/task_cutoffs.toml@@ -19,6 +19,7 @@# no number.[cutoff_sec]+"AM-Bench" = { privileged = 3600 }"AutoBio" = { privileged = 3600, standard = 3600 }"BEHAVIOR-1K" = { privileged = 7200, standard = 7200 }"BiGym 2.0" = { privileged = 3600, standard = 3600, standard-realtime = 3600 }@@ -267,3 +268,12 @@ from_sec = 0to_sec = 3600decided_by = "owner (board 0112: a realtime twin's cutoff equals its standard twin's)"note = "the first standard-realtime task (table_tennis): the standard twin's number"++[[history]]+date = "2026-10-14"+benchmark = "AM-Bench"+modes = ["privileged"]+from_sec = 0+to_sec = 3600+decided_by = "proposal (D8 default)"+note = "the benchmark's first tasks (privileged only): the protocol's default; every Python process pays a few minutes of Isaac Sim start, which the hour includes"diff --git a/scripts/task_dynamics.toml b/scripts/task_dynamics.tomlindex e96182019b..dc6e83c9a0 100644--- a/scripts/task_dynamics.toml+++ b/scripts/task_dynamics.toml@@ -18,6 +18,7 @@# (file:line): agentboard task 0106, dynamic_tasks.csv.[benchmark]+"AM-Bench" = { dynamics = "static", why = "A hovering hexarotor with an arm (it balances actively, which does not count) at a wall-mounted button, slider or valve; the button's spring only gives back what the robot pushed in, the valve and slider have no drive, so nothing moves except by the robot or gravity." }"AutoBio" = { dynamics = "static", why = "Fixed-base arms on a laboratory bench; devices (centrifuge, thermal cycler, mixer, pipette) move only when the robot moves them." }"BEHAVIOR-1K" = { dynamics = "static", why = "R1Pro (wheeled base) in household scenes; objects move only by the robot or gravity; cooking / freezing / toggled states change no motion." }"BiGym 2.0" = { dynamics = "static", why = "G1 (legs held by the GR00T-WBC policy) at kitchen fixtures; objects and fixtures move only by the robot or gravity." }diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/README.md b/tasks/ambench-press-button-fahexa-i00-privileged/README.mdnew file mode 100644index 0000000000..3aa9a45843--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/README.md@@ -0,0 +1,65 @@+# ambench-press-button-fahexa-i00-privileged++| | |+|---|---|+| Benchmark | AM-Bench |+| Mode | privileged |+| Twin | — (privileged only) |+| Simulator / robot | `ambench` / `ambench-fahexa` |+| Family / instance | `press_button_fahexa` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-ambench:0.1.0` |++## Task+A wall stands in front of the hovering aerial manipulator, and a push button is mounted flat on the wall's front face, facing the robot: a red circular plunger in a dark-grey circular housing. Press the button, i.e. push its spring-loaded plunger into the housing, along the wall's normal, until it is depressed by at least 4 mm (40 % of its 10 mm travel). AM-Bench environment `PressButton-Am-FAHexa-Abs-PID-Direct-v0` (the fully actuated hexarotor with the 4-joint arm, AM-Bench's PID+controller), its seeded reset with seed 0. The deliverable is one replayable trajectory of AM-Bench's absolute+end-effector pose actions at 120 Hz (`/app/output/trajectory.npz`), graded by AM-Bench's own success check within the+task's episode length of 20 s.++## Difficulty+The target is small (as little as 6 cm across), its place on the wall and the wall's tilt change per instance, and the plunger springs back: the 4 mm depression has to be produced by pushing along the (possibly tilted) wall normal from a free-flying, hovering base. Privileged mode gives the full simulator state, unlimited resets and self-replay; the tooling offers only the+environment's own action, its state and its cameras.++## Reference solution+`solution/oracle_actions.npy` (run by `solution/oracle.py` through the agent's own tooling): AM-Bench's scripted expert+for this task, run on this instance (it reads the simulator's state in closed loop) and recorded, followed by 2 s of+holding its last command (a replay may succeed a step later than the live run; rows after success never run). The image+has no expert (`images/ambench/Dockerfile` removes them), and the agent's network reaches only the+model APIs and the package registries.++## Verification+`tests/grade.py` in a separate sandbox: two replays, each in a fresh process, from the verifier's own copy of the instance+(`tests/instance.json`; the rebuilt start is checked against its hash); pass iff AM-Bench's success check holds in both+and both end in the same state (`deterministic`); the replays run without the onboard cameras (camera rendering makes+GPU PhysX timing-dependent). `/logs/verifier/replay.mp4` (both onboard cameras) is filmed by a third process after the+verdict, an illustration only. Oracle:+success at control step 1027 (8.558 s simulated) in both fresh-process replays, which end in the same+state (hash `fcd4de9b60a77009`). `nop`: no trajectory, reward 0.++## Compute resources+Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]` in `task.toml`). The agent phase counts every container of the trial at once (the agent's, and in standard modes the simulator sidecar); the verifier phase runs after it.++| | Agent phase | Verifier |+|---|---|---|+| CPU cores | 8 | 4 |+| Memory | 16 GB | 16 GB |+| GPU memory | 8 GB | 8 GB |++- GPU: required, an RTX-class NVIDIA GPU (ray-tracing cores, for Isaac Sim / Omniverse RTX rendering); recommended: L40S 48GB / L4 24GB / RTX 4090 24GB.+- Measured: freezing the instances and three oracle trials (RTX 4090, 2026-10-13/14, docker stats and nvidia-smi every 10 s, rcb_monitor): a camera-free Isaac process (the default Session, the grader's replays) peaks at 2.9 GiB of memory and 3.2 GiB of GPU memory (oracle trials: 2.8 / 3.1); with the two onboard cameras on (Session(cameras=True), the verifier's filmed illustration) 13.2 GiB and 6.4 GiB; 6-10 cores while Isaac starts, about 1.5 after; the verifier runs one process at a time. The minimums cover one camera-on process+- Limits in the agent phase (docs/PROTOCOL.md §2.10; `[metadata.resources.limits]`, shown to the agent in `instruction.md`; always measured and reported, and exceeding one fails the trial only when the run sets `RCB_LIMITS_ENFORCE=1`), every container of the trial: 16 GiB GPU memory, 28 GiB memory, 512 processes, 20 GiB of new files under `/app`, `/tmp`, `/root`; 60 s within 120 s. Expected peak of the whole trial: 16 GiB GPU memory, 28 GiB memory. Limits measured: a camera-on Isaac process peaks at 13.2 GiB of memory and 6.4 GiB of GPU memory, a camera-free one at 2.9 / 3.2 (the rule's measurement); the agent may run two processes at once (a Session and the replay CLI): at most 26.4 GiB, 12.8 GiB -> memory 28 GiB (the container's cap 34 GiB: 34 / 1.2 >= 28), GPU 16 GiB (at least 16 for Isaac Sim); processes 512 and disk 20 GiB: design defaults, not yet measured.++## Details+| | |+|---|---|+| Upstream | AM-Bench @ 60bf5b7 (Apache-2.0) on Isaac Lab @ f4aa17f / Isaac Sim 5.1.0; Pyroki @ 2eafc99, acados @ fa0af20 |+| Instance | `PressButton-Am-FAHexa-Abs-PID-Direct-v0`, seed 0, the start's state hash in `environment/instance.json` (`initial_sha` c125ec8a4fdd2662) |+| Actions | 8 per control step (1/120 s): end-effector target x y z (m), quaternion w x y z (command frame), gripper (-1 closed .. +1 open) |+| Physics | PhysX on the GPU (dt 1/120 s, one physics step per action); bit-reproducible in a fresh process without the onboard cameras, which the tooling builds only on request (`Session(cameras=True)`) |+| Image | built locally on every host (`images/ambench/BUILD_ONLY`: it contains Isaac Sim); needs an RTX-class NVIDIA GPU (`environment/docker-compose.yaml`) |+| Budget | the agent's cutoff is the `Agent time budget` row above (`scripts/task_cutoffs.toml`); out of it, every Python process pays ~2-6 min of Isaac Sim launch + scene build |++### Provenance+Generated by `scripts/ambench/mk_tasks.py` from `scripts/ambench/descr/press_button_fahexa.json` and `scripts/ambench/frozen/press_button-i00/`+(the expert's rows recorded with `scripts/ambench/freeze.py` in `ghcr.io/mll-lab-nu/eai-ambench:0.1.0`; provenance in `scripts/ambench/instances.json`).diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/Dockerfile b/tasks/ambench-press-button-fahexa-i00-privileged/environment/Dockerfilenew file mode 100644index 0000000000..9050e5343c--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# Base image = AM-Bench (scrubbed: no scripted experts) + Isaac Lab / Isaac Sim 5.1 + the baked web assets (see+# images/ambench/; BUILD_ONLY). Everything task-specific is copied here; no reference solution is in the image.+FROM ghcr.io/mll-lab-nu/eai-ambench:0.1.0+COPY instance.json /app/instance.json+COPY rcb_ambench.py /opt/tools/rcb_ambench.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/docker-compose.yaml b/tasks/ambench-press-button-fahexa-i00-privileged/environment/docker-compose.yamlnew file mode 100644index 0000000000..ef66ce03c4--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/docker-compose.yaml@@ -0,0 +1,47 @@+# Isaac Sim needs an RTX-class NVIDIA GPU even headless. Harbor's local docker sandbox rejects [environment].gpus, but+# merging this onto the main service passes the device through. Isaac's shader/extension cache gets a volume for the+# trial, named after the trial's compose project (no fixed name: side-by-side trials must not share it; Harbor's+# teardown, `compose down --volumes`, deletes it): every trial compiles its shaders once (~2 min).+services:+ main:+ pids_limit: 16384 # rcb-monitor+ shm_size: "8gb"+ volumes:+ - rcb_limits:/run/rcb-limits:ro # rcb-monitor+ - rcb_ambench_cache:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+ # >>> rcb_monitor (resource limits monitor, docs/PROTOCOL.md §2.10; generated by scripts/rcb_monitor/inject.py)+ rcb_monitor:+ image: ghcr.io/mll-lab-nu/eai-monitor:0.1.0@sha256:f2c910f53f79c2bfa4a71298b10c78383cae3afc40720ca562cc845b8d20fb0c+ pid: host # sees every container's processes (and NVML's host PIDs); the agent never sees it+ cgroup: host # reads each container's own cgroup (memory, OOM kills, caps)+ network_mode: none+ cap_add: [SYS_PTRACE] # reads /proc of processes running as other users+ cpus: 0.5+ mem_limit: 256m+ pids_limit: 64+ restart: on-failure:3+ working_dir: /var/rcb-monitor+ volumes:+ - ./rcb_monitor:/opt/rcb_monitor:ro+ - rcb_limits:/run/rcb-limits+ environment:+ RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} # 1: stop the agent at a confirmed violation, and fail the trial+ command: ["python3", "/opt/rcb_monitor/monitor.py", "run"]+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+ # <<< rcb_monitor+volumes:+ rcb_limits: # rcb-monitor+ rcb_ambench_cache:diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/instance.json b/tasks/ambench-press-button-fahexa-i00-privileged/environment/instance.jsonnew file mode 100644index 0000000000..f10d0c326a--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "PressButton-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "PressButton",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 20.0,+ "initial_sha": "c125ec8a4fdd266248f2224493e8e50fd06b6648f7a21ca8568d8dd84267acd8"+}diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_ambench.py b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_ambench.pynew file mode 100644index 0000000000..623d3522c8--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_ambench.py@@ -0,0 +1,451 @@+"""+rcb_ambench.py — task-local tooling for AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0: aerial manipulation on+Isaac Lab / Isaac Sim 5.1): frozen task instance, privileged state, action recording, fresh-process replay. Same shape as+the other benchmarks' rcb_<bench>.py.++Concepts+--------+instance : one AM-Bench environment (a task with one robot and controller profile, e.g.+ PressButton-Am-FAHexa-Abs-PID-Direct-v0) and the seed of its reset (instance.json). AM-Bench draws the task's+ variation (where the button, the slider, the valve or the ball is) from the seeded reset; `initial_sha` is the+ hash of the start it builds, which every replay checks (`instance_matches`).+trajectory : the (T, 8) actions handed to the environment, one row per control step (120 Hz: one physics step of 1/120 s):+ the absolute end-effector target, position x y z (m, world frame, relative to the environment's origin),+ orientation as a unit quaternion w x y z, and the gripper command (-1 = closed .. +1 = open). AM-Bench's own+ low-level controller (the profile's PID) and floating-base inverse kinematics turn it into rotor thrusts and arm+ joint targets inside every step. Physics is PhysX on the GPU: a fresh process replays the same rows to the+ same state (the first episode of a process; later resets in the same process need not be bit-identical)+ WITHOUT the onboard cameras. With them (`Session(cameras=True)`), the per-step rendering makes PhysX's results+ depend on timing (measured: two fresh replays of the same rows part after a few hundred steps), so the+ grader, the reference recordings and a default Session run without them; cameras are for looking only.+success : AM-Bench's own `_get_success` of the task (its `terminated` signal); the episode ends at the first control step+ where it holds, or at the task's episode length (a time-out, not a success). Rows after the end never run.+ Isaac Lab resets the scene inside the step that ends an episode; the tooling keeps the end state's hash+ (taken just before that reset) as the episode's `state_sha`.+ RotateValve: the valve's `base_to_shaft` joint has no limits, and PhysX reports an articulation's unlimited+ revolute joint wrapped into [-pi, pi] (omni.physx 107.3, Isaac Sim 5.1), so AM-Bench's check `joint_pos >=+ 17/18 pi` would also pass a counter-clockwise turn of 190 degrees. The tooling gives that task's+ `_get_success` the unwrapped angle instead: the sum of the joint's per-step changes since the reset (one+ physics step moves it at most 5 rad/s / 120 Hz, far less than pi), so only the clockwise turn the+ instruction asks for counts. Physics, states and hashes are unchanged; the episode just does not end on a+ wrapped reading.++CLI+---+ python rcb_ambench.py replay --instance instance.json --traj traj.npz # one fresh-process replay (the grader's, no cameras)+ python rcb_ambench.py film --instance instance.json --traj traj.npz --video replay.mp4 # the same rows with the cameras on,+ filmed: an illustration only (camera rendering changes the numerics; never a verdict)+ python rcb_ambench.py make-instance --env-id <id> --seed 0 --out instance.json+ python rcb_ambench.py run-actions --instance instance.json --actions actions.npy --out traj.npz+"""+from __future__ import annotations++import os+for _k, _v in (("OMNI_KIT_ACCEPT_EULA", "YES"), ("ACCEPT_EULA", "Y"), ("OMNI_KIT_ALLOW_ROOT", "1"), ("PYTHONUNBUFFERED", "1"),+ ("JAX_PLATFORMS", "cpu")):+ os.environ.setdefault(_k, _v)++import argparse+import hashlib+import json+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++ACTION_DIM = 8+CONTROL_HZ = 120+MAX_STEPS = 8000 # a technical cap above every task's episode length (at most 60 s = 7200 steps)+ASSET_ROOT = "/opt/isaac-assets/Assets/Isaac/5.1" # baked web assets (images/ambench/web_assets.txt)+CAMERAS = ("ee_camera", "base_camera") # the robot profile's onboard cameras (384 x 384 RGB), only with Session(cameras=True)+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")+_APP = None+_APP_CAMERAS = False+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG) or ".", exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ev": ev, "t": round(time.time(), 3), "pid": os.getpid(), **kw}) + "\n")+ except OSError:+ pass+++def _launch_app(cameras: bool = False):+ """Isaac Sim, headless, the asset root pointed at the baked copies (no network needed); rendering only with cameras.+ Once per process: the first Session decides."""+ global _APP, _APP_CAMERAS+ if _APP is not None and cameras != _APP_CAMERAS:+ raise RuntimeError(f"this process launched Isaac Sim with cameras={_APP_CAMERAS}: one Session (one setting) per process")+ if _APP is None:+ _APP_CAMERAS = cameras+ from isaaclab.app import AppLauncher+ ns = argparse.Namespace()+ p = argparse.ArgumentParser(); AppLauncher.add_app_launcher_args(p)+ ns = p.parse_args([])+ ns.headless = True; ns.enable_cameras = bool(cameras); ns.device = "cuda:0"+ ns.kit_args = f"--/persistent/isaac/asset_root/cloud={ASSET_ROOT}"+ _APP = AppLauncher(ns).app+ return _APP+++def load_instance(instance) -> dict:+ return instance if isinstance(instance, dict) else json.loads(Path(instance).read_text())+++def _np(x) -> np.ndarray:+ return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)+++class Session:+ """One AM-Bench environment of one frozen instance. One per process (Isaac Sim runs once per process)."""++ def __init__(self, instance="/app/instance.json", *, strict: bool = False, cameras: bool = False):+ _launch_app(cameras)+ self.cameras = bool(cameras)+ import gymnasium as gym+ import torch+ import ambench.tasks # noqa: F401 (registers the environments)+ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg+ self.torch = torch+ self.instance = load_instance(instance)+ I = self.instance+ self.env_id, self.seed = I["env_id"], int(I["seed"])+ cfg = parse_env_cfg(self.env_id, device="cuda:0", num_envs=1)+ cfg.seed = self.seed+ if not self.cameras: # the robot profile's onboard cameras (and any scene camera) are not built: no rendering+ cfg.robot_profile.ee_camera = None; cfg.robot_profile.base_camera = None; cfg.scene_camera_cfg = None+ self.env = gym.make(self.env_id, cfg=cfg).unwrapped+ # Isaac Lab resets an environment whose episode ended INSIDE that step (DirectRLEnv.step -> _reset_idx), so after the+ # last step the scene is already the next episode's start: keep the end state's hash, taken just before that reset+ self._in_step = False; self.end_sha = None+ _reset_idx = self.env._reset_idx++ def _keep_end_state(env_ids, _reset_idx=_reset_idx):+ if self._in_step:+ self.end_sha = self.state_sha()+ return _reset_idx(env_ids)+ self.env._reset_idx = _keep_end_state+ self._valve = None+ if self.env_id.startswith("RotateValve-"):+ self._unwrap_valve_angle()+ self.n_resets = 0; self.n_steps_total = 0; self.n_clipped = 0+ self._video = None+ self.reset()+ self.initial_sha = self.state_sha()+ want = I.get("initial_sha")+ self.instance_matches = want is None or want == self.initial_sha+ if strict and not self.instance_matches:+ raise RuntimeError(f"the rebuilt scene differs from the frozen instance: {self.initial_sha} != {want}")+ _slog("session_start", env_id=self.env_id, instance_matches=self.instance_matches, cameras=self.cameras)++ # ------------------------------------------------------------------ episode+ def reset(self) -> None:+ """Back to the frozen instance (the seeded reset). Only the first episode of a process is guaranteed bit-identical+ to a fresh process's: check a trajectory with the `replay` CLI."""+ with self.torch.inference_mode(): # as step(): after a step Isaac Lab's buffers are inference tensors+ self.obs, _ = self.env.reset(seed=self.seed)+ self.end_sha = None+ if self._valve is not None:+ self._valve.update(prev=None, angle=None) # the joint is back at 0 rad: count from here+ self.rows: list[np.ndarray] = []+ self.done = False; self.succeeded = False; self.timed_out = False+ self.n_resets += 1+ if self.n_resets > 1:+ _slog("reset", env_id=self.env_id)++ def _unwrap_valve_angle(self) -> None:+ """RotateValve's success on the valve's unwrapped angle (see the module docstring): AM-Bench's `_get_success`, with+ the joint position PhysX reports in [-pi, pi] replaced by the sum of its per-step changes since the reset."""+ env, torch, v = self.env, self.torch, {"prev": None, "angle": None}+ self._valve = v+ two_pi = 2.0 * float(np.pi)++ def _get_success():+ q = env.valve_object.data.joint_pos[:, env.valve_joint_idx].clone()+ if v["prev"] is None: # the first step after a reset, from 0 rad (|q| < 0.05 rad here)+ angle = q+ else:+ angle = v["angle"] + torch.remainder(q - v["prev"] + np.pi, two_pi) - np.pi+ v.update(prev=q, angle=angle)+ target = env.cfg.valve_target_angle+ rotated = angle >= target+ return rotated, {"valve_engaged": angle >= env.cfg.valve_engagement_ratio * target, "valve_rotated": rotated}+ env._get_success = _get_success++ def valve_angle(self) -> float | None:+ """RotateValve: the valve's unwrapped angle in rad since the reset (positive = clockwise from the robot's side),+ what the success check reads; None in other tasks or before the first step."""+ if self._valve is None or self._valve["angle"] is None:+ return None+ return float(_np(self._valve["angle"]).reshape(-1)[0])++ @property+ def n_steps(self) -> int:+ return len(self.rows)++ def clip(self, row) -> tuple[np.ndarray, int]:+ a = np.asarray(row, dtype=np.float64).reshape(-1).copy()+ if a.size != ACTION_DIM or not np.all(np.isfinite(a)):+ raise ValueError(f"an action row has {ACTION_DIM} finite values (x y z qw qx qy qz gripper), got {a.size}")+ n = 0+ g = float(np.clip(a[7], -1.0, 1.0)); n += int(g != a[7]); a[7] = g+ if float(np.linalg.norm(a[3:7])) < 1e-9: # passed on as it is (AM-Bench's controller takes the quaternion it gets)+ raise ValueError("the action's quaternion has zero length")+ return a, n++ def step(self, row) -> bool:+ """One control step (1/120 s). Returns True when the episode is over; a step after that executes nothing."""+ if self.done:+ return True+ a, n = self.clip(row)+ self.n_clipped += n+ t = self.torch.as_tensor(a, dtype=self.torch.float32, device=self.env.device).reshape(1, ACTION_DIM)+ self._in_step = True+ try:+ with self.torch.inference_mode():+ self.obs, _, term, trunc, _ = self.env.step(t)+ finally:+ self._in_step = False+ self.rows.append(a)+ self.n_steps_total += 1+ self.succeeded = bool(_np(term).reshape(-1)[0])+ self.timed_out = bool(_np(trunc).reshape(-1)[0]) and not self.succeeded+ self.done = self.succeeded or self.timed_out or self.n_steps >= MAX_STEPS+ if self._video is not None:+ self._video_add()+ return self.done++ def success(self) -> bool:+ return self.succeeded++ def end_reason(self) -> str | None:+ if self.succeeded:+ return "success"+ if self.timed_out:+ return "timeout"+ return "step_cap" if self.done else None++ def hold_action(self) -> np.ndarray:+ """A row that keeps the current end-effector target and gripper command."""+ cp = self.env.control_pipeline+ pos = _np(cp.ee_cmd_pos_w[0] - self.env.scene.env_origins[0]).astype(np.float64)+ quat = _np(cp.ee_cmd_quat_w[0]).astype(np.float64)+ g = self.rows[-1][7] if self.rows else 1.0+ return np.r_[pos, quat, g]++ def status(self) -> dict[str, Any]:+ # state_sha: the episode's end state once it is over (taken before Isaac Lab's reset), else the current state+ return {"success": self.succeeded, "done": self.done, "end_reason": self.end_reason(), "control_steps": self.n_steps,+ "sim_time_s": round(self.n_steps / CONTROL_HZ, 4), "episode_length_s": float(self.env.cfg.episode_length_s),+ "resets": self.n_resets, "state_sha": self.end_sha if (self.done and self.end_sha) else self.state_sha()}++ def actions(self) -> np.ndarray:+ return np.asarray(self.rows, dtype=np.float64).reshape(-1, ACTION_DIM)++ def record_start(self) -> None:+ self.reset()++ def record_stop(self) -> np.ndarray:+ return self.actions()++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ self.reset()+ for row in A:+ if self.step(row):+ break+ _slog("replay", env_id=self.env_id, rows=int(len(A)), executed=self.n_steps)+ return {**self.status(), "executed_rows": self.n_steps}++ def save_trajectory(self, actions, path="/app/output/trajectory.npz", meta: dict | None = None) -> None:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, task=np.array(self.env_id), actions=A, meta=np.array(json.dumps(meta or {})))++ # ------------------------------------------------------------------ state (privileged)+ def state_sha(self) -> str:+ """sha256 over every articulation's and rigid object's root state, joint positions and velocities."""+ m = hashlib.sha256()+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name in sorted(group):+ d = group[name].data+ for t in (d.root_state_w, getattr(d, "joint_pos", None), getattr(d, "joint_vel", None)):+ if t is not None:+ m.update(name.encode()); m.update(_np(t).tobytes())+ return m.hexdigest()++ def state(self) -> dict[str, Any]:+ """Privileged observation of the task (AM-Bench's own `policy` observation: robot, end effector, task objects and+ goal positions, relative to the environment's origin)."""+ obs = self.obs["policy"][0] if isinstance(self.obs.get("policy"), list) else self.obs.get("policy")+ return {k: _np(v).reshape(-1).tolist() for k, v in (obs.items() if isinstance(obs, dict) else [])}++ def objects(self) -> dict[str, dict]:+ """Every articulation (but the robot) and rigid object of the scene: root pose (wxyz) and velocities, joint state."""+ out, o = {}, _np(self.env.scene.env_origins[0])+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name, obj in group.items():+ if name == "robot":+ continue+ rs = _np(obj.data.root_state_w[0])+ ent = {"position": (rs[:3] - o).tolist(), "orientation_wxyz": rs[3:7].tolist(), "velocity": rs[7:10].tolist(),+ "angular_velocity": rs[10:13].tolist()}+ if getattr(obj.data, "joint_pos", None) is not None:+ ent["joint_pos"] = _np(obj.data.joint_pos[0]).tolist(); ent["joint_names"] = list(obj.joint_names)+ out[name] = ent+ return out++ def proprio(self) -> dict[str, Any]:+ """The robot's own state: base and end-effector poses (world, relative to the env origin; wxyz) and velocities, the+ gripper opening and the arm joints, the current end-effector command."""+ e = self.env; o = _np(e.scene.env_origins[0])+ base = _np(e.robot.data.body_link_state_w[0, e.base_link_idx]); ee = _np(e.robot.data.body_link_state_w[0, e.ee_link_idx])+ jp = _np(e.robot.data.joint_pos[0]); jv = _np(e.robot.data.joint_vel[0])+ return {"base_pose": np.r_[base[:3] - o, base[3:7]].tolist(), "base_vel": base[7:13].tolist(),+ "ee_pose": np.r_[ee[:3] - o, ee[3:7]].tolist(), "ee_vel": ee[7:13].tolist(),+ "gripper_width": float(np.sum(jp[e.gripper_joint_ids])),+ "arm_joint_pos": jp[e.arm_joint_ids].tolist(), "arm_joint_vel": jv[e.arm_joint_ids].tolist(),+ "command": self.hold_action().tolist()}++ # ------------------------------------------------------------------ cameras+ def render_frame(self, camera: str = "ee_camera") -> np.ndarray:+ """RGB uint8 (384, 384, 3) of the robot's onboard camera `ee_camera` (at the end effector) or `base_camera` (on the+ airframe, looking forward), as of the last step. Only in a Session(cameras=True): the cameras render every step+ and that makes the physics timing-dependent, so check what you find there with the replay CLI (no cameras)."""+ if not self.cameras:+ raise RuntimeError("no cameras in this Session: start the process with Session(..., cameras=True) to look "+ "(its numerics differ from the grader's camera-free replay; check trajectories with the CLI)")+ cam = getattr(self.env, camera, None)+ if cam is None:+ raise KeyError(f"no camera {camera!r}; cameras: {[c for c in CAMERAS if getattr(self.env, c, None) is not None]}")+ return _np(cam.data.output["rgb"][0])[..., :3].astype(np.uint8)++ def start_video(self, path, fps: int = 30, camera: str = "ee_camera") -> None:+ import imageio.v2 as imageio+ self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),+ "every": max(1, round(CONTROL_HZ / fps)), "camera": camera, "path": str(path)}+ self._video_add(force=True)++ def _video_add(self, force: bool = False) -> None:+ v = self._video+ if force or self.n_steps % v["every"] == 0 or self.done:+ frames = [self.render_frame(c) for c in CAMERAS if getattr(self.env, c, None) is not None]+ v["w"].append_data(np.concatenate(frames, axis=1))++ def stop_video(self):+ v, self._video = self._video, None+ if v:+ v["w"].close()+ return v["path"]++ def close(self) -> None:+ _slog("session_end", env_id=self.env_id, sim_steps=self.n_steps_total, resets=self.n_resets)+ try:+ self.env.close()+ except Exception: # noqa: BLE001+ pass+++def load_trajectory(path, env_id: str) -> np.ndarray:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != env_id:+ raise ValueError(f"trajectory is for {str(d['task'])!r}, not {env_id!r}")+ A = np.asarray(d["actions"], dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != ACTION_DIM or A.shape[0] > MAX_STEPS or not np.all(np.isfinite(A)):+ raise ValueError(f"actions must be a finite (T, {ACTION_DIM}) array with T <= {MAX_STEPS}, got {list(A.shape)}")+ return A+++def _replay_rows(s: "Session", A: np.ndarray) -> dict:+ for row in A: # the process's first episode+ if s.step(row):+ break+ res = s.status()+ return {**{k: res[k] for k in ("success", "state_sha", "end_reason", "control_steps", "sim_time_s")}, "executed_rows": s.n_steps}+++def _cli_replay(a) -> int:+ """The grader's replay: a fresh process, no cameras (bit-reproducible), the process's first episode."""+ t0 = time.time()+ s = Session(a.instance)+ out: dict[str, Any] = {"task": s.env_id, "instance_matches": bool(s.instance_matches), "initial_sha": s.initial_sha}+ try:+ A = load_trajectory(a.traj, s.env_id)+ except Exception as exc: # noqa: BLE001+ out["error"] = f"bad trajectory: {exc!r}"[:300]; print(json.dumps(out), flush=True); return 2+ out["replays"] = [_replay_rows(s, A)]+ out["n_actions"] = int(len(A)); out["replay_wall_s"] = round(time.time() - t0, 2)+ print(json.dumps(out), flush=True)+ s.close()+ return 0+++def _cli_film(a) -> int:+ """An illustration, never a verdict: the rows with the onboard cameras on, filmed (both cameras side by side) plus the+ last end-effector frame. Camera rendering makes the physics timing-dependent, so this episode may end differently."""+ t0 = time.time()+ s = Session(a.instance, cameras=True)+ A = load_trajectory(a.traj, s.env_id)+ s.start_video(a.video, fps=a.fps)+ res = _replay_rows(s, A)+ s.stop_video()+ from PIL import Image+ Image.fromarray(s.render_frame("ee_camera")).save(str(Path(a.video).with_suffix(".last.png")))+ print(json.dumps({"task": s.env_id, "film": res, "video": a.video, "film_wall_s": round(time.time() - t0, 2)}), flush=True)+ s.close()+ return 0+++def _cli_make_instance(a) -> int:+ inst = {"env_id": a.env_id, "seed": int(a.seed)}+ s = Session(inst)+ inst.update({"task": a.env_id.split("-")[0], "action_dim": ACTION_DIM, "control_hz": CONTROL_HZ,+ "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha})+ Path(a.out).write_text(json.dumps(inst, indent=1) + "\n")+ print(json.dumps({"env_id": a.env_id, "initial_sha": s.initial_sha}), flush=True)+ s.close()+ return 0+++def _cli_run_actions(a) -> int:+ s = Session(a.instance, strict=True)+ for row in np.load(a.actions): # the process's first episode (no second reset), as the grader's+ if s.step(row):+ break+ res = {**s.status(), "executed_rows": s.n_steps}+ s.save_trajectory(s.actions(), a.out, meta={"source": "reference rows"})+ print(json.dumps({k: res[k] for k in ("success", "end_reason", "state_sha", "control_steps", "executed_rows", "sim_time_s")}), flush=True)+ s.close()+ return 0+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay"); r.add_argument("--instance", required=True); r.add_argument("--traj", required=True)+ f = sub.add_parser("film"); f.add_argument("--instance", required=True); f.add_argument("--traj", required=True)+ f.add_argument("--video", required=True); f.add_argument("--fps", type=int, default=30)+ m = sub.add_parser("make-instance"); m.add_argument("--env-id", required=True); m.add_argument("--seed", type=int, default=0); m.add_argument("--out", required=True)+ x = sub.add_parser("run-actions"); x.add_argument("--instance", required=True); x.add_argument("--actions", required=True); x.add_argument("--out", required=True)+ a = ap.parse_args(argv)+ global SESSION_LOG+ SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "") # the CLI logs nothing unless asked+ try:+ rc = {"replay": _cli_replay, "film": _cli_film, "make-instance": _cli_make_instance, "run-actions": _cli_run_actions}[a.cmd](a)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error: report it and leave at once+ import traceback+ traceback.print_exc(); rc = 3+ sys.stdout.flush(); sys.stderr.flush()+ os._exit(rc) # Isaac Sim's shutdown can hang or crash after the result line; the result is printed+++if __name__ == "__main__":+ main()diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/limits.json b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/limits.jsonnew file mode 100644index 0000000000..b276655018--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/limits.json@@ -0,0 +1,33 @@+{+ "caps": {+ "main": {+ "cpus": 8.0,+ "memory_gb": 34.0,+ "pids": 16384+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": true,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 16.0,+ "max_memory_gb": 28.0,+ "max_processes": 512,+ "mode": "privileged",+ "scope": "trial",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "ambench-press-button-fahexa-i00-privileged",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 16.0,+ "trial_max_memory_gb": 28.0,+ "window_sec": 120.0+}diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/monitor.pynew file mode 100644index 0000000000..81fdc91877--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/monitor.py@@ -0,0 +1,966 @@+#!/usr/bin/env python3+"""rcb_monitor: the trusted resource-limits monitor sidecar of every task (docs/PROTOCOL.md §2.10, record rcb-monitor/1).++Runs as the compose service `rcb_monitor` (generated by scripts/rcb_monitor/inject.py): `pid: host`, `cgroup: host`,+`network_mode: none`, CAP_SYS_PTRACE, the task's GPU reservation, its code read-only from the task directory. The agent+cannot see it (another PID namespace), reach it (no network) or write its record (its own file system).++Which containers it watches: the services that mount the trial's beacon volume `rcb_limits` (read-only at+/run/rcb-limits) are in scope, the ones that mount `rcb_observe` are only recorded (the benchmark's own services: the+simulator sidecar of standard modes, RoboPaint's privileged `scorer`). The compose project names both volumes, so they are unique to the trial; the monitor finds the containers as+the mount namespaces whose /run/rcb-limits is the same directory as its own (docker compose exec'd processes included).+A namespace that does not show the beacon is asked again at every tick (a container that is still being set up has the+host's root until its pivot_root: "no" is never remembered); a "yes" is kept only while the process that proved it lives.+A process whose first thread has exited is found through a thread that lives; a zombie counts in its parent's container.++Every tick (5 s; disk every 60 s) it samples, per container and summed over the scope: GPU memory (NVML, per process,+compute and graphics), memory (cgroup anon+shmem when the container has its own cgroup, else PSS anon+shmem), processes+(TGIDs, zombies included), disk growth under the limits' disk_paths in the agent's container (complete walks only, in+slices between the samples), CPU (recorded only). It appends to /var/rcb-monitor/samples.jsonl and+events.jsonl and writes the agent-visible /run/rcb-limits/usage.json.++Kernel OOM kills (`oom` events) are read from each watched container's cgroup `memory.events` by a thread of its own+(OomWatch), many times a second: a kill that takes the container's main process with it ends the container, and compose+restarts it with a new cgroup whose counters start at 0, within milliseconds -- a reading once per tick never sees it.+Every event says whom it hit (`scope`: a container the limits bind, or a benchmark-owned service that is only+recorded) and why (`cause`): "cap" when the container's own `oom` counter rose with it (the kernel says its memory+reached its own cap), else "host" (the host's OOM killer, or an enclosing cgroup's: not this container's doing).+Only a "cap" kill in the scope is a violation (rcb_limits.violations); the verifier step reports the others.++RCB_LIMITS_ENFORCE=1 (run-time switch; compose default 0; 0/1/true/false, anything else is a fatal record): once a+violation is confirmed (rcb_limits.violations, the verifier's own rule) the monitor SIGKILLs every in-scope process+except each container's PID 1, so the agent stops at once and Harbor goes on to collection and the verifier (an agent+killed this way ends like one that exited non-zero). It also protects the host (`emergency_kill` events, never a+violation by themselves): above EMERGENCY_GPU_FACTOR x the GPU-memory limit at one sample it kills the scope's process+that holds the most GPU memory; where the runtime applies no kernel memory cap, it stands in for it and kills the+largest process once the scope is above its declared memory caps.+0: it only records.++ python3 monitor.py run # the service's command+ python3 monitor.py seal --wait 90 # the first sidecar collect hook: seal the record (summary.json), print it+"""+import ctypes+import json+import os+import select+import signal+import stat as stat_mod+import sys+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import rcb_limits # noqa: E402+import selftest # noqa: E402++REC = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+PROC, CGROUP = "/proc", "/sys/fs/cgroup" # module globals: scripts/rcb_monitor/test_monitor.py points them at a fake tree+SCOPE_BEACON, OBSERVE_BEACON = "/run/rcb-limits", "/run/rcb-observe"+LIMITS = os.path.join(HERE, "limits.json")+HZ = os.sysconf("SC_CLK_TCK")+PAGE = os.sysconf("SC_PAGE_SIZE")+GIB = float(2 ** 30)+EMERGENCY_GPU_FACTOR = 1.5 # host protection (enforced runs): above this x the GPU-memory limit at one sample+DISK_SLICE_SEC = 1.5 # of every tick a running disk walk may take (the monitor's CPU cap is half a core)+DISK_WALK_MAX_SEC = 300.0 # a walk not finished by then is partial: a gap in the record, never a baseline+OOM_COLD_SEC = 0.02 # OomWatch: every memory.events is read this often (or at once, when the kernel notifies)+OOM_HOT_SEC = 0.002 # ... and this often for OOM_HOT_FOR_SEC after any of them changed (memory pressure)+OOM_HOT_FOR_SEC = 2.0+OOM_CAP_WINDOW_SEC = 10.0 # a kill is the container's own cap's when its `oom` counter rose with it or this shortly before+OOM_FORGET_SEC = 600.0 # a cgroup not seen by the sampler for this long is no longer watched+++# --------------------------------------------------------------------------------------------------- small helpers+def now():+ return time.time()+++def rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def read(p):+ try:+ with open(p) as f:+ return f.read()+ except OSError:+ return None+++def stat_id(p):+ try:+ st = os.stat(p)+ return (st.st_dev, st.st_ino)+ except OSError:+ return None+++def stat_of(base):+ """(starttime, utime+stime) of the process or thread at /proc path `base`, or None."""+ s = read(base + "/stat")+ if not s:+ return None+ try:+ f = s.rsplit(")", 1)[1].split()+ return int(f[19]), int(f[11]) + int(f[12])+ except (IndexError, ValueError):+ return None+++def proc_stat(pid):+ return stat_of(f"{PROC}/{pid}")+++def status(pid):+ s = read(f"{PROC}/{pid}/status")+ if not s:+ return {}+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v.strip()+ return d+++def kb(v):+ try:+ return int((v or "0").split()[0])+ except (ValueError, IndexError):+ return 0+++def append(name, obj):+ with open(os.path.join(REC, name), "a") as f:+ f.write(json.dumps(obj, separators=(",", ":")) + "\n")+++def write_json(path, obj):+ tmp = path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f, indent=1)+ os.replace(tmp, path)+++def event(kind, **kw):+ kw.update(t=round(now(), 2), event=kind)+ append("events.jsonl", kw)+++def no_dump():+ """Not dumpable: without CAP_SYS_PTRACE nobody (not even the same uid) can open /proc/<monitor>/{root,mem,fd}."""+ try:+ ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLE = 4+ except Exception:+ pass+++# --------------------------------------------------------------------------------------------------- NVML+class Nvml:+ """Per-process GPU memory (host PIDs: the monitor runs in the host PID namespace) and per-card use, via libnvidia-ml+ (ctypes; no nvidia-smi child processes)."""++ class Proc(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong),+ ("gpuInstanceId", ctypes.c_uint), ("computeInstanceId", ctypes.c_uint)]++ class Proc1(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong)]++ class Mem(ctypes.Structure):+ _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]++ def __init__(self):+ self.lib = ctypes.CDLL("libnvidia-ml.so.1")+ if self.lib.nvmlInit_v2() != 0:+ raise RuntimeError("nvmlInit failed")+ n = ctypes.c_uint(0)+ self.lib.nvmlDeviceGetCount_v2(ctypes.byref(n))+ self.handles = []+ for i in range(n.value):+ h = ctypes.c_void_p()+ if self.lib.nvmlDeviceGetHandleByIndex_v2(i, ctypes.byref(h)) == 0:+ self.handles.append(h)+ self.fns = []+ for name, st in (("nvmlDeviceGetComputeRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses", self.Proc1),+ ("nvmlDeviceGetGraphicsRunningProcesses", self.Proc1)):+ kind = "compute" if "Compute" in name else "graphics"+ if any(k == kind for k, _, _ in self.fns):+ continue+ try:+ self.fns.append((kind, getattr(self.lib, name), st))+ except AttributeError:+ pass++ def sample(self):+ """({host pid: MiB}, {card index: (used MiB, total MiB)}, {host pids whose memory NVML does not tell})."""+ per, cards, unknown = {}, {}, set()+ for i, h in enumerate(self.handles):+ m = self.Mem()+ if self.lib.nvmlDeviceGetMemoryInfo(h, ctypes.byref(m)) == 0:+ cards[i] = (m.used // 2 ** 20, m.total // 2 ** 20)+ seen = {}+ for _kind, fn, st in self.fns:+ cnt = ctypes.c_uint(0)+ rc = fn(h, ctypes.byref(cnt), None)+ if rc not in (0, 7): # 7 = NVML_ERROR_INSUFFICIENT_SIZE: cnt now holds the count+ continue+ cnt = ctypes.c_uint(cnt.value + 16)+ arr = (st * cnt.value)()+ if fn(h, ctypes.byref(cnt), arr) != 0:+ continue+ for k in range(cnt.value):+ mem = arr[k].usedGpuMemory+ if mem >= 2 ** 63: # NVML_VALUE_NOT_AVAILABLE (MIG / vGPU / WSL): not a zero+ unknown.add(arr[k].pid)+ mib = 0+ else:+ mib = mem // 2 ** 20+ seen[arr[k].pid] = max(seen.get(arr[k].pid, 0), mib) # a C+G process is in both lists+ for p, v in seen.items():+ per[p] = per.get(p, 0) + v+ return per, cards, unknown+++# --------------------------------------------------------------------------------------------------- disk+class DiskWalk:+ """One measurement of the files under `paths` below `root` (the agent container's root, seen through /proc): the+ sum of st_blocks, every hard-linked file once, never descending into another mount (a directory on another device;+ files are not asked for theirs: on an overlay root whose layers sit on different file systems they report their+ layer's), `exclude` skipped. It runs in+ slices (step) between the monitor's samples, so a large tree delays no sample. `done` only when every directory was+ read: only then is `bytes` a measurement; before that it is a lower bound."""++ def __init__(self, root, paths, exclude):+ self.root, self.t0 = root, now()+ self.bytes = self.entries = 0+ self.done, self.why = False, None+ self._it = self._walk(list(paths), {root + x.rstrip("/") for x in exclude})++ def _walk(self, paths, excl):+ linked = set() # (dev, ino) of files with several names: counted once+ for base in paths:+ top = self.root + base+ try:+ dev = os.lstat(top).st_dev+ except FileNotFoundError:+ continue # the path does not exist in this container: nothing under it+ except OSError as e:+ self.why = f"{base}: {type(e).__name__}"+ return+ stack = [top]+ while stack:+ d = stack.pop()+ try:+ it = os.scandir(d)+ except FileNotFoundError:+ continue # removed since its parent was read+ except OSError as e:+ self.why = f"{d[len(self.root):]}: {type(e).__name__}"+ return+ with it:+ for e in it:+ try:+ st = e.stat(follow_symlinks=False)+ except OSError:+ continue # removed meanwhile+ if stat_mod.S_ISDIR(st.st_mode):+ if st.st_dev != dev or e.path in excl:+ continue # another mount (never crossed: not the container's own files)+ stack.append(e.path)+ elif st.st_nlink > 1:+ k = (st.st_dev, st.st_ino)+ if k in linked:+ continue+ linked.add(k)+ self.bytes += st.st_blocks * 512+ self.entries += 1+ if self.entries % 256 == 0:+ yield+ yield+ self.done = True++ def step(self, budget_sec):+ """Walk on for at most `budget_sec`; True when the walk has ended (done, or failed with `why`)."""+ end = now() + budget_sec+ for _ in self._it:+ if now() >= end:+ return False+ return True+++# --------------------------------------------------------------------------------------------------- OOM kills+class OomWatch:+ """Kernel OOM kills of the watched containers, from each one's cgroup v2 `memory.events`:+ oom times the cgroup's memory reached its own limit (memory.max) and an allocation was about to fail+ oom_kill processes of the cgroup killed by any OOM killer (its own limit's, an enclosing cgroup's, the host's)+ A kill whose `oom` counter rose with it (or within OOM_CAP_WINDOW_SEC before) happened at the container's own cap+ (`cause: "cap"`); one without is the host's or an enclosing cgroup's OOM killer (`cause: "host"`), which the+ container did not cause by its own use (PROTOCOL §2.10: nothing another trial does can fail a trial).++ The counters live and die with the cgroup, and a container whose main process is killed is gone (and restarted by+ compose with fresh counters) within milliseconds. So the files are read by this object's own thread, every+ OOM_COLD_SEC, at once when the kernel signals a change (poll: memory.events notifies), and every OOM_HOT_SEC for a+ while after any change (the `max` counter rises under memory pressure, before a kill). A kill that removes the+ cgroup within about a millisecond can still be missed: such a kill is then in no record.++ scan() reads every file once; the sampler calls it at each tick when the thread does not run (the tests). The+ thread ends when the record is sealed."""++ def __init__(self):+ self.lock = threading.Lock()+ self.w = {} # cgroup dir -> {"role", "scope", "fd", "kill", "oom", "sig", "cap_t", "seen"}+ self.hot_until = 0.0+ self.thread = None+ self.stopped = False # set at the seal: the record is closed, like the samples++ def watch(self, cg, role, scope, t):+ """The sampler saw this container's cgroup at time t."""+ with self.lock:+ e = self.w.get(cg)+ if e is None:+ e = self.w[cg] = {"fd": None, "kill": None, "oom": None, "sig": None, "cap_t": None}+ e.update(role=role, scope=bool(scope), seen=t)++ @staticmethod+ def _close(e):+ if e["fd"] is not None:+ try:+ os.close(e["fd"])+ except OSError:+ pass+ e["fd"] = None++ def _read(self, cg, e):+ """The counters of the cgroup's memory.events ({} when the file cannot be read: the container is not up).+ A file that stops answering belonged to a cgroup that is gone; the same path opened again is a new cgroup (the+ container restarted: another directory, by its inode and creation time), whose counters all belong to the+ trial: they are compared with 0. The same cgroup opened again keeps what was already counted."""+ for _ in (0, 1):+ try:+ if e["fd"] is None:+ e["fd"] = os.open(cg + "/memory.events", os.O_RDONLY)+ st = os.stat(cg)+ ident = (st.st_dev, st.st_ino, st.st_ctime_ns)+ if e["sig"] is not None and ident != e.get("ident"):+ e["kill"] = e["oom"] = 0 # read before, gone, here again: another instance of the cgroup+ e["ident"] = ident+ os.lseek(e["fd"], 0, os.SEEK_SET)+ out = {}+ for line in os.read(e["fd"], 8192).decode("ascii", "replace").splitlines():+ k, _, v = line.partition(" ")+ if v.strip().isdigit():+ out[k] = int(v)+ return out+ except OSError:+ self._close(e)+ return {}++ def scan(self):+ """Read every watched file once and record the kills since the last reading. True when a counter changed."""+ changed = False+ with self.lock:+ t = now()+ for cg, e in list(self.w.items()):+ if t - e["seen"] > OOM_FORGET_SEC:+ self._close(e)+ del self.w[cg]+ continue+ c = self._read(cg, e)+ if "oom_kill" not in c:+ continue+ kill, oom = c["oom_kill"], c.get("oom", 0)+ sig = (kill, oom, c.get("max", 0))+ if e["kill"] is None or kill < e["kill"] or oom < e["oom"]:+ # the first reading is the baseline; counters that went back are a new cgroup under the same path+ e["kill"], e["oom"] = (kill, oom) if e["kill"] is None else (0, 0)+ changed |= sig != e["sig"]+ if oom > e["oom"]:+ e["cap_t"] = t+ if kill > e["kill"]:+ at_cap = e["cap_t"] is not None and t - e["cap_t"] <= OOM_CAP_WINDOW_SEC+ kw = {"role": e["role"], "scope": e["scope"], "count": kill - e["kill"],+ "cause": "cap" if at_cap else "host", "cap_hits": oom - e["oom"]}+ for name, key in (("memory.max", "memory_cap_gb"), ("memory.current", "memory_current_gb")):+ v = (read(cg + "/" + name) or "").strip() # evidence only: the cause is the counters'+ if v.isdigit():+ kw[key] = round(int(v) / GIB, 3)+ event("oom", **kw)+ e["kill"], e["oom"], e["sig"] = kill, oom, sig+ return changed++ def start(self):+ self.thread = threading.Thread(target=self._loop, name="rcb-oom-watch", daemon=True)+ self.thread.start()++ def _loop(self):+ said = False+ while not self.stopped:+ try:+ if self.scan():+ self.hot_until = now() + OOM_HOT_FOR_SEC+ if now() < self.hot_until:+ time.sleep(OOM_HOT_SEC)+ continue+ with self.lock:+ fds = [e["fd"] for e in self.w.values() if e["fd"] is not None]+ if not fds:+ time.sleep(OOM_COLD_SEC)+ continue+ p = select.poll() # memory.events notifies its readers (POLLPRI) when it changes+ for fd in fds:+ p.register(fd, select.POLLPRI | select.POLLERR)+ if p.poll(OOM_COLD_SEC * 1000):+ self.hot_until = now() + OOM_HOT_FOR_SEC+ except Exception as e: # never stop watching+ if not said:+ said = True+ try:+ event("error", why=f"oom watch: {type(e).__name__}: {e}"[:300])+ except Exception:+ pass+ time.sleep(OOM_COLD_SEC)+++# --------------------------------------------------------------------------------------------------- the monitor+class Monitor:+ def __init__(self):+ self.lim = rcb_limits.read_json(LIMITS) or {}+ self.tick = float(self.lim.get("tick_sec", 5))+ self.disk_tick = float(self.lim.get("disk_tick_sec", 60))+ self.enforce, self.switch_error = rcb_limits.parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ self.me_mnt = rl(f"{PROC}/self/ns/mnt")+ self.beacon = {"scope": stat_id(SCOPE_BEACON), "observe": stat_id(OBSERVE_BEACON)}+ self.cls = {} # mnt ns -> {"kind", "role", "witness": (proc path, starttime)}: only what IS watched+ self.neg, self.ok = set(), set() # this tick: namespaces that said no / whose witness still lives+ self.via = {} # pid -> /proc path of a living thread, for a process whose first thread has exited+ self.prev_cpu = {} # pid -> (starttime, ticks, t)+ self.oomw = OomWatch() # kernel OOM kills of the watched containers (its own thread in run())+ self.disk_base = None # GiB under disk_paths at the first complete walk (kept in state.json across restarts)+ self.disk_last = 0.0+ self.disk_gb = None+ self.walk = None # (DiskWalk, mnt ns, proc path, starttime) of the measurement under way+ self.series = [] # [(t, {metric: value})] of the last window, for enforcement decisions+ self.confirmed = {} # metric -> time+ self.kill_until = 0.0+ self.killed = 0+ self.emergency = [] # the emergency_kill events of this run+ self.scope_seen = False+ self.gpu_unknown = False+ self.caps = selftest.capabilities()+ self.nvml = None+ try:+ self.nvml = Nvml()+ except Exception as e:+ self.caps["nvml_error"] = f"{type(e).__name__}: {e}"[:200]+ self.caps["nvml"] = int(self.nvml is not None)+ self.caps["nvml_devices"] = len(self.nvml.handles) if self.nvml else 0+ self.t0 = now()+ self._last_measures, self._gpu_per = [], {}+ self.fatal_scope = False++ # ---- scope discovery+ def base(self, pid):+ """The /proc path to read a process's namespaces, root and memory from."""+ return self.via.get(pid) or f"{PROC}/{pid}"++ def classify(self, mnt, base):+ """{"kind": "scope" | "observe", "role": "main" | "sidecar"} when the mount namespace `mnt` (of the process or+ thread at /proc path `base`) is one of the trial's containers, else None.++ "No" is never remembered beyond this tick: while a container is set up, its init process is already in a new+ mount namespace but still has the host's root, and the beacon appears only with its pivot_root. "Yes" is+ remembered while the process that proved it lives in the namespace (the kernel may give the number of a+ namespace that ended to a new one)."""+ if mnt in self.ok:+ return self.cls[mnt]+ if mnt in self.neg:+ return None+ c = self.cls.get(mnt)+ if c is not None:+ wbase, wstart = c["witness"]+ ws = stat_of(wbase)+ if ws and ws[0] == wstart and rl(wbase + "/ns/mnt") == mnt:+ self.ok.add(mnt)+ return c+ del self.cls[mnt]+ root = base + "/root"+ kind = None+ if self.beacon["scope"] and stat_id(root + SCOPE_BEACON) == self.beacon["scope"]:+ kind = "scope"+ elif self.beacon["observe"] and stat_id(root + OBSERVE_BEACON) == self.beacon["observe"]:+ kind = "observe"+ st = stat_of(base)+ here = st is not None and rl(base + "/ns/mnt") == mnt # a vanished process tells nothing: ask the next+ if kind and here:+ c = {"kind": kind, "role": "main" if os.path.isdir(root + "/logs/agent") else "sidecar",+ "witness": (base, st[0])}+ self.cls[mnt] = c+ self.ok.add(mnt)+ return c+ if here:+ self.neg.add(mnt)+ return None++ def live_thread(self, pid):+ """/proc path of a thread of `pid` that still runs (its first thread has exited: /proc/<pid>/ns is empty)."""+ try:+ tids = os.listdir(f"{PROC}/{pid}/task")+ except OSError:+ return None+ for tid in tids:+ b = f"{PROC}/{pid}/task/{tid}"+ if tid != str(pid) and rl(b + "/ns/mnt"):+ return b+ return None++ def groups(self):+ """{mnt ns: {"kind", "role", "pids": [...], "zombies": n}} of the watched containers."""+ self.neg, self.ok, self.via = set(), set(), {}+ out, where, lost = {}, {}, []+ try:+ names = os.listdir(PROC)+ except OSError:+ names = []+ for d in names:+ if not d.isdigit():+ continue+ pid = int(d)+ mnt = rl(f"{PROC}/{pid}/ns/mnt")+ if mnt is None:+ lost.append(pid)+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, f"{PROC}/{pid}")+ if c:+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ zombies = []+ for pid in lost:+ b = self.live_thread(pid)+ if not b:+ zombies.append(pid)+ continue+ mnt = rl(b + "/ns/mnt") # its first thread exited, the others run on: a process like any other+ if mnt is None:+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, b)+ if c:+ self.via[pid] = b+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ for pid in zombies:+ st = status(pid)+ if st.get("State", "").startswith("Z"): # a zombie holds a PID until its parent reaps it: counted there+ try:+ g = out.get(where.get(int(st.get("PPid", "0"))))+ except ValueError:+ g = None+ if g:+ g["zombies"] += 1+ self.cls = {m: c for m, c in self.cls.items() if m in self.ok}+ return out++ # ---- per-container measurements+ def cgroup_of(self, pids):+ """The container's own cgroup v2 directory (under the host tree, `cgroup: host`) when every process in it is this+ container's (rootless podman without cgroup delegation leaves containers in a shared one), else None."""+ paths = set()+ for p in pids[:8]:+ s = read(f"{PROC}/{p}/cgroup") or ""+ for line in s.splitlines():+ if line.startswith("0::"):+ paths.add(line[3:].strip())+ if len(paths) != 1:+ return None+ d = CGROUP + paths.pop()+ procs = read(d + "/cgroup.procs")+ if procs is None:+ return None+ members = {int(x) for x in procs.split() if x.isdigit()}+ return d if members and members <= set(pids) else None++ def mem_pss(self, pids):+ tot = 0+ for p in pids:+ s = read(self.base(p) + "/smaps_rollup")+ if s is None:+ st = status(p)+ tot += kb(st.get("RssAnon")) + kb(st.get("RssShmem"))+ continue+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v+ tot += (kb(d.get("Pss_Anon")) + kb(d.get("Pss_Shmem"))) if "Pss_Anon" in d else kb(d.get("Pss"))+ return tot / 1024.0 / 1024.0 # GiB++ def measure(self, g, gpu_per, t, gpu_unknown=()):+ pids = g["pids"]+ threads = cpu = 0.0+ for p in pids:+ threads += int(status(p).get("Threads", "0") or 0)+ ps = proc_stat(p)+ if ps:+ pv = self.prev_cpu.get(p)+ if pv and pv[0] == ps[0] and t > pv[2]:+ cpu += max(0, ps[1] - pv[1]) / HZ / (t - pv[2])+ self.prev_cpu[p] = (ps[0], ps[1], t)+ cg = self.cgroup_of(pids)+ m = {"kind": g["kind"], "role": g["role"], "processes": len(pids) + g.get("zombies", 0),+ "zombies": g.get("zombies", 0), "threads": int(threads), "cpu": round(cpu, 2),+ "gpu_memory_gb": round(sum(gpu_per.get(p, 0) for p in pids) / 1024.0, 3), "cgroup": int(cg is not None)}+ unknown = sum(1 for p in pids if p in gpu_unknown)+ if unknown:+ m["gpu_unmeasured"] = unknown # processes on the GPU whose memory NVML does not tell+ if cg:+ st = {}+ for line in (read(cg + "/memory.stat") or "").splitlines():+ k, _, v = line.partition(" ")+ st[k] = v+ try:+ m["memory_gb"] = round((int(st.get("anon", 0)) + int(st.get("shmem", 0))) / GIB, 3)+ except ValueError:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ mx = (read(cg + "/memory.max") or "").strip()+ m["memory_cap_gb"] = None if mx in ("", "max") else round(int(mx) / GIB, 2)+ self.oomw.watch(cg, g["role"], g["kind"] == "scope", now())+ else:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ return m++ # ---- disk+ def main_proc(self, groups):+ """(mnt ns, pid) to reach the agent container's files through: its PID 1 when visible (it outlives the others)."""+ for mnt, g in groups.items():+ if g["kind"] == "scope" and g["role"] == "main" and g["pids"]:+ init = [p for p in g["pids"] if (status(p).get("NSpid") or "").split()[-1:] == ["1"]]+ return mnt, (init[0] if init else min(g["pids"]))+ return None, None++ def disk_step(self, t, groups):+ """The disk value of this sample: GiB the files under disk_paths grew since the baseline, or None (not measured+ at this tick). Only a complete walk of a container that is still there is a measurement; only such a walk sets+ the baseline. A walk that did not finish is a lower bound: it can show that the limit is exceeded, never that it+ is not, and it never becomes the baseline."""+ if self.walk is None:+ mnt, pid = self.main_proc(groups)+ if pid is None or t - self.disk_last < self.disk_tick:+ return None+ b = self.base(pid)+ st = stat_of(b)+ if st is None:+ return None+ self.disk_last = t+ self.walk = (DiskWalk(b + "/root", self.lim.get("disk_paths") or ["/app"], self.lim.get("disk_exclude") or []),+ mnt, b, st[0])+ w, mnt, b, start = self.walk+ ended = w.step(DISK_SLICE_SEC)+ if not ended and now() - w.t0 <= DISK_WALK_MAX_SEC:+ return None # goes on at the next tick+ self.walk = None+ st = stat_of(b)+ there = st is not None and st[0] == start and rl(b + "/ns/mnt") == mnt # the same container, still up+ gb = w.bytes / GIB+ if ended and w.done and there:+ if self.disk_base is None:+ self.disk_base = gb+ self.save_state()+ event("disk_baseline", gb=round(gb, 3), entries=w.entries)+ self.disk_gb = round(max(0.0, gb - self.disk_base), 3)+ return self.disk_gb+ why = "the container's process ended during the walk" if not there else (w.why or "not finished in time")+ event("disk_partial", why=why, gb=round(gb, 3), entries=w.entries, sec=round(now() - w.t0, 1))+ lim = float(self.lim.get("max_disk_gb") or 0)+ if there and self.disk_base is not None and lim and gb - self.disk_base > lim:+ self.disk_gb = round(gb - self.disk_base, 3) # already over the limit, whatever the rest holds+ return self.disk_gb+ return None++ # ---- state that must outlive a restart of the monitor (restart: on-failure)+ def save_state(self):+ try:+ write_json(os.path.join(REC, "state.json"), {"disk_base": self.disk_base})+ except OSError:+ pass++ def restore(self):+ """After a restart: the disk baseline, the confirmed violations and the last window of samples come back from+ the record, so that a crash neither resets the baseline nor forgets time already spent over a limit."""+ st = rcb_limits.read_json(os.path.join(REC, "state.json")) or {}+ if isinstance(st.get("disk_base"), (int, float)):+ self.disk_base = float(st["disk_base"])+ _, samples, events = rcb_limits.load_record(REC)+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [(s["t"], s.get("scope") or {}) for s in samples+ if isinstance(s.get("t"), (int, float)) and s["t"] >= self.t0 - window - 3 * self.tick]+ for e in events:+ k = e.get("event")+ if k == "violation" and e.get("metric"):+ self.confirmed.setdefault(e["metric"], e.get("t") or self.t0)+ elif k in ("kill", "emergency_kill"):+ self.killed += int(e.get("processes") or 0)+ if k == "emergency_kill":+ self.emergency.append(e)+ elif k == "scope_found":+ self.scope_seen = True+ if self.enforce and self.confirmed and self.t0 - max(self.confirmed.values()) < 60:+ self.kill_until = max(self.confirmed.values()) + 60++ # ---- enforcement+ @staticmethod+ def spared(pids):+ """The container's own processes that must outlive a kill: its PID 1 and what PID 1 started with it (Harbor's+ `sh -c "sleep infinity"` keepalive). Agent processes are exec'd into the container (their parent is outside+ it) or, when orphaned, adopted by PID 1 later: those are never spared."""+ st = {p: status(p) for p in pids}+ init = [p for p in pids if (st[p].get("NSpid") or "").split()[-1:] == ["1"]]+ if not init:+ return set()+ t1 = (proc_stat(init[0]) or (0, 0))[0]+ keep = set(init)+ for p in pids:+ ns_ppid = None+ ns = (st[p].get("NSpid") or "").split()+ if ns and st[p].get("PPid") is not None:+ # PPid in /proc/<pid>/status is in the reader's namespace (host); compare with PID 1's host PID+ ns_ppid = int(st[p]["PPid"])+ ps = proc_stat(p)+ if ns_ppid == init[0] and ps and ps[0] - t1 <= 2 * HZ: # started with the container, not adopted later+ keep.add(p)+ return keep++ def kill_scope(self, groups, why):+ n = 0+ for mnt, g in groups.items():+ if g["kind"] != "scope":+ continue+ snap = {p: proc_stat(p) for p in g["pids"]}+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue # PID 1 and its keepalive: the container stays up for collection+ if rl(self.base(p) + "/ns/mnt") != mnt or not snap[p] or proc_stat(p) is None \+ or proc_stat(p)[0] != snap[p][0]:+ continue # gone, or its PID now names another process+ try:+ os.kill(p, signal.SIGKILL)+ n += 1+ except OSError:+ pass+ if n:+ self.killed += n+ event("kill", why=why, processes=n)+ return n++ def scope_memory_cap(self):+ """GiB: the declared memory caps of the services the limits bind, summed (None: not declared)."""+ caps = self.lim.get("caps") or {}+ names = self.lim.get("scope_services") or (+ [n for n in caps if n != "*"] if self.lim.get("scope") == "trial" else ["main"])+ vals = [float(caps[n]["memory_gb"]) for n in names if isinstance(caps.get(n), dict) and caps[n].get("memory_gb")]+ return sum(vals) if vals else None++ def check(self, t, scope_vals, groups):+ self.series.append((t, scope_vals))+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [x for x in self.series if x[0] >= t - window - 3 * self.tick]+ samples = [{"t": a, "scope": b} for a, b in self.series]+ for v in rcb_limits.violations(samples, self.lim):+ if v["metric"] not in self.confirmed:+ self.confirmed[v["metric"]] = t+ event("violation", **v)+ if self.enforce:+ self.kill_until = t + 60+ if self.enforce and t <= self.kill_until:+ self.kill_scope(groups, ",".join(sorted(self.confirmed)))+ # Host protection (enforced runs only; PROTOCOL §2.10). An emergency kill is never a violation by itself: the+ # trial fails only by the sustained rule above or a kernel OOM kill at its own memory cap. Both conditions are+ # the trial's own doing (its scope's use against its own limit or caps), never the state of a card or host it+ # shares with other trials.+ if self.enforce:+ cap = self.scope_memory_cap()+ lim_gpu = float(self.lim.get("max_gpu_memory_gb") or 0)+ if cap and scope_vals["memory_gb"] > cap and not any(+ m.get("memory_cap_gb") for m in self._last_measures if m["kind"] == "scope"):+ # no kernel memory cap holds here (e.g. rootless podman without cgroups): stand in for it+ self._emergency(groups, "memory", cap, scope_vals["memory_gb"], key="mem")+ if lim_gpu and scope_vals["gpu_memory_gb"] > EMERGENCY_GPU_FACTOR * lim_gpu:+ self._emergency(groups, "gpu_memory", lim_gpu, scope_vals["gpu_memory_gb"], key="gpu")++ def _emergency(self, groups, why, limit, observed, key):+ best, bv = None, 0 # only a process that holds some: never one with none of it+ for g in groups.values():+ if g["kind"] != "scope":+ continue+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue+ v = self._gpu_per.get(p, 0) if key == "gpu" else self.rss_kb(p)+ if v > bv:+ best, bv = p, v+ if best:+ try:+ os.kill(best, signal.SIGKILL)+ self.killed += 1+ e = {"why": why, "limit": limit, "observed": round(observed, 3), "processes": 1}+ event("emergency_kill", **e)+ self.emergency.append(dict(e, t=round(now(), 2)))+ except OSError:+ pass++ def rss_kb(self, p):+ v = kb(status(p).get("VmRSS"))+ if not v and p in self.via: # the first thread has exited: its status has no memory lines+ for line in (read(self.via[p] + "/status") or "").splitlines():+ if line.startswith("VmRSS:"):+ v = kb(line.partition(":")[2])+ return v++ # ---- main loop+ def run(self):+ os.makedirs(REC, exist_ok=True)+ restarted = os.path.exists(os.path.join(REC, "meta.json"))+ meta = {"format": rcb_limits.FORMAT, "started": round(self.t0, 2), "enforce": self.enforce, "limits": self.lim,+ "capabilities": self.caps, "beacons": {k: bool(v) for k, v in self.beacon.items()}}+ if self.switch_error:+ meta["switch_error"] = self.switch_error+ if restarted:+ self.restore()+ event("restart", capabilities=self.caps)+ else:+ write_json(os.path.join(REC, "meta.json"), meta)+ event("start", enforce=self.enforce, capabilities=self.caps)+ if self.switch_error:+ event("fatal", why=self.switch_error + " (nothing is enforced; the trial is not a result)")+ if not self.beacon["scope"]:+ event("fatal", why="no scope beacon mounted at /run/rcb-limits")+ if self.lim.get("gpu") and not self.nvml:+ event("fatal", why="GPU task but NVML is unavailable: " + str(self.caps.get("nvml_error")))+ sys.setswitchinterval(0.001) # the OOM watch must get its turn within a millisecond+ self.oomw.start()+ while not os.path.exists(os.path.join(REC, "seal.request")):+ t = now()+ try:+ self.tick_once(t)+ except Exception as e: # a vanished process mid-read must never stop the record+ import traceback+ traceback.print_exc()+ event("error", why=f"{type(e).__name__}: {e}"[:300])+ for p in list(self.prev_cpu):+ if t - self.prev_cpu[p][2] > 60:+ del self.prev_cpu[p]+ time.sleep(max(0.2, self.tick - (now() - t)))+ self.seal()+ while True: # stay up: Harbor copies the record after the hook+ time.sleep(3600)++ def tick_once(self, t):+ groups = self.groups()+ gpu_per, cards, gpu_unknown = self.nvml.sample() if self.nvml else ({}, {}, set())+ self._gpu_per = gpu_per+ ms = [self.measure(g, gpu_per, t, gpu_unknown) for g in groups.values()]+ self._last_measures = ms+ if self.oomw.thread is None:+ self.oomw.scan() # no thread (tests): read the OOM counters with the sample+ scope = [m for m in ms if m["kind"] == "scope"]+ if scope and not self.scope_seen:+ self.scope_seen = True+ event("scope_found", containers=len(scope), roles=sorted(m["role"] for m in scope))+ if not self.scope_seen and not self.fatal_scope and t - self.t0 > 120:+ self.fatal_scope = True+ event("fatal", why="no container mounting the trial's beacon found within 120 s")+ disk_now = self.disk_step(t, groups)+ vals = {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in scope), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in scope), 3),+ "processes": sum(m["processes"] for m in scope), "disk_gb": disk_now}+ unknown = sum(m.get("gpu_unmeasured", 0) for m in scope)+ if unknown:+ vals["gpu_unmeasured"] = unknown+ if not self.gpu_unknown:+ self.gpu_unknown = True+ event("gpu_unmeasured", processes=unknown,+ why="NVML does not tell the GPU memory of processes in scope (MIG / vGPU?): counted as 0")+ obs = [m for m in ms if m["kind"] == "observe"]+ append("samples.jsonl", {"t": round(t, 2), "scope": vals,+ "observe": {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in obs), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in obs), 3),+ "processes": sum(m["processes"] for m in obs)},+ "cards": {str(k): v for k, v in cards.items()}, "containers": ms})+ self.check(t, vals, groups)+ try:+ write_json(SCOPE_BEACON + "/usage.json", {+ "t": round(t, 2), "gpu_memory_gb": vals["gpu_memory_gb"], "memory_gb": vals["memory_gb"],+ "processes": vals["processes"], "disk_gb": self.disk_gb, "enforced": self.enforce,+ "limits": {k: self.lim.get(k) for k in ("max_gpu_memory_gb", "max_memory_gb", "max_processes",+ "max_disk_gb", "sustain_sec", "window_sec")},+ "violations": sorted(self.confirmed),+ # processes the monitor killed at once to protect the host (not violations by themselves)+ "emergency_kills": len(self.emergency), "last_emergency_kill": (self.emergency or [None])[-1]})+ except OSError:+ pass++ def seal(self):+ try:+ self.oomw.scan() # the counters once more, whatever the watch thread is doing+ except Exception:+ pass+ # The record ends here, for OOM kills as for the samples: what happens to a sidecar in the collect hooks that+ # follow (its replays) is the grader's to judge, from the hook's own evidence.+ self.oomw.stopped = True+ summary, samples, events = rcb_limits.load_record(REC)+ viol = rcb_limits.violations(samples, self.lim, events)+ meta = rcb_limits.read_json(os.path.join(REC, "meta.json")) or {}+ out = {+ "format": rcb_limits.FORMAT, "sealed": True, "enforce": meta.get("enforce", self.enforce),+ "started": meta.get("started"), "ended": round(now(), 2), "n_samples": len(samples),+ "scope_seen": self.scope_seen or any((s.get("scope") or {}).get("processes") for s in samples),+ "peaks": rcb_limits.peaks(samples), "violations": viol,+ "killed": sum(int(e.get("processes") or 0) for e in events if e.get("event") in ("kill", "emergency_kill")),+ "emergency_kills": sum(1 for e in events if e.get("event") == "emergency_kill"),+ "disk_baseline_gb": self.disk_base,+ "disk_partial_walks": sum(1 for e in events if e.get("event") == "disk_partial"),+ "restarts": sum(1 for e in events if e.get("event") == "restart"),+ "capabilities": meta.get("capabilities", self.caps), "limits": self.lim}+ if meta.get("switch_error") or self.switch_error:+ out["switch_error"] = meta.get("switch_error") or self.switch_error+ write_json(os.path.join(REC, "summary.json"), out)+ event("seal", violations=len(viol))+++def seal_cmd(wait):+ open(os.path.join(REC, "seal.request"), "a").close()+ path = os.path.join(REC, "summary.json")+ t_end = now() + wait+ while now() < t_end and not os.path.exists(path):+ time.sleep(0.5)+ s = rcb_limits.read_json(path)+ print(json.dumps({k: (s or {}).get(k) for k in ("sealed", "enforce", "n_samples", "peaks", "violations", "killed")}))+ return 0+++def main(argv):+ if argv[:1] == ["seal"]:+ wait = float(argv[argv.index("--wait") + 1]) if "--wait" in argv else 90.0+ return seal_cmd(wait)+ if argv[:1] in (["run"], []):+ no_dump()+ Monitor().run()+ return 0+ print(__doc__)+ return 2+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.pynew file mode 100644index 0000000000..a979bcdaff--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.py@@ -0,0 +1,457 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/selftest.pynew file mode 100644index 0000000000..89d553743f--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/environment/rcb_monitor/selftest.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""What the resource monitor can measure where it runs (capabilities(), written into its record), and a self-test of+the shared violation rule and the verifier step (no containers needed; ci_checks/check-monitor.py runs it):++ python3 scripts/rcb_monitor/selftest.py+"""+import json+import os+import sys+import tempfile++HERE = os.path.dirname(os.path.abspath(__file__))+++def _rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def capabilities():+ """Facts the verifier and the results footnotes need: does the monitor see the host's processes (pid: host), the+ host's cgroup tree (cgroup: host; per-container memory and OOM counts), """+ c = {}+ try:+ pids = [d for d in os.listdir("/proc") if d.isdigit()]+ except OSError:+ pids = []+ try:+ c["pid_host"] = int(len(pids) > 1 and open("/proc/1/comm").read().strip() != open("/proc/self/comm").read().strip())+ except OSError:+ c["pid_host"] = 0+ own = ""+ try:+ own = [ln[3:].strip() for ln in open("/proc/self/cgroup") if ln.startswith("0::")][0]+ except (OSError, IndexError):+ pass+ c["cgroup_v2"] = int(os.path.exists("/sys/fs/cgroup/cgroup.controllers"))+ c["cgroup_host"] = int(bool(own) and own != "/" and os.path.isdir("/sys/fs/cgroup" + own))+ return c+++# --------------------------------------------------------------------------------------------------- self-test+def _check(cond, msg):+ if not cond:+ raise AssertionError(msg)+++def test_rule():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ tick = 5.0+ over = [(i * tick, 10.0 if 20 <= i < 33 else 1.0) for i in range(60)] # 65 s over the limit+ _check(abs(r.sustained(over, 5, 60, 120, tick) - 160.0) < 0.01, "65 s over: confirmed at 60 s")+ short = [(i * tick, 10.0 if 20 <= i < 31 else 1.0) for i in range(60)] # 55 s+ _check(r.sustained(short, 5, 60, 120, tick) is None, "55 s over: no violation")+ flap = [(i * tick, 10.0 if (i % 2 == 0 and i >= 20) else 1.0) for i in range(80)] # half the time, never 60 s straight+ _check(r.sustained(flap, 5, 60, 120, tick) is not None, "59 s on / 1 s off does not escape: 60 s in any 120 s")+ sparse = [(i * 25.0, 10.0) for i in range(4)] # 25 s gaps count 15 s each+ _check(r.sustained(sparse, 5, 60, 120, tick) is None, "gaps never count against the agent")+ _check(r.sustained(over, 0, 60, 120, tick) is None, "limit 0 = not limited")+ disk = [(0, 1.0), (60, 30.0), (120, 1.0), (180, 30.0), (240, 31.0)]+ _check(r.consecutive(disk, 20) == 240, "disk: two consecutive measurements over")+++def test_verify():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ lim = {"max_gpu_memory_gb": 4.0, "max_memory_gb": 8.0, "max_processes": 100, "max_disk_gb": 10.0,+ "sustain_sec": 60, "window_sec": 120, "tick_sec": 5}+ for enforce, gpu, want in ((1, 6.0, "fail"), (0, 6.0, "observe"), (1, 3.0, "pass")):+ with tempfile.TemporaryDirectory() as d:+ rec, tests, logs = (os.path.join(d, x) for x in ("rec", "tests", "logs"))+ for x in (rec, tests, logs):+ os.makedirs(x)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ with open(os.path.join(rec, "samples.jsonl"), "w") as f:+ for i in range(40):+ f.write(json.dumps({"t": 1000 + 5 * i, "scope": {"gpu_memory_gb": gpu if i > 5 else 0.5,+ "memory_gb": 2.0, "processes": 10,+ "disk_gb": 0.1 if i % 12 == 0 else None}}) + "\n")+ open(os.path.join(rec, "events.jsonl"), "w").close()+ json.dump({"format": r.FORMAT, "sealed": True, "enforce": enforce, "scope_seen": True},+ open(os.path.join(rec, "summary.json"), "w"))+ json.dump({"success": 1, "infra_error": 0}, open(os.path.join(logs, "reward.json"), "w"))+ open(os.path.join(logs, "reward.txt"), "w").write("1\n")+ import shutil+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=rec, RCB_VERIFIER_LOGS=logs)+ import subprocess+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ txt = open(os.path.join(logs, "reward.txt")).read().strip()+ if want == "fail":+ _check(out["success"] == 0 and out["resource_limit_exceeded"] == 1 and out["success_before_limits"] == 1+ and txt == "0" and out["over_gpu_memory_gb"] == 1, f"enforced violation fails: {out}")+ elif want == "observe":+ _check(out["success"] == 1 and out["limits_violation_observed"] == 1 and txt == "1"+ and "resource_limit_exceeded" not in out, f"observe mode only records: {out}")+ else:+ _check(out["success"] == 1 and out["limits_violation_observed"] == 0 and out["resource_monitor_missing"] == 0,+ f"within limits: {out}")+ _check(out["peak_gpu_memory_gb"] == gpu, "peak recorded")+ # no record at all: enforced = infra, observed = flagged only+ for enforce in (1, 0):+ with tempfile.TemporaryDirectory() as d:+ logs, tests = os.path.join(d, "logs"), os.path.join(d, "tests")+ os.makedirs(logs)+ os.makedirs(tests)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ json.dump({"success": 1}, open(os.path.join(logs, "reward.json"), "w"))+ import shutil+ import subprocess+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=os.path.join(d, "none"), RCB_VERIFIER_LOGS=logs,+ RCB_LIMITS_ENFORCE=str(enforce))+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ _check(out["resource_monitor_missing"] == 1 and out.get("infra_error", 0) == enforce,+ f"missing record (enforce={enforce}): {out}")+++def main():+ if sys.argv[1:2] == ["caps"]:+ print(json.dumps(capabilities()))+ return 0+ test_rule()+ test_verify()+ print("rcb_monitor selftest: ok")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/instruction.md b/tasks/ambench-press-button-fahexa-i00-privileged/instruction.mdnew file mode 100644index 0000000000..4405c40947--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/instruction.md@@ -0,0 +1,87 @@+# AM-Bench · Press Button — frozen instance i00++You control a simulated **aerial manipulator**: a fully actuated hexarotor (six tilted rotors, so it can hold any attitude+while hovering) carrying a small arm (four joints: three pitch joints and a roll joint) with a two-finger gripper, in+AM-Bench on Isaac Lab / Isaac Sim 5.1 (PhysX), via Python. **Task:** A wall stands in front of the hovering aerial manipulator, and a push button is mounted flat on the wall's front face, facing the robot: a red circular plunger in a dark-grey circular housing. Press the button, i.e. push its spring-loaded plunger into the housing, along the wall's normal, until it is depressed by at least 4 mm (40 % of its 10 mm travel).++This is a *fixed scene instance*: the scene and the robot start the same way after every reset, and you may reset and+retry as many times as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a+general policy.++## Scene+The ground is the world's z = 0 plane. In front of the robot stands an immovable (kinematic) wall: a slab 0.1 m thick, 2.0 m wide and 2.0 m tall with a concrete-block surface, its front face turned toward the robot. Its distance, its sideways offset and a small tilt (the top leaning toward or away from the robot) vary between instances. On the wall's front face sits a push button: a dark-grey circular housing, 12 mm thick, fixed flush to the wall, and in front of it a red circular plunger, 10 mm thick, whose face stands about 2 cm proud of the wall surface. The plunger is the only moving part: it slides along the wall's normal into the housing (10 mm of travel) and is spring-loaded, returning to its rest position when not pushed. Where the button sits on the central part of the wall varies between instances, and so does its face size (plunger diameter between 6 and 12 cm, housing proportionally 1.2 times wider). Nothing moves by itself. The robot starts hovering level and motionless, facing the wall, with its arm at its zero joint configuration (end effector a little ahead of and above the airframe) and the gripper closed.++Exactly (privileged information, also readable through the tooling): One environment; its origin is the world origin. Robot at every reset: base_link at (0, 0, 1.0) m with orientation (1, 0, 0, 0) wxyz (body +x is the world +x direction), zero velocity; arm_link1_pitch_joint = arm_link2_pitch_joint = arm_link3_pitch_joint = arm_link4_roll_joint = 0 rad; arm_lfinger_joint = arm_rfinger_joint = 0.001 m (their lower limit: gripper closed, gripper_width 0.002 m). By the robot's URDF kinematics this puts ee_link at about (0.227, 0, 1.124) m with identity orientation and the tool-tip point (ee_link origin + 0.18 m along the ee_link x axis) at about (0.407, 0, 1.124) m; the end-effector command is initialised to the current ee_link pose. Wall: kinematic cuboid 0.1 (x) x 2.0 (y) x 2.0 (z) m, nominal centre (2.0, 0.0, 1.0) m and orientation identity (front face the plane x = centre_x - 0.05, normal -x, toward the robot); friction 1.0 static / 1.0 dynamic, restitution 0; visual material NVIDIA Concrete_Block.mdl. At each reset (Isaac Lab mdp.reset_root_state_uniform) the centre becomes (2.0 + dx, 0.0 + dy, 1.0) with dx, dy ~ U(-0.2, 0.2) m independently, and the orientation becomes quat_from_euler_xyz(0, pitch, 0) with pitch ~ U(-0.2, 0.2) rad (a rotation about the world y axis through the wall centre; positive pitch tilts the top of the wall away from the robot, the front normal turning upward). Button: articulation push_button.usd with a fixed root (housing) and self-collisions disabled. At each reset, after the wall, its root is placed at wall_centre + R_wall (-0.05, by, bz) with by, bz ~ U(-0.3, 0.3) m independently (a point on the wall's front face, offset in the wall's own y-z plane) and given the wall's orientation, so the button's local +x is the wall normal pointing into the wall. Housing: cylinder along local x, radius 0.072 s, thickness 0.012 m (local x from -0.012 to 0), mass 0.5 kg, colour (0.1, 0.1, 0.1). Plunger (body 'plunger'; AM-Bench's goal_pos observation is its position): cylinder radius 0.06 s, thickness 0.01 m, authored at local x = -0.015 (its face about 2 cm in front of the wall surface), mass 0.02 kg, colour (0.9, 0.1, 0.1). Button physics material: static friction 0.6, dynamic 0.5, restitution 0.1. Prismatic joint PlungerSlideJoint along the button's local +x (positive = plunger pushed toward the wall), limits [0, 0.01] m, reset to 0 m with zero velocity every episode; Isaac Lab implicit actuator with stiffness 1000 N/m and damping 80 N s/m toward the target 0 m, effort limit 20 N, velocity limit 5 m/s. Scale s (applied to the button's local y and z only: face radius changes, thickness does not) ~ U(0.5, 1.0), drawn once when the environment is created (a prestartup event), not at each reset. Scene default physics material: friction 1.0 / 1.0, restitution 0.++## Success (AM-Bench's own check)+Success when the button's prismatic joint PlungerSlideJoint has position >= 0.004 m (button_pressed_threshold; the joint ranges from 0 m, unpressed, to 0.01 m, fully pressed; positive = plunger pushed into the housing toward the wall). Evaluated after every control step (decimation 1, so after every 1/120 s physics step) on the simulated state; no hold time is required. The episode terminates at the first step where it holds. Otherwise it is truncated by the time limit: episode_length_s = 20 s, i.e. max_episode_length = 2400 control steps; AM-Bench raises the time-out when episode_length_buf >= max_episode_length - 1, i.e. at the 2399th step.+The episode **ends by itself** at the first control step where the check holds (success; rows after it are never+executed), or when the task's episode length of **20 s** runs out (a failure: AM-Bench's time-out ends the episode+at control step 2399). Isaac Lab resets the scene inside the step that ends an episode, so after it `s.state()`,+`s.objects()` and the cameras show the start again; `s.status()` keeps the outcome and the end state's hash.++## Deliverable+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed+open-loop from the same initial state in two fresh processes and scored 1 if the task succeeds in both replays and both+end in the same state, else 0. Also leave the script that produced it at `/app/output/gen.py`. Save a working trajectory+as soon as you have one and overwrite it as you improve it: whatever is in `/app/output/` when the time is up is graded.+The file holds `task` and `actions`, a (T, 8) float array of at most **8,000 rows** (one per control step); anything else+(another shape, NaN, more rows, a file that is not such an npz) scores 0.++## Tooling (already installed; run `python` from any directory)+```python+from rcb_ambench import Session+s = Session(instance="/app/instance.json") # ~2-6 min: launches Isaac Sim, builds the scene, resets to the frozen instance+ # (no cameras, as the grader; Session(..., cameras=True) to look: see below)+s.reset() # back to the frozen instance (the seeded reset; as often as you like)+s.step(row) # one control step (1/120 s): row = 8 values (below); True once the episode is over+s.hold_action() # a row that keeps the current end-effector target and gripper command+s.status() # {'success', 'done', 'end_reason', 'control_steps', 'sim_time_s', 'episode_length_s', 'state_sha', ...}+s.state() # privileged: AM-Bench's own observation of the task (robot, end effector, task objects, goal)+s.objects() # every task object and fixture: pose (xyz + quaternion wxyz), velocities, joint state+s.proprio() # the robot: base and end-effector poses and velocities, gripper width, arm joints, current command+s.actions() # (T, 8) rows executed since the last reset: the trajectory of this episode+s.replay(actions) # reset, run the rows open-loop until the episode ends, return status (+ executed_rows)+s.save_trajectory(actions, "/app/output/trajectory.npz")+s.render_frame("ee_camera") # cameras=True only: RGB uint8 (384, 384, 3) at the end effector, or "base_camera" (on the airframe, looking forward)+s.start_video("/app/output/try.mp4"); ...; s.stop_video() # cameras=True only: film the steps in between (both cameras side by side)+s.env # the Isaac Lab environment itself (AM-Bench's source is in /opt/ambench: read-only reference)+```+The tooling is deliberately thin: the environment's own action, its state and its cameras. Reaching, pressing, pushing,+turning and throwing are yours to build. Isaac Sim runs once per process, and only the first episode of a process is+guaranteed to be bit-identical to a fresh process's: after changes, check your trajectory with the grader's CLI.+**Cameras.** The robot's two onboard cameras exist only in a `Session(..., cameras=True)` (decided once per process). With+them, Isaac renders every step and that makes PhysX's results depend on timing: two runs of the same rows can part after a+few hundred steps. The grader replays without cameras, where a fresh process reproduces a trajectory bit for bit, so use+the cameras to look and check every trajectory with the CLI below.++The grader replays in two fresh processes; each is exactly this CLI (a fresh process, so run it to self-check):+`python /opt/tools/rcb_ambench.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`+(`... film --instance ... --traj ... --video out.mp4` films the rows with the cameras on: an illustration, not a verdict).++## Conventions+- World frame: metres, z up, the ground is the plane z = 0; positions are relative to the environment's origin (the+ tooling and the actions use the same origin); quaternions are **wxyz**.+- Action row (8 values per control step), AM-Bench's absolute end-effector pose action: the target position of the+ end-effector link (x, y, z, m) and its target orientation (qw, qx, qy, qz, in AM-Bench's command frame of the end+ effector: `s.proprio()["command"]` and `hold_action()` give the current target in the same convention), then the gripper+ command (-1 = closed .. +1 = open). Every step, AM-Bench's floating-base inverse kinematics turns the target into an+ airframe pose and arm joint targets, its PID controller turns the airframe pose into the six rotor thrusts, and the arm+ joints track their targets.+- Control and physics run at 120 Hz (one physics step per row). There is no step budget: the time limit (`## Time limit`)+ is your only budget; an episode lasts at most 20 s of simulated time.+- One `Session` per process (Isaac Sim launches once, then the scene builds: ~2-6 min, the upper end on a busy host).+ Physics is PhysX on the **GPU** (about 10-15 control steps per second of wall time). One Isaac process takes up to+ ~13 GiB of memory and ~6.5 GiB of GPU memory: run at most two at once. Do not call `s.close()` before writing every+ output.++## External material+You may install packages you need (pip, apt). Please solve the task yourself: do not look up or download a solution to it, such as this benchmark's own source code, published or reference solutions, recorded demonstrations, or policies trained for it. This is an honour rule; trials are reviewed. The network reaches your model's API and the package registries (PyPI, Debian / Ubuntu archives) only.++## Resource limits+Limits for the whole trial, all its processes together (every simulator you start included): at most **16 GiB of GPU memory**, **28 GiB of memory**, **512 processes** and **20 GiB** of new files under `/app`, `/tmp` and `/root`. GPU memory counts what a process reserves (JAX, for example, reserves most of the card unless told not to). These limits may be enforced (from protocol v1.2 on): when enforcement is on, exceeding one for 60 s within any 2 minutes, or a process killed for lack of memory, ends the trial as a failure (reward 0), whatever the deliverable. A monitor outside your container measures every few seconds; the current values are in `/run/rcb-limits/usage.json`. When enforcement is on and GPU memory goes above 1.5 times its limit, the monitor also kills the process holding the most of it at once, to protect the machine; that alone does not fail the trial. CPU is capped at 8 cores for your container; the cap only slows you down.++## Time limit+You have 3600 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task.++This is wall-clock time from the start of your session; the time a simulator takes to start counts. When it is up you are stopped without warning and only what is in `/app/output/` at that moment is graded, so save a deliverable as soon as you have one and overwrite it whenever you have a better one. Your session started when you received this task: run `date` now, and again before you decide that time is short; work out the time left from those readings, never from a guess. Installing packages is not cheating (`## External material` above).diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/solution/oracle.py b/tasks/ambench-press-button-fahexa-i00-privileged/solution/oracle.pynew file mode 100644index 0000000000..b695ebf3dc--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/solution/oracle.py@@ -0,0 +1,15 @@+"""Oracle (privileged): run the reference rows on the frozen instance with the agent's tooling, stopping at the end of+the episode, and save the rows that ran as /app/output/trajectory.npz."""+import json, os+import numpy as np+from rcb_ambench import Session+HERE = os.path.dirname(os.path.abspath(__file__))+s = Session(instance="/app/instance.json", strict=True)+for row in np.load(os.path.join(HERE, "oracle_actions.npy")).astype(np.float64): # the process's first episode, as the grader's+ if s.step(row):+ break+st = {**s.status(), "executed_rows": s.n_steps}+s.save_trajectory(s.actions(), "/app/output/trajectory.npz", meta={"source": "reference rows"})+print(json.dumps({k: st[k] for k in ("success", "end_reason", "executed_rows", "sim_time_s", "state_sha")}), flush=True)+s.close()+os._exit(0 if st["success"] else 1)diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/solution/oracle_actions.npy b/tasks/ambench-press-button-fahexa-i00-privileged/solution/oracle_actions.npynew file mode 100644index 0000000000..67efe0cd51Binary files /dev/null and b/tasks/ambench-press-button-fahexa-i00-privileged/solution/oracle_actions.npy differdiff --git a/tasks/ambench-press-button-fahexa-i00-privileged/solution/solve.sh b/tasks/ambench-press-button-fahexa-i00-privileged/solution/solve.shnew file mode 100755index 0000000000..365611c270--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/solution/solve.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Oracle: replay the reference rows (solution/oracle_actions.npy: AM-Bench's scripted expert for this task, run on this+# instance and recorded, then 2 s of holding its last command; the expert reads the simulator's true state) through the+# agent's own tooling, and save the trajectory. The rows live in solution/ only (never in the agent image, which has no+# expert).+set -e+mkdir -p /app/output+cp /solution/oracle.py /app/output/gen.py+python /solution/oracle.pydiff --git a/tasks/ambench-press-button-fahexa-i00-privileged/task.toml b/tasks/ambench-press-button-fahexa-i00-privileged/task.tomlnew file mode 100644index 0000000000..af4602e774--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/task.toml@@ -0,0 +1,97 @@+# Generated by scripts/ambench/mk_tasks.py -- edit the template or scripts/ambench/descr/, not this.+schema_version = "1.3"+artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]++[task]+name = "robot-coding-bench/ambench-press-button-fahexa-i00-privileged"+description = "AM-Bench PressButton-Am-FAHexa-Abs-PID-Direct-v0 (a fully actuated hexarotor with a 4-joint arm and a two-finger gripper, Isaac Lab / Isaac Sim 5.1): produce one replayable trajectory of AM-Bench's absolute end-effector pose actions at 120 Hz. Task: A wall stands in front of the hovering aerial manipulator, and a push button is mounted flat on the wall's front face, facing the robot: a red circular plunger in a dark-grey circular housing. Press the button, i.e. push its spring-loaded plunger into the housing, along the wall's normal, until it is depressed by at least 4 mm (40 % of its 10 mm travel). Frozen scene instance: AM-Bench's seeded reset, seed 0; graded by AM-Bench's own success check in two fresh-process replays."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "ambench", "aerial-manipulation", "isaac-lab", "isaac-sim", "hexarotor", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "ambench" # AM-Bench @ 60bf5b7 on Isaac Lab @ f4aa17f / Isaac Sim 5.1 (PhysX on the GPU, RTX rendering)+robot = "ambench-fahexa"+family = "press_button_fahexa"+mode = "privileged"+dynamics = "static" # scene dynamics (docs/PROTOCOL.md §2.14): scripts/task_dynamics.toml+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 2.0++[metadata.resources]+# minimum compute to run this task (docs/PROTOCOL.md §2.9)+min_cpus = 8.0+min_memory_gb = 16.0+min_gpu_memory_gb = 8.0+gpu_required = true+gpu_class = "rtx"+recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"+verifier_min_cpus = 4.0+verifier_min_memory_gb = 16.0+verifier_min_gpu_memory_gb = 8.0+measured = "freezing the instances and three oracle trials (RTX 4090, 2026-10-13/14, docker stats and nvidia-smi every 10 s, rcb_monitor): a camera-free Isaac process (the default Session, the grader's replays) peaks at 2.9 GiB of memory and 3.2 GiB of GPU memory (oracle trials: 2.8 / 3.1); with the two onboard cameras on (Session(cameras=True), the verifier's filmed illustration) 13.2 GiB and 6.4 GiB; 6-10 cores while Isaac starts, about 1.5 after; the verifier runs one process at a time. The minimums cover one camera-on process"++[metadata.resources.limits]+# agent-phase limits in GiB (docs/PROTOCOL.md §2.10); scope: trial = every container, agent = the agent's container;+# enforced from protocol v1.2 when RCB_LIMITS_ENFORCE=1 (a violation fails the trial), otherwise recorded only+scope = "trial"+max_gpu_memory_gb = 16.0+max_memory_gb = 28.0+max_processes = 512+max_disk_gb = 20.0+disk_paths = ["/app", "/tmp", "/root"]+disk_exclude = []+sustain_sec = 60.0+window_sec = 120.0+trial_max_gpu_memory_gb = 16.0+trial_max_memory_gb = 28.0+measured = "a camera-on Isaac process peaks at 13.2 GiB of memory and 6.4 GiB of GPU memory, a camera-free one at 2.9 / 3.2 (the rule's measurement); the agent may run two processes at once (a Session and the replay CLI): at most 26.4 GiB, 12.8 GiB -> memory 28 GiB (the container's cap 34 GiB: 34 / 1.2 >= 28), GPU 16 GiB (at least 16 for Isaac Sim); processes 512 and disk 20 GiB: design defaults, not yet measured"++[metadata.resources.caps]+# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)+main = { cpus = 8.0, memory_gb = 34.0, pids = 16384 }++[metadata.seeds]+# the instances this task may run from (docs/PROTOCOL.md §2.13): the default, the ones a runner may draw+# from (a list, { from = A, to = B } or "any"), and the ones the reference solution under solution/ is for+default = 0+allowed = [0]+oracle = [0]++[verifier]+timeout_sec = 9000.0 # tests/grade.py's limits for the longest episode (3120 rows: 1500 s + 3120 / 4 = 2280 s per+ # process): two fresh-process replays (no cameras), one rerun of a replay that died early,+ # and the filmed illustration (cameras on; its time-out only costs the video); measured:+ # 1.5-6 min of Isaac start, the verifier's first one compiling its shaders, + 9-12 control+ # steps/s+environment_mode = "separate" # verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then+network_mode = "no-network" # Isaac Sim starts and renders offline: every asset is in the image (images/ambench/web_assets.txt)++# Resource limits (docs/PROTOCOL.md §2.10): seal the monitor's record first, before any other sidecar ends the episode.+[[verifier.collect]]+service = "rcb_monitor"+command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90"+timeout_sec = 120++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 8+memory_mb = 24576++[agent]+timeout_sec = 3600.0 # the agent's cutoff: scripts/task_cutoffs.toml, the one table (written by normalize, PROTOCOL §2.12)+# AM-Bench's scripted experts and its datasets are public upstream, so the agent reaches the model APIs and the package+# registries, nothing else (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com", "pypi.org", "files.pythonhosted.org", "deb.debian.org", "security.debian.org", "archive.ubuntu.com", "security.ubuntu.com", "snapshot.ubuntu.com"]++[environment]+build_timeout_sec = 3600.0+cpus = 8+memory_mb = 34816++[verifier.env]+RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/Dockerfile b/tasks/ambench-press-button-fahexa-i00-privileged/tests/Dockerfilenew file mode 100644index 0000000000..32e315793a--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/Dockerfile@@ -0,0 +1,11 @@+# Separate verifier sandbox (PROTOCOL §4): the same simulator image with the verifier's own copies of the tooling and the+# frozen instance baked in. Nothing the agent did in its container reaches this one -- Harbor uploads only the declared+# artifacts (/app/output/), so a patched success check or a swapped interpreter in the agent container cannot influence+# the verdict.+FROM ghcr.io/mll-lab-nu/eai-ambench:0.1.0+COPY grade.py instance.json rcb_ambench.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /tests+# resource limits: the verifier step and its copy of the limits (docs/PROTOCOL.md §2.10) # rcb-monitor+COPY rcb_limits.py rcb_limits.json /tests/diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/docker-compose.yaml b/tasks/ambench-press-button-fahexa-i00-privileged/tests/docker-compose.yamlnew file mode 100644index 0000000000..eaf78d197a--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/docker-compose.yaml@@ -0,0 +1,16 @@+# The verifier replays in Isaac Sim, which needs the GPU. Its Kit cache is a TRUSTED volume: Isaac keeps generated+# Python there that Kit imports at startup, so a cache the agent could write must never reach the grader.+services:+ main:+ shm_size: "8gb"+ volumes:+ - rcb_ambench_cache_trusted:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+volumes:+ rcb_ambench_cache_trusted:diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/grade.py b/tasks/ambench-press-button-fahexa-i00-privileged/tests/grade.pynew file mode 100644index 0000000000..580b28b5aa--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/grade.py@@ -0,0 +1,177 @@+"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2++Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a+human-viewable video /logs/verifier/replay.mp4 (the robot's two onboard cameras) plus replay.last.png, filmed AFTER the+verdict by a third process (`rcb_ambench.py film`) with the cameras on: camera rendering makes the physics timing-dependent,+so the verdict replays run without cameras and the video is an illustration that never enters the reward.+Replays `--repeat` times, each in its own FRESH process (`rcb_ambench.py replay`, no cameras), so fresh process == fresh+process is the determinism check. Success requires every replay to complete the task (AM-Bench's own `_get_success`) AND all+final-state hashes to agree, so a lucky non-deterministic run cannot pass. The frozen scene rebuilt here from+tests/instance.json must also match the recorded one (`instance_ok`: the exact state hash of the seeded reset).++Whose failure a 0 is (every path writes a reward; `deterministic`, `grader_error` and `infra_error` are always present):+- the agent's: no file (`missing_trajectory`), another task's trajectory (`wrong_task`), a file that is not a+ trajectory (`bad_trajectory`: not an npz, no `task` / `actions` entry, pickled or object arrays, the wrong shape, NaN/inf,+ more than MAX_STEPS rows), or a replay that does not complete the task or is not deterministic;+- the verifier's (`grader_error` = 1, with `infra_error` = 1: no verdict on the agent): a replay process that ends+ without a result (Isaac died) or runs out of its time limit (`replay_timed_out`), the rebuilt frozen scene not matching+ the recorded instance (`instance_ok` = 0: the host, not the trajectory), or any other error in this script.+"""+from __future__ import annotations+import argparse, json, os, subprocess, sys, time, traceback+import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+# Wall-clock limit of ONE replay process, scaled with the rows that can run (time limits only; the verdict rules do not+# depend on them). The grader accepts up to MAX_STEPS rows, but the episode ends at the task's own episode length (10-26 s+# here: at most 3119 control steps), so later rows never run. Measured on an RTX 4090 host: Isaac start + scene build+# 1.5-6 min (the upper end with other Isaac jobs on the GPU; the verifier's first start also compiles the shaders into its+# fresh Kit cache), then about 12 control steps/s (the onboard cameras render every step). The allowance is REPLAY_STARTUP_S for the start plus the runnable rows at REPLAY_MIN_RATE control steps/s+# (the same for the filming process, whose time-out only ends the video), never below REPLAY_FLOOR_S; task.toml's+# [verifier] timeout_sec fits the three processes of the longest episode, so a replay that is too slow ends here with a+# written reward (`replay_timed_out`), never with Harbor killing the verifier.+REPLAY_FLOOR_S, REPLAY_STARTUP_S, REPLAY_MIN_RATE = 1800.0, 1500.0, 4.0+++def replay_timeout(n_steps: int) -> float:+ return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_steps / REPLAY_MIN_RATE)+++def load_trajectory(path: str, family: str, action_dim: int, max_steps: int):+ """(actions, None), or (None, reward fields) when the file is not a gradable trajectory of this task. Everything+ here is the agent's deliverable: a file that cannot be read is the agent's 0 (`bad_trajectory`), not a grader error."""+ try:+ d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...+ task = str(d["task"]) # no `task` entry: KeyError; an object array: ValueError+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable trajectory: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if task != family:+ return None, {"wrong_task": 1}+ try:+ acts = np.asarray(d["actions"], dtype=np.float32)+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable actions: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if acts.ndim != 2 or acts.shape[1] != action_dim or acts.shape[0] > max_steps or not np.all(np.isfinite(acts)):+ return None, {"bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0}+ return acts, None+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)+ ap.add_argument("--no-video", action="store_true"); ap.add_argument("--video-fps", type=int, default=30)+ a = ap.parse_args()+ # Agent interaction cost from the tooling's append-only log (whole debugging history, not just the deliverable).+ # The log lives in the agent's container, so these fields are SELF-REPORTED cost accounting, not evidence+ # (agent_cost_self_reported = 1); the parser must survive any content the agent may have written there.+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ try:+ with open("/app/output/rcb_session_log.jsonl") as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000: break+ try:+ e = json.loads(line); ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start": cost["agent_sessions"] += 1+ elif ev == "reset": cost["agent_resets"] += 1+ elif ev == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ elif ev == "record": cost["agent_records"] += 1+ elif ev == "replay": cost["agent_replays"] += 1+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict+ continue+ except Exception: # noqa: BLE001+ pass+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions must not be counted+ ZERO = {"success": 0, "deterministic": 0, "grader_error": 0, "infra_error": 0} # an early exit: the agent's 0+ ERR = {"success": 0, "deterministic": 0, "grader_error": 1, "infra_error": 1} # no verdict on the agent+ if not os.path.isfile(a.traj):+ write(False, {**ZERO, "missing_trajectory": 1, **cost}); return 0+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling+ from rcb_ambench import MAX_STEPS, ACTION_DIM+ inst = json.load(open(a.instance)); env_id = inst["env_id"]+ acts, bad = load_trajectory(a.traj, env_id, ACTION_DIM, MAX_STEPS)+ if bad is not None:+ write(False, {**ZERO, **bad, **cost}); return 0+ tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_ambench.py")+ runnable = min(int(acts.shape[0]), int(round(float(inst["episode_length_s"]) * int(inst["control_hz"]))))+ t0 = time.time(); runs = []+ attempts = []+ for i in range(a.repeat):+ limit = replay_timeout(runnable)+ for attempt in (1, 2): # a process that died without a result (Isaac) is run once more+ cmd = [sys.executable, tool, "replay", "--instance", a.instance, "--traj", a.traj]+ try:+ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})+ stdout, run = p.stdout, {"error": f"replay process rc={p.returncode}"}+ except subprocess.TimeoutExpired as exc:+ print(f"[grade] replay {i + 1} exceeded its {limit:.0f} s limit ({len(acts)} rows)", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_timed_out": 1, "replay_timeout_s": round(limit, 1), "n_actions": int(len(acts)),+ "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ for line in stdout.splitlines(): # the last JSON object the CLI printed (Isaac writes to stdout too)+ if line.startswith("{"):+ try:+ v = json.loads(line)+ except ValueError:+ continue+ if isinstance(v, dict): run = v+ print(f"[grade] replay {i + 1}: {json.dumps(run)[:800]}", file=sys.stderr, flush=True)+ attempts.append(attempt)+ if "replays" in run or attempt == 2:+ break+ print(f"[grade] replay {i + 1} gave no result ({run.get('error')}): running it once more", file=sys.stderr, flush=True)+ runs.append(run)+ outs = [(r.get("replays") or [{}])[0] for r in runs]+ if any("error" in r or not o for r, o in zip(runs, outs)):+ print(f"[grade] a replay process gave no result: {[r.get('error') for r in runs]}", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_failed": 1, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ replay_wall = round(time.time() - t0, 1)+ all_success = all(o.get("success") for o in outs)+ deterministic = len({o.get("state_sha") for o in outs}) == 1+ instance_ok = all(bool(r.get("instance_matches")) for r in runs)+ ok = all_success and deterministic and instance_ok+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "replays": len(outs),+ "sim_steps": int(outs[0].get("control_steps") or 0), "sim_time_s": float(outs[0].get("sim_time_s") or 0.0),+ "timed_out": int(outs[-1].get("end_reason") == "timeout"),+ "replay_wall_s": replay_wall, "replay_timeout_s": round(limit, 1),+ # the rebuilt frozen scene is not the recorded one: this host, not the trajectory (no verdict on the agent)+ "grader_error": int(not instance_ok), "infra_error": int(not instance_ok),+ "replay_retries": int(sum(x - 1 for x in attempts)), **cost}+ write(ok, out) # the verdict is written before the illustration is filmed+ film = {}+ if not a.no_video: # an illustration after the verdict: never part of the reward+ try:+ p = subprocess.run([sys.executable, tool, "film", "--instance", a.instance, "--traj", a.traj, "--video",+ os.path.join(LOG_DIR, "replay.mp4"), "--fps", str(a.video_fps)], stdout=subprocess.PIPE,+ stderr=sys.stderr, text=True, timeout=replay_timeout(runnable), env={**os.environ, "RCB_SESSION_LOG": ""})+ for line in p.stdout.splitlines():+ if line.startswith("{"):+ try:+ film = json.loads(line).get("film") or {}+ except (ValueError, AttributeError):+ pass+ except Exception as exc: # noqa: BLE001 — a time-out or a crash only costs the video+ print(f"[grade] filming failed: {exc!r}"[:300], file=sys.stderr, flush=True)+ out.update(video_rendered=int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))),+ video_episode_success=int(bool(film.get("success"))))+ write(ok, out)+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {**ERR, **cost})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/instance.json b/tasks/ambench-press-button-fahexa-i00-privileged/tests/instance.jsonnew file mode 100644index 0000000000..f10d0c326a--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "PressButton-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "PressButton",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 20.0,+ "initial_sha": "c125ec8a4fdd266248f2224493e8e50fd06b6648f7a21ca8568d8dd84267acd8"+}diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_ambench.py b/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_ambench.pynew file mode 100644index 0000000000..623d3522c8--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_ambench.py@@ -0,0 +1,451 @@+"""+rcb_ambench.py — task-local tooling for AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0: aerial manipulation on+Isaac Lab / Isaac Sim 5.1): frozen task instance, privileged state, action recording, fresh-process replay. Same shape as+the other benchmarks' rcb_<bench>.py.++Concepts+--------+instance : one AM-Bench environment (a task with one robot and controller profile, e.g.+ PressButton-Am-FAHexa-Abs-PID-Direct-v0) and the seed of its reset (instance.json). AM-Bench draws the task's+ variation (where the button, the slider, the valve or the ball is) from the seeded reset; `initial_sha` is the+ hash of the start it builds, which every replay checks (`instance_matches`).+trajectory : the (T, 8) actions handed to the environment, one row per control step (120 Hz: one physics step of 1/120 s):+ the absolute end-effector target, position x y z (m, world frame, relative to the environment's origin),+ orientation as a unit quaternion w x y z, and the gripper command (-1 = closed .. +1 = open). AM-Bench's own+ low-level controller (the profile's PID) and floating-base inverse kinematics turn it into rotor thrusts and arm+ joint targets inside every step. Physics is PhysX on the GPU: a fresh process replays the same rows to the+ same state (the first episode of a process; later resets in the same process need not be bit-identical)+ WITHOUT the onboard cameras. With them (`Session(cameras=True)`), the per-step rendering makes PhysX's results+ depend on timing (measured: two fresh replays of the same rows part after a few hundred steps), so the+ grader, the reference recordings and a default Session run without them; cameras are for looking only.+success : AM-Bench's own `_get_success` of the task (its `terminated` signal); the episode ends at the first control step+ where it holds, or at the task's episode length (a time-out, not a success). Rows after the end never run.+ Isaac Lab resets the scene inside the step that ends an episode; the tooling keeps the end state's hash+ (taken just before that reset) as the episode's `state_sha`.+ RotateValve: the valve's `base_to_shaft` joint has no limits, and PhysX reports an articulation's unlimited+ revolute joint wrapped into [-pi, pi] (omni.physx 107.3, Isaac Sim 5.1), so AM-Bench's check `joint_pos >=+ 17/18 pi` would also pass a counter-clockwise turn of 190 degrees. The tooling gives that task's+ `_get_success` the unwrapped angle instead: the sum of the joint's per-step changes since the reset (one+ physics step moves it at most 5 rad/s / 120 Hz, far less than pi), so only the clockwise turn the+ instruction asks for counts. Physics, states and hashes are unchanged; the episode just does not end on a+ wrapped reading.++CLI+---+ python rcb_ambench.py replay --instance instance.json --traj traj.npz # one fresh-process replay (the grader's, no cameras)+ python rcb_ambench.py film --instance instance.json --traj traj.npz --video replay.mp4 # the same rows with the cameras on,+ filmed: an illustration only (camera rendering changes the numerics; never a verdict)+ python rcb_ambench.py make-instance --env-id <id> --seed 0 --out instance.json+ python rcb_ambench.py run-actions --instance instance.json --actions actions.npy --out traj.npz+"""+from __future__ import annotations++import os+for _k, _v in (("OMNI_KIT_ACCEPT_EULA", "YES"), ("ACCEPT_EULA", "Y"), ("OMNI_KIT_ALLOW_ROOT", "1"), ("PYTHONUNBUFFERED", "1"),+ ("JAX_PLATFORMS", "cpu")):+ os.environ.setdefault(_k, _v)++import argparse+import hashlib+import json+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++ACTION_DIM = 8+CONTROL_HZ = 120+MAX_STEPS = 8000 # a technical cap above every task's episode length (at most 60 s = 7200 steps)+ASSET_ROOT = "/opt/isaac-assets/Assets/Isaac/5.1" # baked web assets (images/ambench/web_assets.txt)+CAMERAS = ("ee_camera", "base_camera") # the robot profile's onboard cameras (384 x 384 RGB), only with Session(cameras=True)+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")+_APP = None+_APP_CAMERAS = False+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG) or ".", exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ev": ev, "t": round(time.time(), 3), "pid": os.getpid(), **kw}) + "\n")+ except OSError:+ pass+++def _launch_app(cameras: bool = False):+ """Isaac Sim, headless, the asset root pointed at the baked copies (no network needed); rendering only with cameras.+ Once per process: the first Session decides."""+ global _APP, _APP_CAMERAS+ if _APP is not None and cameras != _APP_CAMERAS:+ raise RuntimeError(f"this process launched Isaac Sim with cameras={_APP_CAMERAS}: one Session (one setting) per process")+ if _APP is None:+ _APP_CAMERAS = cameras+ from isaaclab.app import AppLauncher+ ns = argparse.Namespace()+ p = argparse.ArgumentParser(); AppLauncher.add_app_launcher_args(p)+ ns = p.parse_args([])+ ns.headless = True; ns.enable_cameras = bool(cameras); ns.device = "cuda:0"+ ns.kit_args = f"--/persistent/isaac/asset_root/cloud={ASSET_ROOT}"+ _APP = AppLauncher(ns).app+ return _APP+++def load_instance(instance) -> dict:+ return instance if isinstance(instance, dict) else json.loads(Path(instance).read_text())+++def _np(x) -> np.ndarray:+ return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)+++class Session:+ """One AM-Bench environment of one frozen instance. One per process (Isaac Sim runs once per process)."""++ def __init__(self, instance="/app/instance.json", *, strict: bool = False, cameras: bool = False):+ _launch_app(cameras)+ self.cameras = bool(cameras)+ import gymnasium as gym+ import torch+ import ambench.tasks # noqa: F401 (registers the environments)+ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg+ self.torch = torch+ self.instance = load_instance(instance)+ I = self.instance+ self.env_id, self.seed = I["env_id"], int(I["seed"])+ cfg = parse_env_cfg(self.env_id, device="cuda:0", num_envs=1)+ cfg.seed = self.seed+ if not self.cameras: # the robot profile's onboard cameras (and any scene camera) are not built: no rendering+ cfg.robot_profile.ee_camera = None; cfg.robot_profile.base_camera = None; cfg.scene_camera_cfg = None+ self.env = gym.make(self.env_id, cfg=cfg).unwrapped+ # Isaac Lab resets an environment whose episode ended INSIDE that step (DirectRLEnv.step -> _reset_idx), so after the+ # last step the scene is already the next episode's start: keep the end state's hash, taken just before that reset+ self._in_step = False; self.end_sha = None+ _reset_idx = self.env._reset_idx++ def _keep_end_state(env_ids, _reset_idx=_reset_idx):+ if self._in_step:+ self.end_sha = self.state_sha()+ return _reset_idx(env_ids)+ self.env._reset_idx = _keep_end_state+ self._valve = None+ if self.env_id.startswith("RotateValve-"):+ self._unwrap_valve_angle()+ self.n_resets = 0; self.n_steps_total = 0; self.n_clipped = 0+ self._video = None+ self.reset()+ self.initial_sha = self.state_sha()+ want = I.get("initial_sha")+ self.instance_matches = want is None or want == self.initial_sha+ if strict and not self.instance_matches:+ raise RuntimeError(f"the rebuilt scene differs from the frozen instance: {self.initial_sha} != {want}")+ _slog("session_start", env_id=self.env_id, instance_matches=self.instance_matches, cameras=self.cameras)++ # ------------------------------------------------------------------ episode+ def reset(self) -> None:+ """Back to the frozen instance (the seeded reset). Only the first episode of a process is guaranteed bit-identical+ to a fresh process's: check a trajectory with the `replay` CLI."""+ with self.torch.inference_mode(): # as step(): after a step Isaac Lab's buffers are inference tensors+ self.obs, _ = self.env.reset(seed=self.seed)+ self.end_sha = None+ if self._valve is not None:+ self._valve.update(prev=None, angle=None) # the joint is back at 0 rad: count from here+ self.rows: list[np.ndarray] = []+ self.done = False; self.succeeded = False; self.timed_out = False+ self.n_resets += 1+ if self.n_resets > 1:+ _slog("reset", env_id=self.env_id)++ def _unwrap_valve_angle(self) -> None:+ """RotateValve's success on the valve's unwrapped angle (see the module docstring): AM-Bench's `_get_success`, with+ the joint position PhysX reports in [-pi, pi] replaced by the sum of its per-step changes since the reset."""+ env, torch, v = self.env, self.torch, {"prev": None, "angle": None}+ self._valve = v+ two_pi = 2.0 * float(np.pi)++ def _get_success():+ q = env.valve_object.data.joint_pos[:, env.valve_joint_idx].clone()+ if v["prev"] is None: # the first step after a reset, from 0 rad (|q| < 0.05 rad here)+ angle = q+ else:+ angle = v["angle"] + torch.remainder(q - v["prev"] + np.pi, two_pi) - np.pi+ v.update(prev=q, angle=angle)+ target = env.cfg.valve_target_angle+ rotated = angle >= target+ return rotated, {"valve_engaged": angle >= env.cfg.valve_engagement_ratio * target, "valve_rotated": rotated}+ env._get_success = _get_success++ def valve_angle(self) -> float | None:+ """RotateValve: the valve's unwrapped angle in rad since the reset (positive = clockwise from the robot's side),+ what the success check reads; None in other tasks or before the first step."""+ if self._valve is None or self._valve["angle"] is None:+ return None+ return float(_np(self._valve["angle"]).reshape(-1)[0])++ @property+ def n_steps(self) -> int:+ return len(self.rows)++ def clip(self, row) -> tuple[np.ndarray, int]:+ a = np.asarray(row, dtype=np.float64).reshape(-1).copy()+ if a.size != ACTION_DIM or not np.all(np.isfinite(a)):+ raise ValueError(f"an action row has {ACTION_DIM} finite values (x y z qw qx qy qz gripper), got {a.size}")+ n = 0+ g = float(np.clip(a[7], -1.0, 1.0)); n += int(g != a[7]); a[7] = g+ if float(np.linalg.norm(a[3:7])) < 1e-9: # passed on as it is (AM-Bench's controller takes the quaternion it gets)+ raise ValueError("the action's quaternion has zero length")+ return a, n++ def step(self, row) -> bool:+ """One control step (1/120 s). Returns True when the episode is over; a step after that executes nothing."""+ if self.done:+ return True+ a, n = self.clip(row)+ self.n_clipped += n+ t = self.torch.as_tensor(a, dtype=self.torch.float32, device=self.env.device).reshape(1, ACTION_DIM)+ self._in_step = True+ try:+ with self.torch.inference_mode():+ self.obs, _, term, trunc, _ = self.env.step(t)+ finally:+ self._in_step = False+ self.rows.append(a)+ self.n_steps_total += 1+ self.succeeded = bool(_np(term).reshape(-1)[0])+ self.timed_out = bool(_np(trunc).reshape(-1)[0]) and not self.succeeded+ self.done = self.succeeded or self.timed_out or self.n_steps >= MAX_STEPS+ if self._video is not None:+ self._video_add()+ return self.done++ def success(self) -> bool:+ return self.succeeded++ def end_reason(self) -> str | None:+ if self.succeeded:+ return "success"+ if self.timed_out:+ return "timeout"+ return "step_cap" if self.done else None++ def hold_action(self) -> np.ndarray:+ """A row that keeps the current end-effector target and gripper command."""+ cp = self.env.control_pipeline+ pos = _np(cp.ee_cmd_pos_w[0] - self.env.scene.env_origins[0]).astype(np.float64)+ quat = _np(cp.ee_cmd_quat_w[0]).astype(np.float64)+ g = self.rows[-1][7] if self.rows else 1.0+ return np.r_[pos, quat, g]++ def status(self) -> dict[str, Any]:+ # state_sha: the episode's end state once it is over (taken before Isaac Lab's reset), else the current state+ return {"success": self.succeeded, "done": self.done, "end_reason": self.end_reason(), "control_steps": self.n_steps,+ "sim_time_s": round(self.n_steps / CONTROL_HZ, 4), "episode_length_s": float(self.env.cfg.episode_length_s),+ "resets": self.n_resets, "state_sha": self.end_sha if (self.done and self.end_sha) else self.state_sha()}++ def actions(self) -> np.ndarray:+ return np.asarray(self.rows, dtype=np.float64).reshape(-1, ACTION_DIM)++ def record_start(self) -> None:+ self.reset()++ def record_stop(self) -> np.ndarray:+ return self.actions()++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ self.reset()+ for row in A:+ if self.step(row):+ break+ _slog("replay", env_id=self.env_id, rows=int(len(A)), executed=self.n_steps)+ return {**self.status(), "executed_rows": self.n_steps}++ def save_trajectory(self, actions, path="/app/output/trajectory.npz", meta: dict | None = None) -> None:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, task=np.array(self.env_id), actions=A, meta=np.array(json.dumps(meta or {})))++ # ------------------------------------------------------------------ state (privileged)+ def state_sha(self) -> str:+ """sha256 over every articulation's and rigid object's root state, joint positions and velocities."""+ m = hashlib.sha256()+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name in sorted(group):+ d = group[name].data+ for t in (d.root_state_w, getattr(d, "joint_pos", None), getattr(d, "joint_vel", None)):+ if t is not None:+ m.update(name.encode()); m.update(_np(t).tobytes())+ return m.hexdigest()++ def state(self) -> dict[str, Any]:+ """Privileged observation of the task (AM-Bench's own `policy` observation: robot, end effector, task objects and+ goal positions, relative to the environment's origin)."""+ obs = self.obs["policy"][0] if isinstance(self.obs.get("policy"), list) else self.obs.get("policy")+ return {k: _np(v).reshape(-1).tolist() for k, v in (obs.items() if isinstance(obs, dict) else [])}++ def objects(self) -> dict[str, dict]:+ """Every articulation (but the robot) and rigid object of the scene: root pose (wxyz) and velocities, joint state."""+ out, o = {}, _np(self.env.scene.env_origins[0])+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name, obj in group.items():+ if name == "robot":+ continue+ rs = _np(obj.data.root_state_w[0])+ ent = {"position": (rs[:3] - o).tolist(), "orientation_wxyz": rs[3:7].tolist(), "velocity": rs[7:10].tolist(),+ "angular_velocity": rs[10:13].tolist()}+ if getattr(obj.data, "joint_pos", None) is not None:+ ent["joint_pos"] = _np(obj.data.joint_pos[0]).tolist(); ent["joint_names"] = list(obj.joint_names)+ out[name] = ent+ return out++ def proprio(self) -> dict[str, Any]:+ """The robot's own state: base and end-effector poses (world, relative to the env origin; wxyz) and velocities, the+ gripper opening and the arm joints, the current end-effector command."""+ e = self.env; o = _np(e.scene.env_origins[0])+ base = _np(e.robot.data.body_link_state_w[0, e.base_link_idx]); ee = _np(e.robot.data.body_link_state_w[0, e.ee_link_idx])+ jp = _np(e.robot.data.joint_pos[0]); jv = _np(e.robot.data.joint_vel[0])+ return {"base_pose": np.r_[base[:3] - o, base[3:7]].tolist(), "base_vel": base[7:13].tolist(),+ "ee_pose": np.r_[ee[:3] - o, ee[3:7]].tolist(), "ee_vel": ee[7:13].tolist(),+ "gripper_width": float(np.sum(jp[e.gripper_joint_ids])),+ "arm_joint_pos": jp[e.arm_joint_ids].tolist(), "arm_joint_vel": jv[e.arm_joint_ids].tolist(),+ "command": self.hold_action().tolist()}++ # ------------------------------------------------------------------ cameras+ def render_frame(self, camera: str = "ee_camera") -> np.ndarray:+ """RGB uint8 (384, 384, 3) of the robot's onboard camera `ee_camera` (at the end effector) or `base_camera` (on the+ airframe, looking forward), as of the last step. Only in a Session(cameras=True): the cameras render every step+ and that makes the physics timing-dependent, so check what you find there with the replay CLI (no cameras)."""+ if not self.cameras:+ raise RuntimeError("no cameras in this Session: start the process with Session(..., cameras=True) to look "+ "(its numerics differ from the grader's camera-free replay; check trajectories with the CLI)")+ cam = getattr(self.env, camera, None)+ if cam is None:+ raise KeyError(f"no camera {camera!r}; cameras: {[c for c in CAMERAS if getattr(self.env, c, None) is not None]}")+ return _np(cam.data.output["rgb"][0])[..., :3].astype(np.uint8)++ def start_video(self, path, fps: int = 30, camera: str = "ee_camera") -> None:+ import imageio.v2 as imageio+ self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),+ "every": max(1, round(CONTROL_HZ / fps)), "camera": camera, "path": str(path)}+ self._video_add(force=True)++ def _video_add(self, force: bool = False) -> None:+ v = self._video+ if force or self.n_steps % v["every"] == 0 or self.done:+ frames = [self.render_frame(c) for c in CAMERAS if getattr(self.env, c, None) is not None]+ v["w"].append_data(np.concatenate(frames, axis=1))++ def stop_video(self):+ v, self._video = self._video, None+ if v:+ v["w"].close()+ return v["path"]++ def close(self) -> None:+ _slog("session_end", env_id=self.env_id, sim_steps=self.n_steps_total, resets=self.n_resets)+ try:+ self.env.close()+ except Exception: # noqa: BLE001+ pass+++def load_trajectory(path, env_id: str) -> np.ndarray:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != env_id:+ raise ValueError(f"trajectory is for {str(d['task'])!r}, not {env_id!r}")+ A = np.asarray(d["actions"], dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != ACTION_DIM or A.shape[0] > MAX_STEPS or not np.all(np.isfinite(A)):+ raise ValueError(f"actions must be a finite (T, {ACTION_DIM}) array with T <= {MAX_STEPS}, got {list(A.shape)}")+ return A+++def _replay_rows(s: "Session", A: np.ndarray) -> dict:+ for row in A: # the process's first episode+ if s.step(row):+ break+ res = s.status()+ return {**{k: res[k] for k in ("success", "state_sha", "end_reason", "control_steps", "sim_time_s")}, "executed_rows": s.n_steps}+++def _cli_replay(a) -> int:+ """The grader's replay: a fresh process, no cameras (bit-reproducible), the process's first episode."""+ t0 = time.time()+ s = Session(a.instance)+ out: dict[str, Any] = {"task": s.env_id, "instance_matches": bool(s.instance_matches), "initial_sha": s.initial_sha}+ try:+ A = load_trajectory(a.traj, s.env_id)+ except Exception as exc: # noqa: BLE001+ out["error"] = f"bad trajectory: {exc!r}"[:300]; print(json.dumps(out), flush=True); return 2+ out["replays"] = [_replay_rows(s, A)]+ out["n_actions"] = int(len(A)); out["replay_wall_s"] = round(time.time() - t0, 2)+ print(json.dumps(out), flush=True)+ s.close()+ return 0+++def _cli_film(a) -> int:+ """An illustration, never a verdict: the rows with the onboard cameras on, filmed (both cameras side by side) plus the+ last end-effector frame. Camera rendering makes the physics timing-dependent, so this episode may end differently."""+ t0 = time.time()+ s = Session(a.instance, cameras=True)+ A = load_trajectory(a.traj, s.env_id)+ s.start_video(a.video, fps=a.fps)+ res = _replay_rows(s, A)+ s.stop_video()+ from PIL import Image+ Image.fromarray(s.render_frame("ee_camera")).save(str(Path(a.video).with_suffix(".last.png")))+ print(json.dumps({"task": s.env_id, "film": res, "video": a.video, "film_wall_s": round(time.time() - t0, 2)}), flush=True)+ s.close()+ return 0+++def _cli_make_instance(a) -> int:+ inst = {"env_id": a.env_id, "seed": int(a.seed)}+ s = Session(inst)+ inst.update({"task": a.env_id.split("-")[0], "action_dim": ACTION_DIM, "control_hz": CONTROL_HZ,+ "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha})+ Path(a.out).write_text(json.dumps(inst, indent=1) + "\n")+ print(json.dumps({"env_id": a.env_id, "initial_sha": s.initial_sha}), flush=True)+ s.close()+ return 0+++def _cli_run_actions(a) -> int:+ s = Session(a.instance, strict=True)+ for row in np.load(a.actions): # the process's first episode (no second reset), as the grader's+ if s.step(row):+ break+ res = {**s.status(), "executed_rows": s.n_steps}+ s.save_trajectory(s.actions(), a.out, meta={"source": "reference rows"})+ print(json.dumps({k: res[k] for k in ("success", "end_reason", "state_sha", "control_steps", "executed_rows", "sim_time_s")}), flush=True)+ s.close()+ return 0+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay"); r.add_argument("--instance", required=True); r.add_argument("--traj", required=True)+ f = sub.add_parser("film"); f.add_argument("--instance", required=True); f.add_argument("--traj", required=True)+ f.add_argument("--video", required=True); f.add_argument("--fps", type=int, default=30)+ m = sub.add_parser("make-instance"); m.add_argument("--env-id", required=True); m.add_argument("--seed", type=int, default=0); m.add_argument("--out", required=True)+ x = sub.add_parser("run-actions"); x.add_argument("--instance", required=True); x.add_argument("--actions", required=True); x.add_argument("--out", required=True)+ a = ap.parse_args(argv)+ global SESSION_LOG+ SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "") # the CLI logs nothing unless asked+ try:+ rc = {"replay": _cli_replay, "film": _cli_film, "make-instance": _cli_make_instance, "run-actions": _cli_run_actions}[a.cmd](a)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error: report it and leave at once+ import traceback+ traceback.print_exc(); rc = 3+ sys.stdout.flush(); sys.stderr.flush()+ os._exit(rc) # Isaac Sim's shutdown can hang or crash after the result line; the result is printed+++if __name__ == "__main__":+ main()diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_limits.json b/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_limits.jsonnew file mode 100644index 0000000000..b276655018--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_limits.json@@ -0,0 +1,33 @@+{+ "caps": {+ "main": {+ "cpus": 8.0,+ "memory_gb": 34.0,+ "pids": 16384+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": true,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 16.0,+ "max_memory_gb": 28.0,+ "max_processes": 512,+ "mode": "privileged",+ "scope": "trial",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "ambench-press-button-fahexa-i00-privileged",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 16.0,+ "trial_max_memory_gb": 28.0,+ "window_sec": 120.0+}diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_limits.py b/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_limits.pynew file mode 100644index 0000000000..a979bcdaff--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/rcb_limits.py@@ -0,0 +1,457 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/ambench-press-button-fahexa-i00-privileged/tests/test.sh b/tasks/ambench-press-button-fahexa-i00-privileged/tests/test.shnew file mode 100755index 0000000000..de3fc8c811--- /dev/null+++ b/tasks/ambench-press-button-fahexa-i00-privileged/tests/test.sh@@ -0,0 +1,11 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, see docs/PROTOCOL.md).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resource limits, after the grader (docs/PROTOCOL.md §2.10)+p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # the agent's files are untrusted input: no link out of /app/output, no FIFO or device (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \+ 2> /logs/verifier/grade.logdiff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/README.md b/tasks/ambench-push-slider-fahexa-i00-privileged/README.mdnew file mode 100644index 0000000000..6e51f36f7f--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/README.md@@ -0,0 +1,65 @@+# ambench-push-slider-fahexa-i00-privileged++| | |+|---|---|+| Benchmark | AM-Bench |+| Mode | privileged |+| Twin | — (privileged only) |+| Simulator / robot | `ambench` / `ambench-fahexa` |+| Family / instance | `push_slider_fahexa` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-ambench:0.1.0` |++## Task+A wall stands in front of the hovering aerial manipulator, with a horizontal slider mounted on its front face: a straight rail about 1 m long and a red knob that slides along it. The knob starts at the rail's left end (as seen from the robot facing the wall) and must be pushed along the rail until it is within 5 cm of the right end of its travel, i.e. at least 0.95 m along its 1 m travel. AM-Bench environment `PushSlider-Am-FAHexa-Abs-PID-Direct-v0` (the fully actuated hexarotor with the 4-joint arm, AM-Bench's PID+controller), its seeded reset with seed 0. The deliverable is one replayable trajectory of AM-Bench's absolute+end-effector pose actions at 120 Hz (`/app/output/trajectory.npz`), graded by AM-Bench's own success check within the+task's episode length of 26 s.++## Difficulty+The knob has to be driven 0.95 m, almost the whole length of the rail, in one direction against joint friction and damping, and the fixture's place on the wall changes per instance. Privileged mode gives the full simulator state, unlimited resets and self-replay; the tooling offers only the+environment's own action, its state and its cameras.++## Reference solution+`solution/oracle_actions.npy` (run by `solution/oracle.py` through the agent's own tooling): AM-Bench's scripted expert+for this task, run on this instance (it reads the simulator's state in closed loop) and recorded, followed by 2 s of+holding its last command (a replay may succeed a step later than the live run; rows after success never run). The image+has no expert (`images/ambench/Dockerfile` removes them), and the agent's network reaches only the+model APIs and the package registries.++## Verification+`tests/grade.py` in a separate sandbox: two replays, each in a fresh process, from the verifier's own copy of the instance+(`tests/instance.json`; the rebuilt start is checked against its hash); pass iff AM-Bench's success check holds in both+and both end in the same state (`deterministic`); the replays run without the onboard cameras (camera rendering makes+GPU PhysX timing-dependent). `/logs/verifier/replay.mp4` (both onboard cameras) is filmed by a third process after the+verdict, an illustration only. Oracle:+success at control step 1353 (11.275 s simulated) in both fresh-process replays, which end in the same+state (hash `01a85d356fead490`). `nop`: no trajectory, reward 0.++## Compute resources+Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]` in `task.toml`). The agent phase counts every container of the trial at once (the agent's, and in standard modes the simulator sidecar); the verifier phase runs after it.++| | Agent phase | Verifier |+|---|---|---|+| CPU cores | 8 | 4 |+| Memory | 16 GB | 16 GB |+| GPU memory | 8 GB | 8 GB |++- GPU: required, an RTX-class NVIDIA GPU (ray-tracing cores, for Isaac Sim / Omniverse RTX rendering); recommended: L40S 48GB / L4 24GB / RTX 4090 24GB.+- Measured: freezing the instances and three oracle trials (RTX 4090, 2026-10-13/14, docker stats and nvidia-smi every 10 s, rcb_monitor): a camera-free Isaac process (the default Session, the grader's replays) peaks at 2.9 GiB of memory and 3.2 GiB of GPU memory (oracle trials: 2.8 / 3.1); with the two onboard cameras on (Session(cameras=True), the verifier's filmed illustration) 13.2 GiB and 6.4 GiB; 6-10 cores while Isaac starts, about 1.5 after; the verifier runs one process at a time. The minimums cover one camera-on process+- Limits in the agent phase (docs/PROTOCOL.md §2.10; `[metadata.resources.limits]`, shown to the agent in `instruction.md`; always measured and reported, and exceeding one fails the trial only when the run sets `RCB_LIMITS_ENFORCE=1`), every container of the trial: 16 GiB GPU memory, 28 GiB memory, 512 processes, 20 GiB of new files under `/app`, `/tmp`, `/root`; 60 s within 120 s. Expected peak of the whole trial: 16 GiB GPU memory, 28 GiB memory. Limits measured: a camera-on Isaac process peaks at 13.2 GiB of memory and 6.4 GiB of GPU memory, a camera-free one at 2.9 / 3.2 (the rule's measurement); the agent may run two processes at once (a Session and the replay CLI): at most 26.4 GiB, 12.8 GiB -> memory 28 GiB (the container's cap 34 GiB: 34 / 1.2 >= 28), GPU 16 GiB (at least 16 for Isaac Sim); processes 512 and disk 20 GiB: design defaults, not yet measured.++## Details+| | |+|---|---|+| Upstream | AM-Bench @ 60bf5b7 (Apache-2.0) on Isaac Lab @ f4aa17f / Isaac Sim 5.1.0; Pyroki @ 2eafc99, acados @ fa0af20 |+| Instance | `PushSlider-Am-FAHexa-Abs-PID-Direct-v0`, seed 0, the start's state hash in `environment/instance.json` (`initial_sha` 9bd26bad8cd1cd81) |+| Actions | 8 per control step (1/120 s): end-effector target x y z (m), quaternion w x y z (command frame), gripper (-1 closed .. +1 open) |+| Physics | PhysX on the GPU (dt 1/120 s, one physics step per action); bit-reproducible in a fresh process without the onboard cameras, which the tooling builds only on request (`Session(cameras=True)`) |+| Image | built locally on every host (`images/ambench/BUILD_ONLY`: it contains Isaac Sim); needs an RTX-class NVIDIA GPU (`environment/docker-compose.yaml`) |+| Budget | the agent's cutoff is the `Agent time budget` row above (`scripts/task_cutoffs.toml`); out of it, every Python process pays ~2-6 min of Isaac Sim launch + scene build |++### Provenance+Generated by `scripts/ambench/mk_tasks.py` from `scripts/ambench/descr/push_slider_fahexa.json` and `scripts/ambench/frozen/push_slider-i00/`+(the expert's rows recorded with `scripts/ambench/freeze.py` in `ghcr.io/mll-lab-nu/eai-ambench:0.1.0`; provenance in `scripts/ambench/instances.json`).diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/Dockerfile b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/Dockerfilenew file mode 100644index 0000000000..9050e5343c--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# Base image = AM-Bench (scrubbed: no scripted experts) + Isaac Lab / Isaac Sim 5.1 + the baked web assets (see+# images/ambench/; BUILD_ONLY). Everything task-specific is copied here; no reference solution is in the image.+FROM ghcr.io/mll-lab-nu/eai-ambench:0.1.0+COPY instance.json /app/instance.json+COPY rcb_ambench.py /opt/tools/rcb_ambench.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/docker-compose.yaml b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/docker-compose.yamlnew file mode 100644index 0000000000..ef66ce03c4--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/docker-compose.yaml@@ -0,0 +1,47 @@+# Isaac Sim needs an RTX-class NVIDIA GPU even headless. Harbor's local docker sandbox rejects [environment].gpus, but+# merging this onto the main service passes the device through. Isaac's shader/extension cache gets a volume for the+# trial, named after the trial's compose project (no fixed name: side-by-side trials must not share it; Harbor's+# teardown, `compose down --volumes`, deletes it): every trial compiles its shaders once (~2 min).+services:+ main:+ pids_limit: 16384 # rcb-monitor+ shm_size: "8gb"+ volumes:+ - rcb_limits:/run/rcb-limits:ro # rcb-monitor+ - rcb_ambench_cache:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+ # >>> rcb_monitor (resource limits monitor, docs/PROTOCOL.md §2.10; generated by scripts/rcb_monitor/inject.py)+ rcb_monitor:+ image: ghcr.io/mll-lab-nu/eai-monitor:0.1.0@sha256:f2c910f53f79c2bfa4a71298b10c78383cae3afc40720ca562cc845b8d20fb0c+ pid: host # sees every container's processes (and NVML's host PIDs); the agent never sees it+ cgroup: host # reads each container's own cgroup (memory, OOM kills, caps)+ network_mode: none+ cap_add: [SYS_PTRACE] # reads /proc of processes running as other users+ cpus: 0.5+ mem_limit: 256m+ pids_limit: 64+ restart: on-failure:3+ working_dir: /var/rcb-monitor+ volumes:+ - ./rcb_monitor:/opt/rcb_monitor:ro+ - rcb_limits:/run/rcb-limits+ environment:+ RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} # 1: stop the agent at a confirmed violation, and fail the trial+ command: ["python3", "/opt/rcb_monitor/monitor.py", "run"]+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+ # <<< rcb_monitor+volumes:+ rcb_limits: # rcb-monitor+ rcb_ambench_cache:diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/instance.json b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/instance.jsonnew file mode 100644index 0000000000..9f8b869b25--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "PushSlider-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "PushSlider",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 26.0,+ "initial_sha": "9bd26bad8cd1cd81a7fcc11043a996206a0550e7e00f2a74253efe1822ced584"+}diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_ambench.py b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_ambench.pynew file mode 100644index 0000000000..623d3522c8--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_ambench.py@@ -0,0 +1,451 @@+"""+rcb_ambench.py — task-local tooling for AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0: aerial manipulation on+Isaac Lab / Isaac Sim 5.1): frozen task instance, privileged state, action recording, fresh-process replay. Same shape as+the other benchmarks' rcb_<bench>.py.++Concepts+--------+instance : one AM-Bench environment (a task with one robot and controller profile, e.g.+ PressButton-Am-FAHexa-Abs-PID-Direct-v0) and the seed of its reset (instance.json). AM-Bench draws the task's+ variation (where the button, the slider, the valve or the ball is) from the seeded reset; `initial_sha` is the+ hash of the start it builds, which every replay checks (`instance_matches`).+trajectory : the (T, 8) actions handed to the environment, one row per control step (120 Hz: one physics step of 1/120 s):+ the absolute end-effector target, position x y z (m, world frame, relative to the environment's origin),+ orientation as a unit quaternion w x y z, and the gripper command (-1 = closed .. +1 = open). AM-Bench's own+ low-level controller (the profile's PID) and floating-base inverse kinematics turn it into rotor thrusts and arm+ joint targets inside every step. Physics is PhysX on the GPU: a fresh process replays the same rows to the+ same state (the first episode of a process; later resets in the same process need not be bit-identical)+ WITHOUT the onboard cameras. With them (`Session(cameras=True)`), the per-step rendering makes PhysX's results+ depend on timing (measured: two fresh replays of the same rows part after a few hundred steps), so the+ grader, the reference recordings and a default Session run without them; cameras are for looking only.+success : AM-Bench's own `_get_success` of the task (its `terminated` signal); the episode ends at the first control step+ where it holds, or at the task's episode length (a time-out, not a success). Rows after the end never run.+ Isaac Lab resets the scene inside the step that ends an episode; the tooling keeps the end state's hash+ (taken just before that reset) as the episode's `state_sha`.+ RotateValve: the valve's `base_to_shaft` joint has no limits, and PhysX reports an articulation's unlimited+ revolute joint wrapped into [-pi, pi] (omni.physx 107.3, Isaac Sim 5.1), so AM-Bench's check `joint_pos >=+ 17/18 pi` would also pass a counter-clockwise turn of 190 degrees. The tooling gives that task's+ `_get_success` the unwrapped angle instead: the sum of the joint's per-step changes since the reset (one+ physics step moves it at most 5 rad/s / 120 Hz, far less than pi), so only the clockwise turn the+ instruction asks for counts. Physics, states and hashes are unchanged; the episode just does not end on a+ wrapped reading.++CLI+---+ python rcb_ambench.py replay --instance instance.json --traj traj.npz # one fresh-process replay (the grader's, no cameras)+ python rcb_ambench.py film --instance instance.json --traj traj.npz --video replay.mp4 # the same rows with the cameras on,+ filmed: an illustration only (camera rendering changes the numerics; never a verdict)+ python rcb_ambench.py make-instance --env-id <id> --seed 0 --out instance.json+ python rcb_ambench.py run-actions --instance instance.json --actions actions.npy --out traj.npz+"""+from __future__ import annotations++import os+for _k, _v in (("OMNI_KIT_ACCEPT_EULA", "YES"), ("ACCEPT_EULA", "Y"), ("OMNI_KIT_ALLOW_ROOT", "1"), ("PYTHONUNBUFFERED", "1"),+ ("JAX_PLATFORMS", "cpu")):+ os.environ.setdefault(_k, _v)++import argparse+import hashlib+import json+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++ACTION_DIM = 8+CONTROL_HZ = 120+MAX_STEPS = 8000 # a technical cap above every task's episode length (at most 60 s = 7200 steps)+ASSET_ROOT = "/opt/isaac-assets/Assets/Isaac/5.1" # baked web assets (images/ambench/web_assets.txt)+CAMERAS = ("ee_camera", "base_camera") # the robot profile's onboard cameras (384 x 384 RGB), only with Session(cameras=True)+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")+_APP = None+_APP_CAMERAS = False+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG) or ".", exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ev": ev, "t": round(time.time(), 3), "pid": os.getpid(), **kw}) + "\n")+ except OSError:+ pass+++def _launch_app(cameras: bool = False):+ """Isaac Sim, headless, the asset root pointed at the baked copies (no network needed); rendering only with cameras.+ Once per process: the first Session decides."""+ global _APP, _APP_CAMERAS+ if _APP is not None and cameras != _APP_CAMERAS:+ raise RuntimeError(f"this process launched Isaac Sim with cameras={_APP_CAMERAS}: one Session (one setting) per process")+ if _APP is None:+ _APP_CAMERAS = cameras+ from isaaclab.app import AppLauncher+ ns = argparse.Namespace()+ p = argparse.ArgumentParser(); AppLauncher.add_app_launcher_args(p)+ ns = p.parse_args([])+ ns.headless = True; ns.enable_cameras = bool(cameras); ns.device = "cuda:0"+ ns.kit_args = f"--/persistent/isaac/asset_root/cloud={ASSET_ROOT}"+ _APP = AppLauncher(ns).app+ return _APP+++def load_instance(instance) -> dict:+ return instance if isinstance(instance, dict) else json.loads(Path(instance).read_text())+++def _np(x) -> np.ndarray:+ return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)+++class Session:+ """One AM-Bench environment of one frozen instance. One per process (Isaac Sim runs once per process)."""++ def __init__(self, instance="/app/instance.json", *, strict: bool = False, cameras: bool = False):+ _launch_app(cameras)+ self.cameras = bool(cameras)+ import gymnasium as gym+ import torch+ import ambench.tasks # noqa: F401 (registers the environments)+ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg+ self.torch = torch+ self.instance = load_instance(instance)+ I = self.instance+ self.env_id, self.seed = I["env_id"], int(I["seed"])+ cfg = parse_env_cfg(self.env_id, device="cuda:0", num_envs=1)+ cfg.seed = self.seed+ if not self.cameras: # the robot profile's onboard cameras (and any scene camera) are not built: no rendering+ cfg.robot_profile.ee_camera = None; cfg.robot_profile.base_camera = None; cfg.scene_camera_cfg = None+ self.env = gym.make(self.env_id, cfg=cfg).unwrapped+ # Isaac Lab resets an environment whose episode ended INSIDE that step (DirectRLEnv.step -> _reset_idx), so after the+ # last step the scene is already the next episode's start: keep the end state's hash, taken just before that reset+ self._in_step = False; self.end_sha = None+ _reset_idx = self.env._reset_idx++ def _keep_end_state(env_ids, _reset_idx=_reset_idx):+ if self._in_step:+ self.end_sha = self.state_sha()+ return _reset_idx(env_ids)+ self.env._reset_idx = _keep_end_state+ self._valve = None+ if self.env_id.startswith("RotateValve-"):+ self._unwrap_valve_angle()+ self.n_resets = 0; self.n_steps_total = 0; self.n_clipped = 0+ self._video = None+ self.reset()+ self.initial_sha = self.state_sha()+ want = I.get("initial_sha")+ self.instance_matches = want is None or want == self.initial_sha+ if strict and not self.instance_matches:+ raise RuntimeError(f"the rebuilt scene differs from the frozen instance: {self.initial_sha} != {want}")+ _slog("session_start", env_id=self.env_id, instance_matches=self.instance_matches, cameras=self.cameras)++ # ------------------------------------------------------------------ episode+ def reset(self) -> None:+ """Back to the frozen instance (the seeded reset). Only the first episode of a process is guaranteed bit-identical+ to a fresh process's: check a trajectory with the `replay` CLI."""+ with self.torch.inference_mode(): # as step(): after a step Isaac Lab's buffers are inference tensors+ self.obs, _ = self.env.reset(seed=self.seed)+ self.end_sha = None+ if self._valve is not None:+ self._valve.update(prev=None, angle=None) # the joint is back at 0 rad: count from here+ self.rows: list[np.ndarray] = []+ self.done = False; self.succeeded = False; self.timed_out = False+ self.n_resets += 1+ if self.n_resets > 1:+ _slog("reset", env_id=self.env_id)++ def _unwrap_valve_angle(self) -> None:+ """RotateValve's success on the valve's unwrapped angle (see the module docstring): AM-Bench's `_get_success`, with+ the joint position PhysX reports in [-pi, pi] replaced by the sum of its per-step changes since the reset."""+ env, torch, v = self.env, self.torch, {"prev": None, "angle": None}+ self._valve = v+ two_pi = 2.0 * float(np.pi)++ def _get_success():+ q = env.valve_object.data.joint_pos[:, env.valve_joint_idx].clone()+ if v["prev"] is None: # the first step after a reset, from 0 rad (|q| < 0.05 rad here)+ angle = q+ else:+ angle = v["angle"] + torch.remainder(q - v["prev"] + np.pi, two_pi) - np.pi+ v.update(prev=q, angle=angle)+ target = env.cfg.valve_target_angle+ rotated = angle >= target+ return rotated, {"valve_engaged": angle >= env.cfg.valve_engagement_ratio * target, "valve_rotated": rotated}+ env._get_success = _get_success++ def valve_angle(self) -> float | None:+ """RotateValve: the valve's unwrapped angle in rad since the reset (positive = clockwise from the robot's side),+ what the success check reads; None in other tasks or before the first step."""+ if self._valve is None or self._valve["angle"] is None:+ return None+ return float(_np(self._valve["angle"]).reshape(-1)[0])++ @property+ def n_steps(self) -> int:+ return len(self.rows)++ def clip(self, row) -> tuple[np.ndarray, int]:+ a = np.asarray(row, dtype=np.float64).reshape(-1).copy()+ if a.size != ACTION_DIM or not np.all(np.isfinite(a)):+ raise ValueError(f"an action row has {ACTION_DIM} finite values (x y z qw qx qy qz gripper), got {a.size}")+ n = 0+ g = float(np.clip(a[7], -1.0, 1.0)); n += int(g != a[7]); a[7] = g+ if float(np.linalg.norm(a[3:7])) < 1e-9: # passed on as it is (AM-Bench's controller takes the quaternion it gets)+ raise ValueError("the action's quaternion has zero length")+ return a, n++ def step(self, row) -> bool:+ """One control step (1/120 s). Returns True when the episode is over; a step after that executes nothing."""+ if self.done:+ return True+ a, n = self.clip(row)+ self.n_clipped += n+ t = self.torch.as_tensor(a, dtype=self.torch.float32, device=self.env.device).reshape(1, ACTION_DIM)+ self._in_step = True+ try:+ with self.torch.inference_mode():+ self.obs, _, term, trunc, _ = self.env.step(t)+ finally:+ self._in_step = False+ self.rows.append(a)+ self.n_steps_total += 1+ self.succeeded = bool(_np(term).reshape(-1)[0])+ self.timed_out = bool(_np(trunc).reshape(-1)[0]) and not self.succeeded+ self.done = self.succeeded or self.timed_out or self.n_steps >= MAX_STEPS+ if self._video is not None:+ self._video_add()+ return self.done++ def success(self) -> bool:+ return self.succeeded++ def end_reason(self) -> str | None:+ if self.succeeded:+ return "success"+ if self.timed_out:+ return "timeout"+ return "step_cap" if self.done else None++ def hold_action(self) -> np.ndarray:+ """A row that keeps the current end-effector target and gripper command."""+ cp = self.env.control_pipeline+ pos = _np(cp.ee_cmd_pos_w[0] - self.env.scene.env_origins[0]).astype(np.float64)+ quat = _np(cp.ee_cmd_quat_w[0]).astype(np.float64)+ g = self.rows[-1][7] if self.rows else 1.0+ return np.r_[pos, quat, g]++ def status(self) -> dict[str, Any]:+ # state_sha: the episode's end state once it is over (taken before Isaac Lab's reset), else the current state+ return {"success": self.succeeded, "done": self.done, "end_reason": self.end_reason(), "control_steps": self.n_steps,+ "sim_time_s": round(self.n_steps / CONTROL_HZ, 4), "episode_length_s": float(self.env.cfg.episode_length_s),+ "resets": self.n_resets, "state_sha": self.end_sha if (self.done and self.end_sha) else self.state_sha()}++ def actions(self) -> np.ndarray:+ return np.asarray(self.rows, dtype=np.float64).reshape(-1, ACTION_DIM)++ def record_start(self) -> None:+ self.reset()++ def record_stop(self) -> np.ndarray:+ return self.actions()++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ self.reset()+ for row in A:+ if self.step(row):+ break+ _slog("replay", env_id=self.env_id, rows=int(len(A)), executed=self.n_steps)+ return {**self.status(), "executed_rows": self.n_steps}++ def save_trajectory(self, actions, path="/app/output/trajectory.npz", meta: dict | None = None) -> None:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, task=np.array(self.env_id), actions=A, meta=np.array(json.dumps(meta or {})))++ # ------------------------------------------------------------------ state (privileged)+ def state_sha(self) -> str:+ """sha256 over every articulation's and rigid object's root state, joint positions and velocities."""+ m = hashlib.sha256()+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name in sorted(group):+ d = group[name].data+ for t in (d.root_state_w, getattr(d, "joint_pos", None), getattr(d, "joint_vel", None)):+ if t is not None:+ m.update(name.encode()); m.update(_np(t).tobytes())+ return m.hexdigest()++ def state(self) -> dict[str, Any]:+ """Privileged observation of the task (AM-Bench's own `policy` observation: robot, end effector, task objects and+ goal positions, relative to the environment's origin)."""+ obs = self.obs["policy"][0] if isinstance(self.obs.get("policy"), list) else self.obs.get("policy")+ return {k: _np(v).reshape(-1).tolist() for k, v in (obs.items() if isinstance(obs, dict) else [])}++ def objects(self) -> dict[str, dict]:+ """Every articulation (but the robot) and rigid object of the scene: root pose (wxyz) and velocities, joint state."""+ out, o = {}, _np(self.env.scene.env_origins[0])+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name, obj in group.items():+ if name == "robot":+ continue+ rs = _np(obj.data.root_state_w[0])+ ent = {"position": (rs[:3] - o).tolist(), "orientation_wxyz": rs[3:7].tolist(), "velocity": rs[7:10].tolist(),+ "angular_velocity": rs[10:13].tolist()}+ if getattr(obj.data, "joint_pos", None) is not None:+ ent["joint_pos"] = _np(obj.data.joint_pos[0]).tolist(); ent["joint_names"] = list(obj.joint_names)+ out[name] = ent+ return out++ def proprio(self) -> dict[str, Any]:+ """The robot's own state: base and end-effector poses (world, relative to the env origin; wxyz) and velocities, the+ gripper opening and the arm joints, the current end-effector command."""+ e = self.env; o = _np(e.scene.env_origins[0])+ base = _np(e.robot.data.body_link_state_w[0, e.base_link_idx]); ee = _np(e.robot.data.body_link_state_w[0, e.ee_link_idx])+ jp = _np(e.robot.data.joint_pos[0]); jv = _np(e.robot.data.joint_vel[0])+ return {"base_pose": np.r_[base[:3] - o, base[3:7]].tolist(), "base_vel": base[7:13].tolist(),+ "ee_pose": np.r_[ee[:3] - o, ee[3:7]].tolist(), "ee_vel": ee[7:13].tolist(),+ "gripper_width": float(np.sum(jp[e.gripper_joint_ids])),+ "arm_joint_pos": jp[e.arm_joint_ids].tolist(), "arm_joint_vel": jv[e.arm_joint_ids].tolist(),+ "command": self.hold_action().tolist()}++ # ------------------------------------------------------------------ cameras+ def render_frame(self, camera: str = "ee_camera") -> np.ndarray:+ """RGB uint8 (384, 384, 3) of the robot's onboard camera `ee_camera` (at the end effector) or `base_camera` (on the+ airframe, looking forward), as of the last step. Only in a Session(cameras=True): the cameras render every step+ and that makes the physics timing-dependent, so check what you find there with the replay CLI (no cameras)."""+ if not self.cameras:+ raise RuntimeError("no cameras in this Session: start the process with Session(..., cameras=True) to look "+ "(its numerics differ from the grader's camera-free replay; check trajectories with the CLI)")+ cam = getattr(self.env, camera, None)+ if cam is None:+ raise KeyError(f"no camera {camera!r}; cameras: {[c for c in CAMERAS if getattr(self.env, c, None) is not None]}")+ return _np(cam.data.output["rgb"][0])[..., :3].astype(np.uint8)++ def start_video(self, path, fps: int = 30, camera: str = "ee_camera") -> None:+ import imageio.v2 as imageio+ self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),+ "every": max(1, round(CONTROL_HZ / fps)), "camera": camera, "path": str(path)}+ self._video_add(force=True)++ def _video_add(self, force: bool = False) -> None:+ v = self._video+ if force or self.n_steps % v["every"] == 0 or self.done:+ frames = [self.render_frame(c) for c in CAMERAS if getattr(self.env, c, None) is not None]+ v["w"].append_data(np.concatenate(frames, axis=1))++ def stop_video(self):+ v, self._video = self._video, None+ if v:+ v["w"].close()+ return v["path"]++ def close(self) -> None:+ _slog("session_end", env_id=self.env_id, sim_steps=self.n_steps_total, resets=self.n_resets)+ try:+ self.env.close()+ except Exception: # noqa: BLE001+ pass+++def load_trajectory(path, env_id: str) -> np.ndarray:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != env_id:+ raise ValueError(f"trajectory is for {str(d['task'])!r}, not {env_id!r}")+ A = np.asarray(d["actions"], dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != ACTION_DIM or A.shape[0] > MAX_STEPS or not np.all(np.isfinite(A)):+ raise ValueError(f"actions must be a finite (T, {ACTION_DIM}) array with T <= {MAX_STEPS}, got {list(A.shape)}")+ return A+++def _replay_rows(s: "Session", A: np.ndarray) -> dict:+ for row in A: # the process's first episode+ if s.step(row):+ break+ res = s.status()+ return {**{k: res[k] for k in ("success", "state_sha", "end_reason", "control_steps", "sim_time_s")}, "executed_rows": s.n_steps}+++def _cli_replay(a) -> int:+ """The grader's replay: a fresh process, no cameras (bit-reproducible), the process's first episode."""+ t0 = time.time()+ s = Session(a.instance)+ out: dict[str, Any] = {"task": s.env_id, "instance_matches": bool(s.instance_matches), "initial_sha": s.initial_sha}+ try:+ A = load_trajectory(a.traj, s.env_id)+ except Exception as exc: # noqa: BLE001+ out["error"] = f"bad trajectory: {exc!r}"[:300]; print(json.dumps(out), flush=True); return 2+ out["replays"] = [_replay_rows(s, A)]+ out["n_actions"] = int(len(A)); out["replay_wall_s"] = round(time.time() - t0, 2)+ print(json.dumps(out), flush=True)+ s.close()+ return 0+++def _cli_film(a) -> int:+ """An illustration, never a verdict: the rows with the onboard cameras on, filmed (both cameras side by side) plus the+ last end-effector frame. Camera rendering makes the physics timing-dependent, so this episode may end differently."""+ t0 = time.time()+ s = Session(a.instance, cameras=True)+ A = load_trajectory(a.traj, s.env_id)+ s.start_video(a.video, fps=a.fps)+ res = _replay_rows(s, A)+ s.stop_video()+ from PIL import Image+ Image.fromarray(s.render_frame("ee_camera")).save(str(Path(a.video).with_suffix(".last.png")))+ print(json.dumps({"task": s.env_id, "film": res, "video": a.video, "film_wall_s": round(time.time() - t0, 2)}), flush=True)+ s.close()+ return 0+++def _cli_make_instance(a) -> int:+ inst = {"env_id": a.env_id, "seed": int(a.seed)}+ s = Session(inst)+ inst.update({"task": a.env_id.split("-")[0], "action_dim": ACTION_DIM, "control_hz": CONTROL_HZ,+ "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha})+ Path(a.out).write_text(json.dumps(inst, indent=1) + "\n")+ print(json.dumps({"env_id": a.env_id, "initial_sha": s.initial_sha}), flush=True)+ s.close()+ return 0+++def _cli_run_actions(a) -> int:+ s = Session(a.instance, strict=True)+ for row in np.load(a.actions): # the process's first episode (no second reset), as the grader's+ if s.step(row):+ break+ res = {**s.status(), "executed_rows": s.n_steps}+ s.save_trajectory(s.actions(), a.out, meta={"source": "reference rows"})+ print(json.dumps({k: res[k] for k in ("success", "end_reason", "state_sha", "control_steps", "executed_rows", "sim_time_s")}), flush=True)+ s.close()+ return 0+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay"); r.add_argument("--instance", required=True); r.add_argument("--traj", required=True)+ f = sub.add_parser("film"); f.add_argument("--instance", required=True); f.add_argument("--traj", required=True)+ f.add_argument("--video", required=True); f.add_argument("--fps", type=int, default=30)+ m = sub.add_parser("make-instance"); m.add_argument("--env-id", required=True); m.add_argument("--seed", type=int, default=0); m.add_argument("--out", required=True)+ x = sub.add_parser("run-actions"); x.add_argument("--instance", required=True); x.add_argument("--actions", required=True); x.add_argument("--out", required=True)+ a = ap.parse_args(argv)+ global SESSION_LOG+ SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "") # the CLI logs nothing unless asked+ try:+ rc = {"replay": _cli_replay, "film": _cli_film, "make-instance": _cli_make_instance, "run-actions": _cli_run_actions}[a.cmd](a)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error: report it and leave at once+ import traceback+ traceback.print_exc(); rc = 3+ sys.stdout.flush(); sys.stderr.flush()+ os._exit(rc) # Isaac Sim's shutdown can hang or crash after the result line; the result is printed+++if __name__ == "__main__":+ main()diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/limits.json b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/limits.jsonnew file mode 100644index 0000000000..55fc2d02e6--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/limits.json@@ -0,0 +1,33 @@+{+ "caps": {+ "main": {+ "cpus": 8.0,+ "memory_gb": 34.0,+ "pids": 16384+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": true,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 16.0,+ "max_memory_gb": 28.0,+ "max_processes": 512,+ "mode": "privileged",+ "scope": "trial",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "ambench-push-slider-fahexa-i00-privileged",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 16.0,+ "trial_max_memory_gb": 28.0,+ "window_sec": 120.0+}diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/monitor.pynew file mode 100644index 0000000000..81fdc91877--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/monitor.py@@ -0,0 +1,966 @@+#!/usr/bin/env python3+"""rcb_monitor: the trusted resource-limits monitor sidecar of every task (docs/PROTOCOL.md §2.10, record rcb-monitor/1).++Runs as the compose service `rcb_monitor` (generated by scripts/rcb_monitor/inject.py): `pid: host`, `cgroup: host`,+`network_mode: none`, CAP_SYS_PTRACE, the task's GPU reservation, its code read-only from the task directory. The agent+cannot see it (another PID namespace), reach it (no network) or write its record (its own file system).++Which containers it watches: the services that mount the trial's beacon volume `rcb_limits` (read-only at+/run/rcb-limits) are in scope, the ones that mount `rcb_observe` are only recorded (the benchmark's own services: the+simulator sidecar of standard modes, RoboPaint's privileged `scorer`). The compose project names both volumes, so they are unique to the trial; the monitor finds the containers as+the mount namespaces whose /run/rcb-limits is the same directory as its own (docker compose exec'd processes included).+A namespace that does not show the beacon is asked again at every tick (a container that is still being set up has the+host's root until its pivot_root: "no" is never remembered); a "yes" is kept only while the process that proved it lives.+A process whose first thread has exited is found through a thread that lives; a zombie counts in its parent's container.++Every tick (5 s; disk every 60 s) it samples, per container and summed over the scope: GPU memory (NVML, per process,+compute and graphics), memory (cgroup anon+shmem when the container has its own cgroup, else PSS anon+shmem), processes+(TGIDs, zombies included), disk growth under the limits' disk_paths in the agent's container (complete walks only, in+slices between the samples), CPU (recorded only). It appends to /var/rcb-monitor/samples.jsonl and+events.jsonl and writes the agent-visible /run/rcb-limits/usage.json.++Kernel OOM kills (`oom` events) are read from each watched container's cgroup `memory.events` by a thread of its own+(OomWatch), many times a second: a kill that takes the container's main process with it ends the container, and compose+restarts it with a new cgroup whose counters start at 0, within milliseconds -- a reading once per tick never sees it.+Every event says whom it hit (`scope`: a container the limits bind, or a benchmark-owned service that is only+recorded) and why (`cause`): "cap" when the container's own `oom` counter rose with it (the kernel says its memory+reached its own cap), else "host" (the host's OOM killer, or an enclosing cgroup's: not this container's doing).+Only a "cap" kill in the scope is a violation (rcb_limits.violations); the verifier step reports the others.++RCB_LIMITS_ENFORCE=1 (run-time switch; compose default 0; 0/1/true/false, anything else is a fatal record): once a+violation is confirmed (rcb_limits.violations, the verifier's own rule) the monitor SIGKILLs every in-scope process+except each container's PID 1, so the agent stops at once and Harbor goes on to collection and the verifier (an agent+killed this way ends like one that exited non-zero). It also protects the host (`emergency_kill` events, never a+violation by themselves): above EMERGENCY_GPU_FACTOR x the GPU-memory limit at one sample it kills the scope's process+that holds the most GPU memory; where the runtime applies no kernel memory cap, it stands in for it and kills the+largest process once the scope is above its declared memory caps.+0: it only records.++ python3 monitor.py run # the service's command+ python3 monitor.py seal --wait 90 # the first sidecar collect hook: seal the record (summary.json), print it+"""+import ctypes+import json+import os+import select+import signal+import stat as stat_mod+import sys+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import rcb_limits # noqa: E402+import selftest # noqa: E402++REC = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+PROC, CGROUP = "/proc", "/sys/fs/cgroup" # module globals: scripts/rcb_monitor/test_monitor.py points them at a fake tree+SCOPE_BEACON, OBSERVE_BEACON = "/run/rcb-limits", "/run/rcb-observe"+LIMITS = os.path.join(HERE, "limits.json")+HZ = os.sysconf("SC_CLK_TCK")+PAGE = os.sysconf("SC_PAGE_SIZE")+GIB = float(2 ** 30)+EMERGENCY_GPU_FACTOR = 1.5 # host protection (enforced runs): above this x the GPU-memory limit at one sample+DISK_SLICE_SEC = 1.5 # of every tick a running disk walk may take (the monitor's CPU cap is half a core)+DISK_WALK_MAX_SEC = 300.0 # a walk not finished by then is partial: a gap in the record, never a baseline+OOM_COLD_SEC = 0.02 # OomWatch: every memory.events is read this often (or at once, when the kernel notifies)+OOM_HOT_SEC = 0.002 # ... and this often for OOM_HOT_FOR_SEC after any of them changed (memory pressure)+OOM_HOT_FOR_SEC = 2.0+OOM_CAP_WINDOW_SEC = 10.0 # a kill is the container's own cap's when its `oom` counter rose with it or this shortly before+OOM_FORGET_SEC = 600.0 # a cgroup not seen by the sampler for this long is no longer watched+++# --------------------------------------------------------------------------------------------------- small helpers+def now():+ return time.time()+++def rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def read(p):+ try:+ with open(p) as f:+ return f.read()+ except OSError:+ return None+++def stat_id(p):+ try:+ st = os.stat(p)+ return (st.st_dev, st.st_ino)+ except OSError:+ return None+++def stat_of(base):+ """(starttime, utime+stime) of the process or thread at /proc path `base`, or None."""+ s = read(base + "/stat")+ if not s:+ return None+ try:+ f = s.rsplit(")", 1)[1].split()+ return int(f[19]), int(f[11]) + int(f[12])+ except (IndexError, ValueError):+ return None+++def proc_stat(pid):+ return stat_of(f"{PROC}/{pid}")+++def status(pid):+ s = read(f"{PROC}/{pid}/status")+ if not s:+ return {}+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v.strip()+ return d+++def kb(v):+ try:+ return int((v or "0").split()[0])+ except (ValueError, IndexError):+ return 0+++def append(name, obj):+ with open(os.path.join(REC, name), "a") as f:+ f.write(json.dumps(obj, separators=(",", ":")) + "\n")+++def write_json(path, obj):+ tmp = path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f, indent=1)+ os.replace(tmp, path)+++def event(kind, **kw):+ kw.update(t=round(now(), 2), event=kind)+ append("events.jsonl", kw)+++def no_dump():+ """Not dumpable: without CAP_SYS_PTRACE nobody (not even the same uid) can open /proc/<monitor>/{root,mem,fd}."""+ try:+ ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLE = 4+ except Exception:+ pass+++# --------------------------------------------------------------------------------------------------- NVML+class Nvml:+ """Per-process GPU memory (host PIDs: the monitor runs in the host PID namespace) and per-card use, via libnvidia-ml+ (ctypes; no nvidia-smi child processes)."""++ class Proc(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong),+ ("gpuInstanceId", ctypes.c_uint), ("computeInstanceId", ctypes.c_uint)]++ class Proc1(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong)]++ class Mem(ctypes.Structure):+ _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]++ def __init__(self):+ self.lib = ctypes.CDLL("libnvidia-ml.so.1")+ if self.lib.nvmlInit_v2() != 0:+ raise RuntimeError("nvmlInit failed")+ n = ctypes.c_uint(0)+ self.lib.nvmlDeviceGetCount_v2(ctypes.byref(n))+ self.handles = []+ for i in range(n.value):+ h = ctypes.c_void_p()+ if self.lib.nvmlDeviceGetHandleByIndex_v2(i, ctypes.byref(h)) == 0:+ self.handles.append(h)+ self.fns = []+ for name, st in (("nvmlDeviceGetComputeRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses", self.Proc1),+ ("nvmlDeviceGetGraphicsRunningProcesses", self.Proc1)):+ kind = "compute" if "Compute" in name else "graphics"+ if any(k == kind for k, _, _ in self.fns):+ continue+ try:+ self.fns.append((kind, getattr(self.lib, name), st))+ except AttributeError:+ pass++ def sample(self):+ """({host pid: MiB}, {card index: (used MiB, total MiB)}, {host pids whose memory NVML does not tell})."""+ per, cards, unknown = {}, {}, set()+ for i, h in enumerate(self.handles):+ m = self.Mem()+ if self.lib.nvmlDeviceGetMemoryInfo(h, ctypes.byref(m)) == 0:+ cards[i] = (m.used // 2 ** 20, m.total // 2 ** 20)+ seen = {}+ for _kind, fn, st in self.fns:+ cnt = ctypes.c_uint(0)+ rc = fn(h, ctypes.byref(cnt), None)+ if rc not in (0, 7): # 7 = NVML_ERROR_INSUFFICIENT_SIZE: cnt now holds the count+ continue+ cnt = ctypes.c_uint(cnt.value + 16)+ arr = (st * cnt.value)()+ if fn(h, ctypes.byref(cnt), arr) != 0:+ continue+ for k in range(cnt.value):+ mem = arr[k].usedGpuMemory+ if mem >= 2 ** 63: # NVML_VALUE_NOT_AVAILABLE (MIG / vGPU / WSL): not a zero+ unknown.add(arr[k].pid)+ mib = 0+ else:+ mib = mem // 2 ** 20+ seen[arr[k].pid] = max(seen.get(arr[k].pid, 0), mib) # a C+G process is in both lists+ for p, v in seen.items():+ per[p] = per.get(p, 0) + v+ return per, cards, unknown+++# --------------------------------------------------------------------------------------------------- disk+class DiskWalk:+ """One measurement of the files under `paths` below `root` (the agent container's root, seen through /proc): the+ sum of st_blocks, every hard-linked file once, never descending into another mount (a directory on another device;+ files are not asked for theirs: on an overlay root whose layers sit on different file systems they report their+ layer's), `exclude` skipped. It runs in+ slices (step) between the monitor's samples, so a large tree delays no sample. `done` only when every directory was+ read: only then is `bytes` a measurement; before that it is a lower bound."""++ def __init__(self, root, paths, exclude):+ self.root, self.t0 = root, now()+ self.bytes = self.entries = 0+ self.done, self.why = False, None+ self._it = self._walk(list(paths), {root + x.rstrip("/") for x in exclude})++ def _walk(self, paths, excl):+ linked = set() # (dev, ino) of files with several names: counted once+ for base in paths:+ top = self.root + base+ try:+ dev = os.lstat(top).st_dev+ except FileNotFoundError:+ continue # the path does not exist in this container: nothing under it+ except OSError as e:+ self.why = f"{base}: {type(e).__name__}"+ return+ stack = [top]+ while stack:+ d = stack.pop()+ try:+ it = os.scandir(d)+ except FileNotFoundError:+ continue # removed since its parent was read+ except OSError as e:+ self.why = f"{d[len(self.root):]}: {type(e).__name__}"+ return+ with it:+ for e in it:+ try:+ st = e.stat(follow_symlinks=False)+ except OSError:+ continue # removed meanwhile+ if stat_mod.S_ISDIR(st.st_mode):+ if st.st_dev != dev or e.path in excl:+ continue # another mount (never crossed: not the container's own files)+ stack.append(e.path)+ elif st.st_nlink > 1:+ k = (st.st_dev, st.st_ino)+ if k in linked:+ continue+ linked.add(k)+ self.bytes += st.st_blocks * 512+ self.entries += 1+ if self.entries % 256 == 0:+ yield+ yield+ self.done = True++ def step(self, budget_sec):+ """Walk on for at most `budget_sec`; True when the walk has ended (done, or failed with `why`)."""+ end = now() + budget_sec+ for _ in self._it:+ if now() >= end:+ return False+ return True+++# --------------------------------------------------------------------------------------------------- OOM kills+class OomWatch:+ """Kernel OOM kills of the watched containers, from each one's cgroup v2 `memory.events`:+ oom times the cgroup's memory reached its own limit (memory.max) and an allocation was about to fail+ oom_kill processes of the cgroup killed by any OOM killer (its own limit's, an enclosing cgroup's, the host's)+ A kill whose `oom` counter rose with it (or within OOM_CAP_WINDOW_SEC before) happened at the container's own cap+ (`cause: "cap"`); one without is the host's or an enclosing cgroup's OOM killer (`cause: "host"`), which the+ container did not cause by its own use (PROTOCOL §2.10: nothing another trial does can fail a trial).++ The counters live and die with the cgroup, and a container whose main process is killed is gone (and restarted by+ compose with fresh counters) within milliseconds. So the files are read by this object's own thread, every+ OOM_COLD_SEC, at once when the kernel signals a change (poll: memory.events notifies), and every OOM_HOT_SEC for a+ while after any change (the `max` counter rises under memory pressure, before a kill). A kill that removes the+ cgroup within about a millisecond can still be missed: such a kill is then in no record.++ scan() reads every file once; the sampler calls it at each tick when the thread does not run (the tests). The+ thread ends when the record is sealed."""++ def __init__(self):+ self.lock = threading.Lock()+ self.w = {} # cgroup dir -> {"role", "scope", "fd", "kill", "oom", "sig", "cap_t", "seen"}+ self.hot_until = 0.0+ self.thread = None+ self.stopped = False # set at the seal: the record is closed, like the samples++ def watch(self, cg, role, scope, t):+ """The sampler saw this container's cgroup at time t."""+ with self.lock:+ e = self.w.get(cg)+ if e is None:+ e = self.w[cg] = {"fd": None, "kill": None, "oom": None, "sig": None, "cap_t": None}+ e.update(role=role, scope=bool(scope), seen=t)++ @staticmethod+ def _close(e):+ if e["fd"] is not None:+ try:+ os.close(e["fd"])+ except OSError:+ pass+ e["fd"] = None++ def _read(self, cg, e):+ """The counters of the cgroup's memory.events ({} when the file cannot be read: the container is not up).+ A file that stops answering belonged to a cgroup that is gone; the same path opened again is a new cgroup (the+ container restarted: another directory, by its inode and creation time), whose counters all belong to the+ trial: they are compared with 0. The same cgroup opened again keeps what was already counted."""+ for _ in (0, 1):+ try:+ if e["fd"] is None:+ e["fd"] = os.open(cg + "/memory.events", os.O_RDONLY)+ st = os.stat(cg)+ ident = (st.st_dev, st.st_ino, st.st_ctime_ns)+ if e["sig"] is not None and ident != e.get("ident"):+ e["kill"] = e["oom"] = 0 # read before, gone, here again: another instance of the cgroup+ e["ident"] = ident+ os.lseek(e["fd"], 0, os.SEEK_SET)+ out = {}+ for line in os.read(e["fd"], 8192).decode("ascii", "replace").splitlines():+ k, _, v = line.partition(" ")+ if v.strip().isdigit():+ out[k] = int(v)+ return out+ except OSError:+ self._close(e)+ return {}++ def scan(self):+ """Read every watched file once and record the kills since the last reading. True when a counter changed."""+ changed = False+ with self.lock:+ t = now()+ for cg, e in list(self.w.items()):+ if t - e["seen"] > OOM_FORGET_SEC:+ self._close(e)+ del self.w[cg]+ continue+ c = self._read(cg, e)+ if "oom_kill" not in c:+ continue+ kill, oom = c["oom_kill"], c.get("oom", 0)+ sig = (kill, oom, c.get("max", 0))+ if e["kill"] is None or kill < e["kill"] or oom < e["oom"]:+ # the first reading is the baseline; counters that went back are a new cgroup under the same path+ e["kill"], e["oom"] = (kill, oom) if e["kill"] is None else (0, 0)+ changed |= sig != e["sig"]+ if oom > e["oom"]:+ e["cap_t"] = t+ if kill > e["kill"]:+ at_cap = e["cap_t"] is not None and t - e["cap_t"] <= OOM_CAP_WINDOW_SEC+ kw = {"role": e["role"], "scope": e["scope"], "count": kill - e["kill"],+ "cause": "cap" if at_cap else "host", "cap_hits": oom - e["oom"]}+ for name, key in (("memory.max", "memory_cap_gb"), ("memory.current", "memory_current_gb")):+ v = (read(cg + "/" + name) or "").strip() # evidence only: the cause is the counters'+ if v.isdigit():+ kw[key] = round(int(v) / GIB, 3)+ event("oom", **kw)+ e["kill"], e["oom"], e["sig"] = kill, oom, sig+ return changed++ def start(self):+ self.thread = threading.Thread(target=self._loop, name="rcb-oom-watch", daemon=True)+ self.thread.start()++ def _loop(self):+ said = False+ while not self.stopped:+ try:+ if self.scan():+ self.hot_until = now() + OOM_HOT_FOR_SEC+ if now() < self.hot_until:+ time.sleep(OOM_HOT_SEC)+ continue+ with self.lock:+ fds = [e["fd"] for e in self.w.values() if e["fd"] is not None]+ if not fds:+ time.sleep(OOM_COLD_SEC)+ continue+ p = select.poll() # memory.events notifies its readers (POLLPRI) when it changes+ for fd in fds:+ p.register(fd, select.POLLPRI | select.POLLERR)+ if p.poll(OOM_COLD_SEC * 1000):+ self.hot_until = now() + OOM_HOT_FOR_SEC+ except Exception as e: # never stop watching+ if not said:+ said = True+ try:+ event("error", why=f"oom watch: {type(e).__name__}: {e}"[:300])+ except Exception:+ pass+ time.sleep(OOM_COLD_SEC)+++# --------------------------------------------------------------------------------------------------- the monitor+class Monitor:+ def __init__(self):+ self.lim = rcb_limits.read_json(LIMITS) or {}+ self.tick = float(self.lim.get("tick_sec", 5))+ self.disk_tick = float(self.lim.get("disk_tick_sec", 60))+ self.enforce, self.switch_error = rcb_limits.parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ self.me_mnt = rl(f"{PROC}/self/ns/mnt")+ self.beacon = {"scope": stat_id(SCOPE_BEACON), "observe": stat_id(OBSERVE_BEACON)}+ self.cls = {} # mnt ns -> {"kind", "role", "witness": (proc path, starttime)}: only what IS watched+ self.neg, self.ok = set(), set() # this tick: namespaces that said no / whose witness still lives+ self.via = {} # pid -> /proc path of a living thread, for a process whose first thread has exited+ self.prev_cpu = {} # pid -> (starttime, ticks, t)+ self.oomw = OomWatch() # kernel OOM kills of the watched containers (its own thread in run())+ self.disk_base = None # GiB under disk_paths at the first complete walk (kept in state.json across restarts)+ self.disk_last = 0.0+ self.disk_gb = None+ self.walk = None # (DiskWalk, mnt ns, proc path, starttime) of the measurement under way+ self.series = [] # [(t, {metric: value})] of the last window, for enforcement decisions+ self.confirmed = {} # metric -> time+ self.kill_until = 0.0+ self.killed = 0+ self.emergency = [] # the emergency_kill events of this run+ self.scope_seen = False+ self.gpu_unknown = False+ self.caps = selftest.capabilities()+ self.nvml = None+ try:+ self.nvml = Nvml()+ except Exception as e:+ self.caps["nvml_error"] = f"{type(e).__name__}: {e}"[:200]+ self.caps["nvml"] = int(self.nvml is not None)+ self.caps["nvml_devices"] = len(self.nvml.handles) if self.nvml else 0+ self.t0 = now()+ self._last_measures, self._gpu_per = [], {}+ self.fatal_scope = False++ # ---- scope discovery+ def base(self, pid):+ """The /proc path to read a process's namespaces, root and memory from."""+ return self.via.get(pid) or f"{PROC}/{pid}"++ def classify(self, mnt, base):+ """{"kind": "scope" | "observe", "role": "main" | "sidecar"} when the mount namespace `mnt` (of the process or+ thread at /proc path `base`) is one of the trial's containers, else None.++ "No" is never remembered beyond this tick: while a container is set up, its init process is already in a new+ mount namespace but still has the host's root, and the beacon appears only with its pivot_root. "Yes" is+ remembered while the process that proved it lives in the namespace (the kernel may give the number of a+ namespace that ended to a new one)."""+ if mnt in self.ok:+ return self.cls[mnt]+ if mnt in self.neg:+ return None+ c = self.cls.get(mnt)+ if c is not None:+ wbase, wstart = c["witness"]+ ws = stat_of(wbase)+ if ws and ws[0] == wstart and rl(wbase + "/ns/mnt") == mnt:+ self.ok.add(mnt)+ return c+ del self.cls[mnt]+ root = base + "/root"+ kind = None+ if self.beacon["scope"] and stat_id(root + SCOPE_BEACON) == self.beacon["scope"]:+ kind = "scope"+ elif self.beacon["observe"] and stat_id(root + OBSERVE_BEACON) == self.beacon["observe"]:+ kind = "observe"+ st = stat_of(base)+ here = st is not None and rl(base + "/ns/mnt") == mnt # a vanished process tells nothing: ask the next+ if kind and here:+ c = {"kind": kind, "role": "main" if os.path.isdir(root + "/logs/agent") else "sidecar",+ "witness": (base, st[0])}+ self.cls[mnt] = c+ self.ok.add(mnt)+ return c+ if here:+ self.neg.add(mnt)+ return None++ def live_thread(self, pid):+ """/proc path of a thread of `pid` that still runs (its first thread has exited: /proc/<pid>/ns is empty)."""+ try:+ tids = os.listdir(f"{PROC}/{pid}/task")+ except OSError:+ return None+ for tid in tids:+ b = f"{PROC}/{pid}/task/{tid}"+ if tid != str(pid) and rl(b + "/ns/mnt"):+ return b+ return None++ def groups(self):+ """{mnt ns: {"kind", "role", "pids": [...], "zombies": n}} of the watched containers."""+ self.neg, self.ok, self.via = set(), set(), {}+ out, where, lost = {}, {}, []+ try:+ names = os.listdir(PROC)+ except OSError:+ names = []+ for d in names:+ if not d.isdigit():+ continue+ pid = int(d)+ mnt = rl(f"{PROC}/{pid}/ns/mnt")+ if mnt is None:+ lost.append(pid)+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, f"{PROC}/{pid}")+ if c:+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ zombies = []+ for pid in lost:+ b = self.live_thread(pid)+ if not b:+ zombies.append(pid)+ continue+ mnt = rl(b + "/ns/mnt") # its first thread exited, the others run on: a process like any other+ if mnt is None:+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, b)+ if c:+ self.via[pid] = b+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ for pid in zombies:+ st = status(pid)+ if st.get("State", "").startswith("Z"): # a zombie holds a PID until its parent reaps it: counted there+ try:+ g = out.get(where.get(int(st.get("PPid", "0"))))+ except ValueError:+ g = None+ if g:+ g["zombies"] += 1+ self.cls = {m: c for m, c in self.cls.items() if m in self.ok}+ return out++ # ---- per-container measurements+ def cgroup_of(self, pids):+ """The container's own cgroup v2 directory (under the host tree, `cgroup: host`) when every process in it is this+ container's (rootless podman without cgroup delegation leaves containers in a shared one), else None."""+ paths = set()+ for p in pids[:8]:+ s = read(f"{PROC}/{p}/cgroup") or ""+ for line in s.splitlines():+ if line.startswith("0::"):+ paths.add(line[3:].strip())+ if len(paths) != 1:+ return None+ d = CGROUP + paths.pop()+ procs = read(d + "/cgroup.procs")+ if procs is None:+ return None+ members = {int(x) for x in procs.split() if x.isdigit()}+ return d if members and members <= set(pids) else None++ def mem_pss(self, pids):+ tot = 0+ for p in pids:+ s = read(self.base(p) + "/smaps_rollup")+ if s is None:+ st = status(p)+ tot += kb(st.get("RssAnon")) + kb(st.get("RssShmem"))+ continue+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v+ tot += (kb(d.get("Pss_Anon")) + kb(d.get("Pss_Shmem"))) if "Pss_Anon" in d else kb(d.get("Pss"))+ return tot / 1024.0 / 1024.0 # GiB++ def measure(self, g, gpu_per, t, gpu_unknown=()):+ pids = g["pids"]+ threads = cpu = 0.0+ for p in pids:+ threads += int(status(p).get("Threads", "0") or 0)+ ps = proc_stat(p)+ if ps:+ pv = self.prev_cpu.get(p)+ if pv and pv[0] == ps[0] and t > pv[2]:+ cpu += max(0, ps[1] - pv[1]) / HZ / (t - pv[2])+ self.prev_cpu[p] = (ps[0], ps[1], t)+ cg = self.cgroup_of(pids)+ m = {"kind": g["kind"], "role": g["role"], "processes": len(pids) + g.get("zombies", 0),+ "zombies": g.get("zombies", 0), "threads": int(threads), "cpu": round(cpu, 2),+ "gpu_memory_gb": round(sum(gpu_per.get(p, 0) for p in pids) / 1024.0, 3), "cgroup": int(cg is not None)}+ unknown = sum(1 for p in pids if p in gpu_unknown)+ if unknown:+ m["gpu_unmeasured"] = unknown # processes on the GPU whose memory NVML does not tell+ if cg:+ st = {}+ for line in (read(cg + "/memory.stat") or "").splitlines():+ k, _, v = line.partition(" ")+ st[k] = v+ try:+ m["memory_gb"] = round((int(st.get("anon", 0)) + int(st.get("shmem", 0))) / GIB, 3)+ except ValueError:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ mx = (read(cg + "/memory.max") or "").strip()+ m["memory_cap_gb"] = None if mx in ("", "max") else round(int(mx) / GIB, 2)+ self.oomw.watch(cg, g["role"], g["kind"] == "scope", now())+ else:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ return m++ # ---- disk+ def main_proc(self, groups):+ """(mnt ns, pid) to reach the agent container's files through: its PID 1 when visible (it outlives the others)."""+ for mnt, g in groups.items():+ if g["kind"] == "scope" and g["role"] == "main" and g["pids"]:+ init = [p for p in g["pids"] if (status(p).get("NSpid") or "").split()[-1:] == ["1"]]+ return mnt, (init[0] if init else min(g["pids"]))+ return None, None++ def disk_step(self, t, groups):+ """The disk value of this sample: GiB the files under disk_paths grew since the baseline, or None (not measured+ at this tick). Only a complete walk of a container that is still there is a measurement; only such a walk sets+ the baseline. A walk that did not finish is a lower bound: it can show that the limit is exceeded, never that it+ is not, and it never becomes the baseline."""+ if self.walk is None:+ mnt, pid = self.main_proc(groups)+ if pid is None or t - self.disk_last < self.disk_tick:+ return None+ b = self.base(pid)+ st = stat_of(b)+ if st is None:+ return None+ self.disk_last = t+ self.walk = (DiskWalk(b + "/root", self.lim.get("disk_paths") or ["/app"], self.lim.get("disk_exclude") or []),+ mnt, b, st[0])+ w, mnt, b, start = self.walk+ ended = w.step(DISK_SLICE_SEC)+ if not ended and now() - w.t0 <= DISK_WALK_MAX_SEC:+ return None # goes on at the next tick+ self.walk = None+ st = stat_of(b)+ there = st is not None and st[0] == start and rl(b + "/ns/mnt") == mnt # the same container, still up+ gb = w.bytes / GIB+ if ended and w.done and there:+ if self.disk_base is None:+ self.disk_base = gb+ self.save_state()+ event("disk_baseline", gb=round(gb, 3), entries=w.entries)+ self.disk_gb = round(max(0.0, gb - self.disk_base), 3)+ return self.disk_gb+ why = "the container's process ended during the walk" if not there else (w.why or "not finished in time")+ event("disk_partial", why=why, gb=round(gb, 3), entries=w.entries, sec=round(now() - w.t0, 1))+ lim = float(self.lim.get("max_disk_gb") or 0)+ if there and self.disk_base is not None and lim and gb - self.disk_base > lim:+ self.disk_gb = round(gb - self.disk_base, 3) # already over the limit, whatever the rest holds+ return self.disk_gb+ return None++ # ---- state that must outlive a restart of the monitor (restart: on-failure)+ def save_state(self):+ try:+ write_json(os.path.join(REC, "state.json"), {"disk_base": self.disk_base})+ except OSError:+ pass++ def restore(self):+ """After a restart: the disk baseline, the confirmed violations and the last window of samples come back from+ the record, so that a crash neither resets the baseline nor forgets time already spent over a limit."""+ st = rcb_limits.read_json(os.path.join(REC, "state.json")) or {}+ if isinstance(st.get("disk_base"), (int, float)):+ self.disk_base = float(st["disk_base"])+ _, samples, events = rcb_limits.load_record(REC)+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [(s["t"], s.get("scope") or {}) for s in samples+ if isinstance(s.get("t"), (int, float)) and s["t"] >= self.t0 - window - 3 * self.tick]+ for e in events:+ k = e.get("event")+ if k == "violation" and e.get("metric"):+ self.confirmed.setdefault(e["metric"], e.get("t") or self.t0)+ elif k in ("kill", "emergency_kill"):+ self.killed += int(e.get("processes") or 0)+ if k == "emergency_kill":+ self.emergency.append(e)+ elif k == "scope_found":+ self.scope_seen = True+ if self.enforce and self.confirmed and self.t0 - max(self.confirmed.values()) < 60:+ self.kill_until = max(self.confirmed.values()) + 60++ # ---- enforcement+ @staticmethod+ def spared(pids):+ """The container's own processes that must outlive a kill: its PID 1 and what PID 1 started with it (Harbor's+ `sh -c "sleep infinity"` keepalive). Agent processes are exec'd into the container (their parent is outside+ it) or, when orphaned, adopted by PID 1 later: those are never spared."""+ st = {p: status(p) for p in pids}+ init = [p for p in pids if (st[p].get("NSpid") or "").split()[-1:] == ["1"]]+ if not init:+ return set()+ t1 = (proc_stat(init[0]) or (0, 0))[0]+ keep = set(init)+ for p in pids:+ ns_ppid = None+ ns = (st[p].get("NSpid") or "").split()+ if ns and st[p].get("PPid") is not None:+ # PPid in /proc/<pid>/status is in the reader's namespace (host); compare with PID 1's host PID+ ns_ppid = int(st[p]["PPid"])+ ps = proc_stat(p)+ if ns_ppid == init[0] and ps and ps[0] - t1 <= 2 * HZ: # started with the container, not adopted later+ keep.add(p)+ return keep++ def kill_scope(self, groups, why):+ n = 0+ for mnt, g in groups.items():+ if g["kind"] != "scope":+ continue+ snap = {p: proc_stat(p) for p in g["pids"]}+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue # PID 1 and its keepalive: the container stays up for collection+ if rl(self.base(p) + "/ns/mnt") != mnt or not snap[p] or proc_stat(p) is None \+ or proc_stat(p)[0] != snap[p][0]:+ continue # gone, or its PID now names another process+ try:+ os.kill(p, signal.SIGKILL)+ n += 1+ except OSError:+ pass+ if n:+ self.killed += n+ event("kill", why=why, processes=n)+ return n++ def scope_memory_cap(self):+ """GiB: the declared memory caps of the services the limits bind, summed (None: not declared)."""+ caps = self.lim.get("caps") or {}+ names = self.lim.get("scope_services") or (+ [n for n in caps if n != "*"] if self.lim.get("scope") == "trial" else ["main"])+ vals = [float(caps[n]["memory_gb"]) for n in names if isinstance(caps.get(n), dict) and caps[n].get("memory_gb")]+ return sum(vals) if vals else None++ def check(self, t, scope_vals, groups):+ self.series.append((t, scope_vals))+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [x for x in self.series if x[0] >= t - window - 3 * self.tick]+ samples = [{"t": a, "scope": b} for a, b in self.series]+ for v in rcb_limits.violations(samples, self.lim):+ if v["metric"] not in self.confirmed:+ self.confirmed[v["metric"]] = t+ event("violation", **v)+ if self.enforce:+ self.kill_until = t + 60+ if self.enforce and t <= self.kill_until:+ self.kill_scope(groups, ",".join(sorted(self.confirmed)))+ # Host protection (enforced runs only; PROTOCOL §2.10). An emergency kill is never a violation by itself: the+ # trial fails only by the sustained rule above or a kernel OOM kill at its own memory cap. Both conditions are+ # the trial's own doing (its scope's use against its own limit or caps), never the state of a card or host it+ # shares with other trials.+ if self.enforce:+ cap = self.scope_memory_cap()+ lim_gpu = float(self.lim.get("max_gpu_memory_gb") or 0)+ if cap and scope_vals["memory_gb"] > cap and not any(+ m.get("memory_cap_gb") for m in self._last_measures if m["kind"] == "scope"):+ # no kernel memory cap holds here (e.g. rootless podman without cgroups): stand in for it+ self._emergency(groups, "memory", cap, scope_vals["memory_gb"], key="mem")+ if lim_gpu and scope_vals["gpu_memory_gb"] > EMERGENCY_GPU_FACTOR * lim_gpu:+ self._emergency(groups, "gpu_memory", lim_gpu, scope_vals["gpu_memory_gb"], key="gpu")++ def _emergency(self, groups, why, limit, observed, key):+ best, bv = None, 0 # only a process that holds some: never one with none of it+ for g in groups.values():+ if g["kind"] != "scope":+ continue+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue+ v = self._gpu_per.get(p, 0) if key == "gpu" else self.rss_kb(p)+ if v > bv:+ best, bv = p, v+ if best:+ try:+ os.kill(best, signal.SIGKILL)+ self.killed += 1+ e = {"why": why, "limit": limit, "observed": round(observed, 3), "processes": 1}+ event("emergency_kill", **e)+ self.emergency.append(dict(e, t=round(now(), 2)))+ except OSError:+ pass++ def rss_kb(self, p):+ v = kb(status(p).get("VmRSS"))+ if not v and p in self.via: # the first thread has exited: its status has no memory lines+ for line in (read(self.via[p] + "/status") or "").splitlines():+ if line.startswith("VmRSS:"):+ v = kb(line.partition(":")[2])+ return v++ # ---- main loop+ def run(self):+ os.makedirs(REC, exist_ok=True)+ restarted = os.path.exists(os.path.join(REC, "meta.json"))+ meta = {"format": rcb_limits.FORMAT, "started": round(self.t0, 2), "enforce": self.enforce, "limits": self.lim,+ "capabilities": self.caps, "beacons": {k: bool(v) for k, v in self.beacon.items()}}+ if self.switch_error:+ meta["switch_error"] = self.switch_error+ if restarted:+ self.restore()+ event("restart", capabilities=self.caps)+ else:+ write_json(os.path.join(REC, "meta.json"), meta)+ event("start", enforce=self.enforce, capabilities=self.caps)+ if self.switch_error:+ event("fatal", why=self.switch_error + " (nothing is enforced; the trial is not a result)")+ if not self.beacon["scope"]:+ event("fatal", why="no scope beacon mounted at /run/rcb-limits")+ if self.lim.get("gpu") and not self.nvml:+ event("fatal", why="GPU task but NVML is unavailable: " + str(self.caps.get("nvml_error")))+ sys.setswitchinterval(0.001) # the OOM watch must get its turn within a millisecond+ self.oomw.start()+ while not os.path.exists(os.path.join(REC, "seal.request")):+ t = now()+ try:+ self.tick_once(t)+ except Exception as e: # a vanished process mid-read must never stop the record+ import traceback+ traceback.print_exc()+ event("error", why=f"{type(e).__name__}: {e}"[:300])+ for p in list(self.prev_cpu):+ if t - self.prev_cpu[p][2] > 60:+ del self.prev_cpu[p]+ time.sleep(max(0.2, self.tick - (now() - t)))+ self.seal()+ while True: # stay up: Harbor copies the record after the hook+ time.sleep(3600)++ def tick_once(self, t):+ groups = self.groups()+ gpu_per, cards, gpu_unknown = self.nvml.sample() if self.nvml else ({}, {}, set())+ self._gpu_per = gpu_per+ ms = [self.measure(g, gpu_per, t, gpu_unknown) for g in groups.values()]+ self._last_measures = ms+ if self.oomw.thread is None:+ self.oomw.scan() # no thread (tests): read the OOM counters with the sample+ scope = [m for m in ms if m["kind"] == "scope"]+ if scope and not self.scope_seen:+ self.scope_seen = True+ event("scope_found", containers=len(scope), roles=sorted(m["role"] for m in scope))+ if not self.scope_seen and not self.fatal_scope and t - self.t0 > 120:+ self.fatal_scope = True+ event("fatal", why="no container mounting the trial's beacon found within 120 s")+ disk_now = self.disk_step(t, groups)+ vals = {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in scope), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in scope), 3),+ "processes": sum(m["processes"] for m in scope), "disk_gb": disk_now}+ unknown = sum(m.get("gpu_unmeasured", 0) for m in scope)+ if unknown:+ vals["gpu_unmeasured"] = unknown+ if not self.gpu_unknown:+ self.gpu_unknown = True+ event("gpu_unmeasured", processes=unknown,+ why="NVML does not tell the GPU memory of processes in scope (MIG / vGPU?): counted as 0")+ obs = [m for m in ms if m["kind"] == "observe"]+ append("samples.jsonl", {"t": round(t, 2), "scope": vals,+ "observe": {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in obs), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in obs), 3),+ "processes": sum(m["processes"] for m in obs)},+ "cards": {str(k): v for k, v in cards.items()}, "containers": ms})+ self.check(t, vals, groups)+ try:+ write_json(SCOPE_BEACON + "/usage.json", {+ "t": round(t, 2), "gpu_memory_gb": vals["gpu_memory_gb"], "memory_gb": vals["memory_gb"],+ "processes": vals["processes"], "disk_gb": self.disk_gb, "enforced": self.enforce,+ "limits": {k: self.lim.get(k) for k in ("max_gpu_memory_gb", "max_memory_gb", "max_processes",+ "max_disk_gb", "sustain_sec", "window_sec")},+ "violations": sorted(self.confirmed),+ # processes the monitor killed at once to protect the host (not violations by themselves)+ "emergency_kills": len(self.emergency), "last_emergency_kill": (self.emergency or [None])[-1]})+ except OSError:+ pass++ def seal(self):+ try:+ self.oomw.scan() # the counters once more, whatever the watch thread is doing+ except Exception:+ pass+ # The record ends here, for OOM kills as for the samples: what happens to a sidecar in the collect hooks that+ # follow (its replays) is the grader's to judge, from the hook's own evidence.+ self.oomw.stopped = True+ summary, samples, events = rcb_limits.load_record(REC)+ viol = rcb_limits.violations(samples, self.lim, events)+ meta = rcb_limits.read_json(os.path.join(REC, "meta.json")) or {}+ out = {+ "format": rcb_limits.FORMAT, "sealed": True, "enforce": meta.get("enforce", self.enforce),+ "started": meta.get("started"), "ended": round(now(), 2), "n_samples": len(samples),+ "scope_seen": self.scope_seen or any((s.get("scope") or {}).get("processes") for s in samples),+ "peaks": rcb_limits.peaks(samples), "violations": viol,+ "killed": sum(int(e.get("processes") or 0) for e in events if e.get("event") in ("kill", "emergency_kill")),+ "emergency_kills": sum(1 for e in events if e.get("event") == "emergency_kill"),+ "disk_baseline_gb": self.disk_base,+ "disk_partial_walks": sum(1 for e in events if e.get("event") == "disk_partial"),+ "restarts": sum(1 for e in events if e.get("event") == "restart"),+ "capabilities": meta.get("capabilities", self.caps), "limits": self.lim}+ if meta.get("switch_error") or self.switch_error:+ out["switch_error"] = meta.get("switch_error") or self.switch_error+ write_json(os.path.join(REC, "summary.json"), out)+ event("seal", violations=len(viol))+++def seal_cmd(wait):+ open(os.path.join(REC, "seal.request"), "a").close()+ path = os.path.join(REC, "summary.json")+ t_end = now() + wait+ while now() < t_end and not os.path.exists(path):+ time.sleep(0.5)+ s = rcb_limits.read_json(path)+ print(json.dumps({k: (s or {}).get(k) for k in ("sealed", "enforce", "n_samples", "peaks", "violations", "killed")}))+ return 0+++def main(argv):+ if argv[:1] == ["seal"]:+ wait = float(argv[argv.index("--wait") + 1]) if "--wait" in argv else 90.0+ return seal_cmd(wait)+ if argv[:1] in (["run"], []):+ no_dump()+ Monitor().run()+ return 0+ print(__doc__)+ return 2+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.pynew file mode 100644index 0000000000..a979bcdaff--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.py@@ -0,0 +1,457 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/selftest.pynew file mode 100644index 0000000000..89d553743f--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/environment/rcb_monitor/selftest.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""What the resource monitor can measure where it runs (capabilities(), written into its record), and a self-test of+the shared violation rule and the verifier step (no containers needed; ci_checks/check-monitor.py runs it):++ python3 scripts/rcb_monitor/selftest.py+"""+import json+import os+import sys+import tempfile++HERE = os.path.dirname(os.path.abspath(__file__))+++def _rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def capabilities():+ """Facts the verifier and the results footnotes need: does the monitor see the host's processes (pid: host), the+ host's cgroup tree (cgroup: host; per-container memory and OOM counts), """+ c = {}+ try:+ pids = [d for d in os.listdir("/proc") if d.isdigit()]+ except OSError:+ pids = []+ try:+ c["pid_host"] = int(len(pids) > 1 and open("/proc/1/comm").read().strip() != open("/proc/self/comm").read().strip())+ except OSError:+ c["pid_host"] = 0+ own = ""+ try:+ own = [ln[3:].strip() for ln in open("/proc/self/cgroup") if ln.startswith("0::")][0]+ except (OSError, IndexError):+ pass+ c["cgroup_v2"] = int(os.path.exists("/sys/fs/cgroup/cgroup.controllers"))+ c["cgroup_host"] = int(bool(own) and own != "/" and os.path.isdir("/sys/fs/cgroup" + own))+ return c+++# --------------------------------------------------------------------------------------------------- self-test+def _check(cond, msg):+ if not cond:+ raise AssertionError(msg)+++def test_rule():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ tick = 5.0+ over = [(i * tick, 10.0 if 20 <= i < 33 else 1.0) for i in range(60)] # 65 s over the limit+ _check(abs(r.sustained(over, 5, 60, 120, tick) - 160.0) < 0.01, "65 s over: confirmed at 60 s")+ short = [(i * tick, 10.0 if 20 <= i < 31 else 1.0) for i in range(60)] # 55 s+ _check(r.sustained(short, 5, 60, 120, tick) is None, "55 s over: no violation")+ flap = [(i * tick, 10.0 if (i % 2 == 0 and i >= 20) else 1.0) for i in range(80)] # half the time, never 60 s straight+ _check(r.sustained(flap, 5, 60, 120, tick) is not None, "59 s on / 1 s off does not escape: 60 s in any 120 s")+ sparse = [(i * 25.0, 10.0) for i in range(4)] # 25 s gaps count 15 s each+ _check(r.sustained(sparse, 5, 60, 120, tick) is None, "gaps never count against the agent")+ _check(r.sustained(over, 0, 60, 120, tick) is None, "limit 0 = not limited")+ disk = [(0, 1.0), (60, 30.0), (120, 1.0), (180, 30.0), (240, 31.0)]+ _check(r.consecutive(disk, 20) == 240, "disk: two consecutive measurements over")+++def test_verify():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ lim = {"max_gpu_memory_gb": 4.0, "max_memory_gb": 8.0, "max_processes": 100, "max_disk_gb": 10.0,+ "sustain_sec": 60, "window_sec": 120, "tick_sec": 5}+ for enforce, gpu, want in ((1, 6.0, "fail"), (0, 6.0, "observe"), (1, 3.0, "pass")):+ with tempfile.TemporaryDirectory() as d:+ rec, tests, logs = (os.path.join(d, x) for x in ("rec", "tests", "logs"))+ for x in (rec, tests, logs):+ os.makedirs(x)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ with open(os.path.join(rec, "samples.jsonl"), "w") as f:+ for i in range(40):+ f.write(json.dumps({"t": 1000 + 5 * i, "scope": {"gpu_memory_gb": gpu if i > 5 else 0.5,+ "memory_gb": 2.0, "processes": 10,+ "disk_gb": 0.1 if i % 12 == 0 else None}}) + "\n")+ open(os.path.join(rec, "events.jsonl"), "w").close()+ json.dump({"format": r.FORMAT, "sealed": True, "enforce": enforce, "scope_seen": True},+ open(os.path.join(rec, "summary.json"), "w"))+ json.dump({"success": 1, "infra_error": 0}, open(os.path.join(logs, "reward.json"), "w"))+ open(os.path.join(logs, "reward.txt"), "w").write("1\n")+ import shutil+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=rec, RCB_VERIFIER_LOGS=logs)+ import subprocess+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ txt = open(os.path.join(logs, "reward.txt")).read().strip()+ if want == "fail":+ _check(out["success"] == 0 and out["resource_limit_exceeded"] == 1 and out["success_before_limits"] == 1+ and txt == "0" and out["over_gpu_memory_gb"] == 1, f"enforced violation fails: {out}")+ elif want == "observe":+ _check(out["success"] == 1 and out["limits_violation_observed"] == 1 and txt == "1"+ and "resource_limit_exceeded" not in out, f"observe mode only records: {out}")+ else:+ _check(out["success"] == 1 and out["limits_violation_observed"] == 0 and out["resource_monitor_missing"] == 0,+ f"within limits: {out}")+ _check(out["peak_gpu_memory_gb"] == gpu, "peak recorded")+ # no record at all: enforced = infra, observed = flagged only+ for enforce in (1, 0):+ with tempfile.TemporaryDirectory() as d:+ logs, tests = os.path.join(d, "logs"), os.path.join(d, "tests")+ os.makedirs(logs)+ os.makedirs(tests)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ json.dump({"success": 1}, open(os.path.join(logs, "reward.json"), "w"))+ import shutil+ import subprocess+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=os.path.join(d, "none"), RCB_VERIFIER_LOGS=logs,+ RCB_LIMITS_ENFORCE=str(enforce))+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ _check(out["resource_monitor_missing"] == 1 and out.get("infra_error", 0) == enforce,+ f"missing record (enforce={enforce}): {out}")+++def main():+ if sys.argv[1:2] == ["caps"]:+ print(json.dumps(capabilities()))+ return 0+ test_rule()+ test_verify()+ print("rcb_monitor selftest: ok")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/instruction.md b/tasks/ambench-push-slider-fahexa-i00-privileged/instruction.mdnew file mode 100644index 0000000000..761e88663d--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/instruction.md@@ -0,0 +1,87 @@+# AM-Bench · Push Slider — frozen instance i00++You control a simulated **aerial manipulator**: a fully actuated hexarotor (six tilted rotors, so it can hold any attitude+while hovering) carrying a small arm (four joints: three pitch joints and a roll joint) with a two-finger gripper, in+AM-Bench on Isaac Lab / Isaac Sim 5.1 (PhysX), via Python. **Task:** A wall stands in front of the hovering aerial manipulator, with a horizontal slider mounted on its front face: a straight rail about 1 m long and a red knob that slides along it. The knob starts at the rail's left end (as seen from the robot facing the wall) and must be pushed along the rail until it is within 5 cm of the right end of its travel, i.e. at least 0.95 m along its 1 m travel.++This is a *fixed scene instance*: the scene and the robot start the same way after every reset, and you may reset and+retry as many times as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a+general policy.++## Scene+The ground is the world's z = 0 plane. In front of the robot stands an immovable (kinematic) wall: a slab 0.1 m thick, 2.0 m wide and 2.0 m tall with a concrete-block surface, its front face turned toward the robot. The wall is upright (no tilt in this task); its distance and sideways offset vary between instances. On its front face a slider fixture is mounted horizontally: a fixed rail 1.02 m long and 6 cm tall (a shallow channel standing about 3 cm out from the wall) and a red knob (a 4 x 4 x 6 cm block on a short stem, protruding about 7 cm from the wall surface) that slides along the rail over 1 m of travel. The fixture's height and sideways position on the wall vary between instances. The knob has no spring (it stays where it is left) but its motion is resisted by joint friction and damping. Nothing moves by itself. The robot starts hovering level and motionless, facing the wall, with its arm at its zero joint configuration (end effector a little ahead of and above the airframe) and the gripper closed.++Exactly (privileged information, also readable through the tooling): One environment; its origin is the world origin. Robot at every reset: base_link at (0, 0, 1.0) m with orientation (1, 0, 0, 0) wxyz (body +x is the world +x direction), zero velocity; arm_link1_pitch_joint = arm_link2_pitch_joint = arm_link3_pitch_joint = arm_link4_roll_joint = 0 rad; arm_lfinger_joint = arm_rfinger_joint = 0.001 m (their lower limit: gripper closed, gripper_width 0.002 m). By the robot's URDF kinematics this puts ee_link at about (0.227, 0, 1.124) m with identity orientation and the tool-tip point (ee_link origin + 0.18 m along the ee_link x axis) at about (0.407, 0, 1.124) m; the end-effector command is initialised to the current ee_link pose. Wall: kinematic cuboid 0.1 (x) x 2.0 (y) x 2.0 (z) m, nominal centre (2.0, 0.0, 1.0) m and orientation identity (front face the plane x = centre_x - 0.05, normal -x, toward the robot); friction 1.0 static / 1.0 dynamic, restitution 0; visual material NVIDIA Concrete_Block.mdl. At each reset (Isaac Lab mdp.reset_root_state_uniform) the centre becomes (2.0 + dx, 0.0 + dy, 1.0) with dx, dy ~ U(-0.2, 0.2) m independently; the configured pitch range is (-0, 0), so the wall keeps the identity orientation (upright, front normal -x). Slider: articulation slider_with_rail.usd with a fixed root body 'Rail' and self-collisions disabled. At each reset, after the wall, its root is placed at wall_centre + R_wall (-0.05, sy, sz) with sy, sz ~ U(-0.3, 0.3) m independently (on the wall's front face) and given the orientation R_wall composed with a 180 degree rotation about z, so the rail's local +x points toward the robot (world -x) and its local +y is world -y. Rail (rail frame, scaled 1.02 along y): base box 0.02 (x) x 1.02 (y) x 0.06 (z) m centred on the wall surface (half of it inside the wall), upper and lower edges 0.02 x 1.02 x 0.01 m at x = 0.02, z = +-0.025, edge covers 0.01 x 1.02 x 0.02 m at x = 0.025, z = +-0.018; mass 1 kg; no visual material bound. Knob (body 'Slider', gravity disabled, mass not authored so PhysX derives it from the collision shapes, colour (1, 0, 0)): a base plate 0.005 x 0.02 x 0.03 m at x = 0.017, a short connector cylinder, and a handle box 0.04 (x) x 0.04 (y) x 0.06 (z) m centred 0.052 m in front of the rail plane. Prismatic joint SliderJoint along the rail's local +y (world -y), limits [-0.5, 0.5] m, reset to -0.5 m with zero velocity every episode (knob at world y = root_y + 0.5, the robot's left end); positive motion moves the knob toward world -y. Isaac Lab implicit actuator (overriding the USD drive): stiffness 0, damping 5.0, joint friction 4.0 (static and dynamic), effort limit 1000, velocity limit 2.0 m/s. Scene default physics material: friction 1.0 / 1.0, restitution 0.++## Success (AM-Bench's own check)+Success when the slider's prismatic joint SliderJoint has position >= 0.45 m (slider_pushed_threshold; the joint ranges from -0.5 m to 0.5 m and starts at -0.5 m), i.e. the knob has travelled at least 0.95 m from its start toward world -y (the robot's right). AM-Bench also reports a subtask criterion slider_engaged (joint position - start >= 0.05 x (0.45 - (-0.5)) = 0.0475 m); it is informational only. Evaluated after every control step (decimation 1, so after every 1/120 s physics step) on the simulated state; no hold time is required. The episode terminates at the first step where it holds. Otherwise it is truncated by the time limit: episode_length_s = 26 s, i.e. max_episode_length = 3120 control steps; AM-Bench raises the time-out when episode_length_buf >= max_episode_length - 1, i.e. at the 3119th step.+The episode **ends by itself** at the first control step where the check holds (success; rows after it are never+executed), or when the task's episode length of **26 s** runs out (a failure: AM-Bench's time-out ends the episode+at control step 3119). Isaac Lab resets the scene inside the step that ends an episode, so after it `s.state()`,+`s.objects()` and the cameras show the start again; `s.status()` keeps the outcome and the end state's hash.++## Deliverable+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed+open-loop from the same initial state in two fresh processes and scored 1 if the task succeeds in both replays and both+end in the same state, else 0. Also leave the script that produced it at `/app/output/gen.py`. Save a working trajectory+as soon as you have one and overwrite it as you improve it: whatever is in `/app/output/` when the time is up is graded.+The file holds `task` and `actions`, a (T, 8) float array of at most **8,000 rows** (one per control step); anything else+(another shape, NaN, more rows, a file that is not such an npz) scores 0.++## Tooling (already installed; run `python` from any directory)+```python+from rcb_ambench import Session+s = Session(instance="/app/instance.json") # ~2-6 min: launches Isaac Sim, builds the scene, resets to the frozen instance+ # (no cameras, as the grader; Session(..., cameras=True) to look: see below)+s.reset() # back to the frozen instance (the seeded reset; as often as you like)+s.step(row) # one control step (1/120 s): row = 8 values (below); True once the episode is over+s.hold_action() # a row that keeps the current end-effector target and gripper command+s.status() # {'success', 'done', 'end_reason', 'control_steps', 'sim_time_s', 'episode_length_s', 'state_sha', ...}+s.state() # privileged: AM-Bench's own observation of the task (robot, end effector, task objects, goal)+s.objects() # every task object and fixture: pose (xyz + quaternion wxyz), velocities, joint state+s.proprio() # the robot: base and end-effector poses and velocities, gripper width, arm joints, current command+s.actions() # (T, 8) rows executed since the last reset: the trajectory of this episode+s.replay(actions) # reset, run the rows open-loop until the episode ends, return status (+ executed_rows)+s.save_trajectory(actions, "/app/output/trajectory.npz")+s.render_frame("ee_camera") # cameras=True only: RGB uint8 (384, 384, 3) at the end effector, or "base_camera" (on the airframe, looking forward)+s.start_video("/app/output/try.mp4"); ...; s.stop_video() # cameras=True only: film the steps in between (both cameras side by side)+s.env # the Isaac Lab environment itself (AM-Bench's source is in /opt/ambench: read-only reference)+```+The tooling is deliberately thin: the environment's own action, its state and its cameras. Reaching, pressing, pushing,+turning and throwing are yours to build. Isaac Sim runs once per process, and only the first episode of a process is+guaranteed to be bit-identical to a fresh process's: after changes, check your trajectory with the grader's CLI.+**Cameras.** The robot's two onboard cameras exist only in a `Session(..., cameras=True)` (decided once per process). With+them, Isaac renders every step and that makes PhysX's results depend on timing: two runs of the same rows can part after a+few hundred steps. The grader replays without cameras, where a fresh process reproduces a trajectory bit for bit, so use+the cameras to look and check every trajectory with the CLI below.++The grader replays in two fresh processes; each is exactly this CLI (a fresh process, so run it to self-check):+`python /opt/tools/rcb_ambench.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`+(`... film --instance ... --traj ... --video out.mp4` films the rows with the cameras on: an illustration, not a verdict).++## Conventions+- World frame: metres, z up, the ground is the plane z = 0; positions are relative to the environment's origin (the+ tooling and the actions use the same origin); quaternions are **wxyz**.+- Action row (8 values per control step), AM-Bench's absolute end-effector pose action: the target position of the+ end-effector link (x, y, z, m) and its target orientation (qw, qx, qy, qz, in AM-Bench's command frame of the end+ effector: `s.proprio()["command"]` and `hold_action()` give the current target in the same convention), then the gripper+ command (-1 = closed .. +1 = open). Every step, AM-Bench's floating-base inverse kinematics turns the target into an+ airframe pose and arm joint targets, its PID controller turns the airframe pose into the six rotor thrusts, and the arm+ joints track their targets.+- Control and physics run at 120 Hz (one physics step per row). There is no step budget: the time limit (`## Time limit`)+ is your only budget; an episode lasts at most 26 s of simulated time.+- One `Session` per process (Isaac Sim launches once, then the scene builds: ~2-6 min, the upper end on a busy host).+ Physics is PhysX on the **GPU** (about 10-15 control steps per second of wall time). One Isaac process takes up to+ ~13 GiB of memory and ~6.5 GiB of GPU memory: run at most two at once. Do not call `s.close()` before writing every+ output.++## External material+You may install packages you need (pip, apt). Please solve the task yourself: do not look up or download a solution to it, such as this benchmark's own source code, published or reference solutions, recorded demonstrations, or policies trained for it. This is an honour rule; trials are reviewed. The network reaches your model's API and the package registries (PyPI, Debian / Ubuntu archives) only.++## Resource limits+Limits for the whole trial, all its processes together (every simulator you start included): at most **16 GiB of GPU memory**, **28 GiB of memory**, **512 processes** and **20 GiB** of new files under `/app`, `/tmp` and `/root`. GPU memory counts what a process reserves (JAX, for example, reserves most of the card unless told not to). These limits may be enforced (from protocol v1.2 on): when enforcement is on, exceeding one for 60 s within any 2 minutes, or a process killed for lack of memory, ends the trial as a failure (reward 0), whatever the deliverable. A monitor outside your container measures every few seconds; the current values are in `/run/rcb-limits/usage.json`. When enforcement is on and GPU memory goes above 1.5 times its limit, the monitor also kills the process holding the most of it at once, to protect the machine; that alone does not fail the trial. CPU is capped at 8 cores for your container; the cap only slows you down.++## Time limit+You have 3600 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task.++This is wall-clock time from the start of your session; the time a simulator takes to start counts. When it is up you are stopped without warning and only what is in `/app/output/` at that moment is graded, so save a deliverable as soon as you have one and overwrite it whenever you have a better one. Your session started when you received this task: run `date` now, and again before you decide that time is short; work out the time left from those readings, never from a guess. Installing packages is not cheating (`## External material` above).diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/solution/oracle.py b/tasks/ambench-push-slider-fahexa-i00-privileged/solution/oracle.pynew file mode 100644index 0000000000..b695ebf3dc--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/solution/oracle.py@@ -0,0 +1,15 @@+"""Oracle (privileged): run the reference rows on the frozen instance with the agent's tooling, stopping at the end of+the episode, and save the rows that ran as /app/output/trajectory.npz."""+import json, os+import numpy as np+from rcb_ambench import Session+HERE = os.path.dirname(os.path.abspath(__file__))+s = Session(instance="/app/instance.json", strict=True)+for row in np.load(os.path.join(HERE, "oracle_actions.npy")).astype(np.float64): # the process's first episode, as the grader's+ if s.step(row):+ break+st = {**s.status(), "executed_rows": s.n_steps}+s.save_trajectory(s.actions(), "/app/output/trajectory.npz", meta={"source": "reference rows"})+print(json.dumps({k: st[k] for k in ("success", "end_reason", "executed_rows", "sim_time_s", "state_sha")}), flush=True)+s.close()+os._exit(0 if st["success"] else 1)diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/solution/oracle_actions.npy b/tasks/ambench-push-slider-fahexa-i00-privileged/solution/oracle_actions.npynew file mode 100644index 0000000000..d986cbad88Binary files /dev/null and b/tasks/ambench-push-slider-fahexa-i00-privileged/solution/oracle_actions.npy differdiff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/solution/solve.sh b/tasks/ambench-push-slider-fahexa-i00-privileged/solution/solve.shnew file mode 100755index 0000000000..365611c270--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/solution/solve.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Oracle: replay the reference rows (solution/oracle_actions.npy: AM-Bench's scripted expert for this task, run on this+# instance and recorded, then 2 s of holding its last command; the expert reads the simulator's true state) through the+# agent's own tooling, and save the trajectory. The rows live in solution/ only (never in the agent image, which has no+# expert).+set -e+mkdir -p /app/output+cp /solution/oracle.py /app/output/gen.py+python /solution/oracle.pydiff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/task.toml b/tasks/ambench-push-slider-fahexa-i00-privileged/task.tomlnew file mode 100644index 0000000000..892cf17faa--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/task.toml@@ -0,0 +1,97 @@+# Generated by scripts/ambench/mk_tasks.py -- edit the template or scripts/ambench/descr/, not this.+schema_version = "1.3"+artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]++[task]+name = "robot-coding-bench/ambench-push-slider-fahexa-i00-privileged"+description = "AM-Bench PushSlider-Am-FAHexa-Abs-PID-Direct-v0 (a fully actuated hexarotor with a 4-joint arm and a two-finger gripper, Isaac Lab / Isaac Sim 5.1): produce one replayable trajectory of AM-Bench's absolute end-effector pose actions at 120 Hz. Task: A wall stands in front of the hovering aerial manipulator, with a horizontal slider mounted on its front face: a straight rail about 1 m long and a red knob that slides along it. The knob starts at the rail's left end (as seen from the robot facing the wall) and must be pushed along the rail until it is within 5 cm of the right end of its travel, i.e. at least 0.95 m along its 1 m travel. Frozen scene instance: AM-Bench's seeded reset, seed 0; graded by AM-Bench's own success check in two fresh-process replays."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "ambench", "aerial-manipulation", "isaac-lab", "isaac-sim", "hexarotor", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "ambench" # AM-Bench @ 60bf5b7 on Isaac Lab @ f4aa17f / Isaac Sim 5.1 (PhysX on the GPU, RTX rendering)+robot = "ambench-fahexa"+family = "push_slider_fahexa"+mode = "privileged"+dynamics = "static" # scene dynamics (docs/PROTOCOL.md §2.14): scripts/task_dynamics.toml+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 2.0++[metadata.resources]+# minimum compute to run this task (docs/PROTOCOL.md §2.9)+min_cpus = 8.0+min_memory_gb = 16.0+min_gpu_memory_gb = 8.0+gpu_required = true+gpu_class = "rtx"+recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"+verifier_min_cpus = 4.0+verifier_min_memory_gb = 16.0+verifier_min_gpu_memory_gb = 8.0+measured = "freezing the instances and three oracle trials (RTX 4090, 2026-10-13/14, docker stats and nvidia-smi every 10 s, rcb_monitor): a camera-free Isaac process (the default Session, the grader's replays) peaks at 2.9 GiB of memory and 3.2 GiB of GPU memory (oracle trials: 2.8 / 3.1); with the two onboard cameras on (Session(cameras=True), the verifier's filmed illustration) 13.2 GiB and 6.4 GiB; 6-10 cores while Isaac starts, about 1.5 after; the verifier runs one process at a time. The minimums cover one camera-on process"++[metadata.resources.limits]+# agent-phase limits in GiB (docs/PROTOCOL.md §2.10); scope: trial = every container, agent = the agent's container;+# enforced from protocol v1.2 when RCB_LIMITS_ENFORCE=1 (a violation fails the trial), otherwise recorded only+scope = "trial"+max_gpu_memory_gb = 16.0+max_memory_gb = 28.0+max_processes = 512+max_disk_gb = 20.0+disk_paths = ["/app", "/tmp", "/root"]+disk_exclude = []+sustain_sec = 60.0+window_sec = 120.0+trial_max_gpu_memory_gb = 16.0+trial_max_memory_gb = 28.0+measured = "a camera-on Isaac process peaks at 13.2 GiB of memory and 6.4 GiB of GPU memory, a camera-free one at 2.9 / 3.2 (the rule's measurement); the agent may run two processes at once (a Session and the replay CLI): at most 26.4 GiB, 12.8 GiB -> memory 28 GiB (the container's cap 34 GiB: 34 / 1.2 >= 28), GPU 16 GiB (at least 16 for Isaac Sim); processes 512 and disk 20 GiB: design defaults, not yet measured"++[metadata.resources.caps]+# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)+main = { cpus = 8.0, memory_gb = 34.0, pids = 16384 }++[metadata.seeds]+# the instances this task may run from (docs/PROTOCOL.md §2.13): the default, the ones a runner may draw+# from (a list, { from = A, to = B } or "any"), and the ones the reference solution under solution/ is for+default = 0+allowed = [0]+oracle = [0]++[verifier]+timeout_sec = 9000.0 # tests/grade.py's limits for the longest episode (3120 rows: 1500 s + 3120 / 4 = 2280 s per+ # process): two fresh-process replays (no cameras), one rerun of a replay that died early,+ # and the filmed illustration (cameras on; its time-out only costs the video); measured:+ # 1.5-6 min of Isaac start, the verifier's first one compiling its shaders, + 9-12 control+ # steps/s+environment_mode = "separate" # verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then+network_mode = "no-network" # Isaac Sim starts and renders offline: every asset is in the image (images/ambench/web_assets.txt)++# Resource limits (docs/PROTOCOL.md §2.10): seal the monitor's record first, before any other sidecar ends the episode.+[[verifier.collect]]+service = "rcb_monitor"+command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90"+timeout_sec = 120++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 8+memory_mb = 24576++[agent]+timeout_sec = 3600.0 # the agent's cutoff: scripts/task_cutoffs.toml, the one table (written by normalize, PROTOCOL §2.12)+# AM-Bench's scripted experts and its datasets are public upstream, so the agent reaches the model APIs and the package+# registries, nothing else (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com", "pypi.org", "files.pythonhosted.org", "deb.debian.org", "security.debian.org", "archive.ubuntu.com", "security.ubuntu.com", "snapshot.ubuntu.com"]++[environment]+build_timeout_sec = 3600.0+cpus = 8+memory_mb = 34816++[verifier.env]+RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/Dockerfile b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/Dockerfilenew file mode 100644index 0000000000..32e315793a--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/Dockerfile@@ -0,0 +1,11 @@+# Separate verifier sandbox (PROTOCOL §4): the same simulator image with the verifier's own copies of the tooling and the+# frozen instance baked in. Nothing the agent did in its container reaches this one -- Harbor uploads only the declared+# artifacts (/app/output/), so a patched success check or a swapped interpreter in the agent container cannot influence+# the verdict.+FROM ghcr.io/mll-lab-nu/eai-ambench:0.1.0+COPY grade.py instance.json rcb_ambench.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /tests+# resource limits: the verifier step and its copy of the limits (docs/PROTOCOL.md §2.10) # rcb-monitor+COPY rcb_limits.py rcb_limits.json /tests/diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/docker-compose.yaml b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/docker-compose.yamlnew file mode 100644index 0000000000..eaf78d197a--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/docker-compose.yaml@@ -0,0 +1,16 @@+# The verifier replays in Isaac Sim, which needs the GPU. Its Kit cache is a TRUSTED volume: Isaac keeps generated+# Python there that Kit imports at startup, so a cache the agent could write must never reach the grader.+services:+ main:+ shm_size: "8gb"+ volumes:+ - rcb_ambench_cache_trusted:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+volumes:+ rcb_ambench_cache_trusted:diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/grade.py b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/grade.pynew file mode 100644index 0000000000..580b28b5aa--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/grade.py@@ -0,0 +1,177 @@+"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2++Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a+human-viewable video /logs/verifier/replay.mp4 (the robot's two onboard cameras) plus replay.last.png, filmed AFTER the+verdict by a third process (`rcb_ambench.py film`) with the cameras on: camera rendering makes the physics timing-dependent,+so the verdict replays run without cameras and the video is an illustration that never enters the reward.+Replays `--repeat` times, each in its own FRESH process (`rcb_ambench.py replay`, no cameras), so fresh process == fresh+process is the determinism check. Success requires every replay to complete the task (AM-Bench's own `_get_success`) AND all+final-state hashes to agree, so a lucky non-deterministic run cannot pass. The frozen scene rebuilt here from+tests/instance.json must also match the recorded one (`instance_ok`: the exact state hash of the seeded reset).++Whose failure a 0 is (every path writes a reward; `deterministic`, `grader_error` and `infra_error` are always present):+- the agent's: no file (`missing_trajectory`), another task's trajectory (`wrong_task`), a file that is not a+ trajectory (`bad_trajectory`: not an npz, no `task` / `actions` entry, pickled or object arrays, the wrong shape, NaN/inf,+ more than MAX_STEPS rows), or a replay that does not complete the task or is not deterministic;+- the verifier's (`grader_error` = 1, with `infra_error` = 1: no verdict on the agent): a replay process that ends+ without a result (Isaac died) or runs out of its time limit (`replay_timed_out`), the rebuilt frozen scene not matching+ the recorded instance (`instance_ok` = 0: the host, not the trajectory), or any other error in this script.+"""+from __future__ import annotations+import argparse, json, os, subprocess, sys, time, traceback+import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+# Wall-clock limit of ONE replay process, scaled with the rows that can run (time limits only; the verdict rules do not+# depend on them). The grader accepts up to MAX_STEPS rows, but the episode ends at the task's own episode length (10-26 s+# here: at most 3119 control steps), so later rows never run. Measured on an RTX 4090 host: Isaac start + scene build+# 1.5-6 min (the upper end with other Isaac jobs on the GPU; the verifier's first start also compiles the shaders into its+# fresh Kit cache), then about 12 control steps/s (the onboard cameras render every step). The allowance is REPLAY_STARTUP_S for the start plus the runnable rows at REPLAY_MIN_RATE control steps/s+# (the same for the filming process, whose time-out only ends the video), never below REPLAY_FLOOR_S; task.toml's+# [verifier] timeout_sec fits the three processes of the longest episode, so a replay that is too slow ends here with a+# written reward (`replay_timed_out`), never with Harbor killing the verifier.+REPLAY_FLOOR_S, REPLAY_STARTUP_S, REPLAY_MIN_RATE = 1800.0, 1500.0, 4.0+++def replay_timeout(n_steps: int) -> float:+ return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_steps / REPLAY_MIN_RATE)+++def load_trajectory(path: str, family: str, action_dim: int, max_steps: int):+ """(actions, None), or (None, reward fields) when the file is not a gradable trajectory of this task. Everything+ here is the agent's deliverable: a file that cannot be read is the agent's 0 (`bad_trajectory`), not a grader error."""+ try:+ d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...+ task = str(d["task"]) # no `task` entry: KeyError; an object array: ValueError+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable trajectory: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if task != family:+ return None, {"wrong_task": 1}+ try:+ acts = np.asarray(d["actions"], dtype=np.float32)+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable actions: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if acts.ndim != 2 or acts.shape[1] != action_dim or acts.shape[0] > max_steps or not np.all(np.isfinite(acts)):+ return None, {"bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0}+ return acts, None+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)+ ap.add_argument("--no-video", action="store_true"); ap.add_argument("--video-fps", type=int, default=30)+ a = ap.parse_args()+ # Agent interaction cost from the tooling's append-only log (whole debugging history, not just the deliverable).+ # The log lives in the agent's container, so these fields are SELF-REPORTED cost accounting, not evidence+ # (agent_cost_self_reported = 1); the parser must survive any content the agent may have written there.+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ try:+ with open("/app/output/rcb_session_log.jsonl") as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000: break+ try:+ e = json.loads(line); ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start": cost["agent_sessions"] += 1+ elif ev == "reset": cost["agent_resets"] += 1+ elif ev == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ elif ev == "record": cost["agent_records"] += 1+ elif ev == "replay": cost["agent_replays"] += 1+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict+ continue+ except Exception: # noqa: BLE001+ pass+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions must not be counted+ ZERO = {"success": 0, "deterministic": 0, "grader_error": 0, "infra_error": 0} # an early exit: the agent's 0+ ERR = {"success": 0, "deterministic": 0, "grader_error": 1, "infra_error": 1} # no verdict on the agent+ if not os.path.isfile(a.traj):+ write(False, {**ZERO, "missing_trajectory": 1, **cost}); return 0+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling+ from rcb_ambench import MAX_STEPS, ACTION_DIM+ inst = json.load(open(a.instance)); env_id = inst["env_id"]+ acts, bad = load_trajectory(a.traj, env_id, ACTION_DIM, MAX_STEPS)+ if bad is not None:+ write(False, {**ZERO, **bad, **cost}); return 0+ tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_ambench.py")+ runnable = min(int(acts.shape[0]), int(round(float(inst["episode_length_s"]) * int(inst["control_hz"]))))+ t0 = time.time(); runs = []+ attempts = []+ for i in range(a.repeat):+ limit = replay_timeout(runnable)+ for attempt in (1, 2): # a process that died without a result (Isaac) is run once more+ cmd = [sys.executable, tool, "replay", "--instance", a.instance, "--traj", a.traj]+ try:+ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})+ stdout, run = p.stdout, {"error": f"replay process rc={p.returncode}"}+ except subprocess.TimeoutExpired as exc:+ print(f"[grade] replay {i + 1} exceeded its {limit:.0f} s limit ({len(acts)} rows)", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_timed_out": 1, "replay_timeout_s": round(limit, 1), "n_actions": int(len(acts)),+ "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ for line in stdout.splitlines(): # the last JSON object the CLI printed (Isaac writes to stdout too)+ if line.startswith("{"):+ try:+ v = json.loads(line)+ except ValueError:+ continue+ if isinstance(v, dict): run = v+ print(f"[grade] replay {i + 1}: {json.dumps(run)[:800]}", file=sys.stderr, flush=True)+ attempts.append(attempt)+ if "replays" in run or attempt == 2:+ break+ print(f"[grade] replay {i + 1} gave no result ({run.get('error')}): running it once more", file=sys.stderr, flush=True)+ runs.append(run)+ outs = [(r.get("replays") or [{}])[0] for r in runs]+ if any("error" in r or not o for r, o in zip(runs, outs)):+ print(f"[grade] a replay process gave no result: {[r.get('error') for r in runs]}", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_failed": 1, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ replay_wall = round(time.time() - t0, 1)+ all_success = all(o.get("success") for o in outs)+ deterministic = len({o.get("state_sha") for o in outs}) == 1+ instance_ok = all(bool(r.get("instance_matches")) for r in runs)+ ok = all_success and deterministic and instance_ok+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "replays": len(outs),+ "sim_steps": int(outs[0].get("control_steps") or 0), "sim_time_s": float(outs[0].get("sim_time_s") or 0.0),+ "timed_out": int(outs[-1].get("end_reason") == "timeout"),+ "replay_wall_s": replay_wall, "replay_timeout_s": round(limit, 1),+ # the rebuilt frozen scene is not the recorded one: this host, not the trajectory (no verdict on the agent)+ "grader_error": int(not instance_ok), "infra_error": int(not instance_ok),+ "replay_retries": int(sum(x - 1 for x in attempts)), **cost}+ write(ok, out) # the verdict is written before the illustration is filmed+ film = {}+ if not a.no_video: # an illustration after the verdict: never part of the reward+ try:+ p = subprocess.run([sys.executable, tool, "film", "--instance", a.instance, "--traj", a.traj, "--video",+ os.path.join(LOG_DIR, "replay.mp4"), "--fps", str(a.video_fps)], stdout=subprocess.PIPE,+ stderr=sys.stderr, text=True, timeout=replay_timeout(runnable), env={**os.environ, "RCB_SESSION_LOG": ""})+ for line in p.stdout.splitlines():+ if line.startswith("{"):+ try:+ film = json.loads(line).get("film") or {}+ except (ValueError, AttributeError):+ pass+ except Exception as exc: # noqa: BLE001 — a time-out or a crash only costs the video+ print(f"[grade] filming failed: {exc!r}"[:300], file=sys.stderr, flush=True)+ out.update(video_rendered=int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))),+ video_episode_success=int(bool(film.get("success"))))+ write(ok, out)+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {**ERR, **cost})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/instance.json b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/instance.jsonnew file mode 100644index 0000000000..9f8b869b25--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "PushSlider-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "PushSlider",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 26.0,+ "initial_sha": "9bd26bad8cd1cd81a7fcc11043a996206a0550e7e00f2a74253efe1822ced584"+}diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_ambench.py b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_ambench.pynew file mode 100644index 0000000000..623d3522c8--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_ambench.py@@ -0,0 +1,451 @@+"""+rcb_ambench.py — task-local tooling for AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0: aerial manipulation on+Isaac Lab / Isaac Sim 5.1): frozen task instance, privileged state, action recording, fresh-process replay. Same shape as+the other benchmarks' rcb_<bench>.py.++Concepts+--------+instance : one AM-Bench environment (a task with one robot and controller profile, e.g.+ PressButton-Am-FAHexa-Abs-PID-Direct-v0) and the seed of its reset (instance.json). AM-Bench draws the task's+ variation (where the button, the slider, the valve or the ball is) from the seeded reset; `initial_sha` is the+ hash of the start it builds, which every replay checks (`instance_matches`).+trajectory : the (T, 8) actions handed to the environment, one row per control step (120 Hz: one physics step of 1/120 s):+ the absolute end-effector target, position x y z (m, world frame, relative to the environment's origin),+ orientation as a unit quaternion w x y z, and the gripper command (-1 = closed .. +1 = open). AM-Bench's own+ low-level controller (the profile's PID) and floating-base inverse kinematics turn it into rotor thrusts and arm+ joint targets inside every step. Physics is PhysX on the GPU: a fresh process replays the same rows to the+ same state (the first episode of a process; later resets in the same process need not be bit-identical)+ WITHOUT the onboard cameras. With them (`Session(cameras=True)`), the per-step rendering makes PhysX's results+ depend on timing (measured: two fresh replays of the same rows part after a few hundred steps), so the+ grader, the reference recordings and a default Session run without them; cameras are for looking only.+success : AM-Bench's own `_get_success` of the task (its `terminated` signal); the episode ends at the first control step+ where it holds, or at the task's episode length (a time-out, not a success). Rows after the end never run.+ Isaac Lab resets the scene inside the step that ends an episode; the tooling keeps the end state's hash+ (taken just before that reset) as the episode's `state_sha`.+ RotateValve: the valve's `base_to_shaft` joint has no limits, and PhysX reports an articulation's unlimited+ revolute joint wrapped into [-pi, pi] (omni.physx 107.3, Isaac Sim 5.1), so AM-Bench's check `joint_pos >=+ 17/18 pi` would also pass a counter-clockwise turn of 190 degrees. The tooling gives that task's+ `_get_success` the unwrapped angle instead: the sum of the joint's per-step changes since the reset (one+ physics step moves it at most 5 rad/s / 120 Hz, far less than pi), so only the clockwise turn the+ instruction asks for counts. Physics, states and hashes are unchanged; the episode just does not end on a+ wrapped reading.++CLI+---+ python rcb_ambench.py replay --instance instance.json --traj traj.npz # one fresh-process replay (the grader's, no cameras)+ python rcb_ambench.py film --instance instance.json --traj traj.npz --video replay.mp4 # the same rows with the cameras on,+ filmed: an illustration only (camera rendering changes the numerics; never a verdict)+ python rcb_ambench.py make-instance --env-id <id> --seed 0 --out instance.json+ python rcb_ambench.py run-actions --instance instance.json --actions actions.npy --out traj.npz+"""+from __future__ import annotations++import os+for _k, _v in (("OMNI_KIT_ACCEPT_EULA", "YES"), ("ACCEPT_EULA", "Y"), ("OMNI_KIT_ALLOW_ROOT", "1"), ("PYTHONUNBUFFERED", "1"),+ ("JAX_PLATFORMS", "cpu")):+ os.environ.setdefault(_k, _v)++import argparse+import hashlib+import json+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++ACTION_DIM = 8+CONTROL_HZ = 120+MAX_STEPS = 8000 # a technical cap above every task's episode length (at most 60 s = 7200 steps)+ASSET_ROOT = "/opt/isaac-assets/Assets/Isaac/5.1" # baked web assets (images/ambench/web_assets.txt)+CAMERAS = ("ee_camera", "base_camera") # the robot profile's onboard cameras (384 x 384 RGB), only with Session(cameras=True)+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")+_APP = None+_APP_CAMERAS = False+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG) or ".", exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ev": ev, "t": round(time.time(), 3), "pid": os.getpid(), **kw}) + "\n")+ except OSError:+ pass+++def _launch_app(cameras: bool = False):+ """Isaac Sim, headless, the asset root pointed at the baked copies (no network needed); rendering only with cameras.+ Once per process: the first Session decides."""+ global _APP, _APP_CAMERAS+ if _APP is not None and cameras != _APP_CAMERAS:+ raise RuntimeError(f"this process launched Isaac Sim with cameras={_APP_CAMERAS}: one Session (one setting) per process")+ if _APP is None:+ _APP_CAMERAS = cameras+ from isaaclab.app import AppLauncher+ ns = argparse.Namespace()+ p = argparse.ArgumentParser(); AppLauncher.add_app_launcher_args(p)+ ns = p.parse_args([])+ ns.headless = True; ns.enable_cameras = bool(cameras); ns.device = "cuda:0"+ ns.kit_args = f"--/persistent/isaac/asset_root/cloud={ASSET_ROOT}"+ _APP = AppLauncher(ns).app+ return _APP+++def load_instance(instance) -> dict:+ return instance if isinstance(instance, dict) else json.loads(Path(instance).read_text())+++def _np(x) -> np.ndarray:+ return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)+++class Session:+ """One AM-Bench environment of one frozen instance. One per process (Isaac Sim runs once per process)."""++ def __init__(self, instance="/app/instance.json", *, strict: bool = False, cameras: bool = False):+ _launch_app(cameras)+ self.cameras = bool(cameras)+ import gymnasium as gym+ import torch+ import ambench.tasks # noqa: F401 (registers the environments)+ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg+ self.torch = torch+ self.instance = load_instance(instance)+ I = self.instance+ self.env_id, self.seed = I["env_id"], int(I["seed"])+ cfg = parse_env_cfg(self.env_id, device="cuda:0", num_envs=1)+ cfg.seed = self.seed+ if not self.cameras: # the robot profile's onboard cameras (and any scene camera) are not built: no rendering+ cfg.robot_profile.ee_camera = None; cfg.robot_profile.base_camera = None; cfg.scene_camera_cfg = None+ self.env = gym.make(self.env_id, cfg=cfg).unwrapped+ # Isaac Lab resets an environment whose episode ended INSIDE that step (DirectRLEnv.step -> _reset_idx), so after the+ # last step the scene is already the next episode's start: keep the end state's hash, taken just before that reset+ self._in_step = False; self.end_sha = None+ _reset_idx = self.env._reset_idx++ def _keep_end_state(env_ids, _reset_idx=_reset_idx):+ if self._in_step:+ self.end_sha = self.state_sha()+ return _reset_idx(env_ids)+ self.env._reset_idx = _keep_end_state+ self._valve = None+ if self.env_id.startswith("RotateValve-"):+ self._unwrap_valve_angle()+ self.n_resets = 0; self.n_steps_total = 0; self.n_clipped = 0+ self._video = None+ self.reset()+ self.initial_sha = self.state_sha()+ want = I.get("initial_sha")+ self.instance_matches = want is None or want == self.initial_sha+ if strict and not self.instance_matches:+ raise RuntimeError(f"the rebuilt scene differs from the frozen instance: {self.initial_sha} != {want}")+ _slog("session_start", env_id=self.env_id, instance_matches=self.instance_matches, cameras=self.cameras)++ # ------------------------------------------------------------------ episode+ def reset(self) -> None:+ """Back to the frozen instance (the seeded reset). Only the first episode of a process is guaranteed bit-identical+ to a fresh process's: check a trajectory with the `replay` CLI."""+ with self.torch.inference_mode(): # as step(): after a step Isaac Lab's buffers are inference tensors+ self.obs, _ = self.env.reset(seed=self.seed)+ self.end_sha = None+ if self._valve is not None:+ self._valve.update(prev=None, angle=None) # the joint is back at 0 rad: count from here+ self.rows: list[np.ndarray] = []+ self.done = False; self.succeeded = False; self.timed_out = False+ self.n_resets += 1+ if self.n_resets > 1:+ _slog("reset", env_id=self.env_id)++ def _unwrap_valve_angle(self) -> None:+ """RotateValve's success on the valve's unwrapped angle (see the module docstring): AM-Bench's `_get_success`, with+ the joint position PhysX reports in [-pi, pi] replaced by the sum of its per-step changes since the reset."""+ env, torch, v = self.env, self.torch, {"prev": None, "angle": None}+ self._valve = v+ two_pi = 2.0 * float(np.pi)++ def _get_success():+ q = env.valve_object.data.joint_pos[:, env.valve_joint_idx].clone()+ if v["prev"] is None: # the first step after a reset, from 0 rad (|q| < 0.05 rad here)+ angle = q+ else:+ angle = v["angle"] + torch.remainder(q - v["prev"] + np.pi, two_pi) - np.pi+ v.update(prev=q, angle=angle)+ target = env.cfg.valve_target_angle+ rotated = angle >= target+ return rotated, {"valve_engaged": angle >= env.cfg.valve_engagement_ratio * target, "valve_rotated": rotated}+ env._get_success = _get_success++ def valve_angle(self) -> float | None:+ """RotateValve: the valve's unwrapped angle in rad since the reset (positive = clockwise from the robot's side),+ what the success check reads; None in other tasks or before the first step."""+ if self._valve is None or self._valve["angle"] is None:+ return None+ return float(_np(self._valve["angle"]).reshape(-1)[0])++ @property+ def n_steps(self) -> int:+ return len(self.rows)++ def clip(self, row) -> tuple[np.ndarray, int]:+ a = np.asarray(row, dtype=np.float64).reshape(-1).copy()+ if a.size != ACTION_DIM or not np.all(np.isfinite(a)):+ raise ValueError(f"an action row has {ACTION_DIM} finite values (x y z qw qx qy qz gripper), got {a.size}")+ n = 0+ g = float(np.clip(a[7], -1.0, 1.0)); n += int(g != a[7]); a[7] = g+ if float(np.linalg.norm(a[3:7])) < 1e-9: # passed on as it is (AM-Bench's controller takes the quaternion it gets)+ raise ValueError("the action's quaternion has zero length")+ return a, n++ def step(self, row) -> bool:+ """One control step (1/120 s). Returns True when the episode is over; a step after that executes nothing."""+ if self.done:+ return True+ a, n = self.clip(row)+ self.n_clipped += n+ t = self.torch.as_tensor(a, dtype=self.torch.float32, device=self.env.device).reshape(1, ACTION_DIM)+ self._in_step = True+ try:+ with self.torch.inference_mode():+ self.obs, _, term, trunc, _ = self.env.step(t)+ finally:+ self._in_step = False+ self.rows.append(a)+ self.n_steps_total += 1+ self.succeeded = bool(_np(term).reshape(-1)[0])+ self.timed_out = bool(_np(trunc).reshape(-1)[0]) and not self.succeeded+ self.done = self.succeeded or self.timed_out or self.n_steps >= MAX_STEPS+ if self._video is not None:+ self._video_add()+ return self.done++ def success(self) -> bool:+ return self.succeeded++ def end_reason(self) -> str | None:+ if self.succeeded:+ return "success"+ if self.timed_out:+ return "timeout"+ return "step_cap" if self.done else None++ def hold_action(self) -> np.ndarray:+ """A row that keeps the current end-effector target and gripper command."""+ cp = self.env.control_pipeline+ pos = _np(cp.ee_cmd_pos_w[0] - self.env.scene.env_origins[0]).astype(np.float64)+ quat = _np(cp.ee_cmd_quat_w[0]).astype(np.float64)+ g = self.rows[-1][7] if self.rows else 1.0+ return np.r_[pos, quat, g]++ def status(self) -> dict[str, Any]:+ # state_sha: the episode's end state once it is over (taken before Isaac Lab's reset), else the current state+ return {"success": self.succeeded, "done": self.done, "end_reason": self.end_reason(), "control_steps": self.n_steps,+ "sim_time_s": round(self.n_steps / CONTROL_HZ, 4), "episode_length_s": float(self.env.cfg.episode_length_s),+ "resets": self.n_resets, "state_sha": self.end_sha if (self.done and self.end_sha) else self.state_sha()}++ def actions(self) -> np.ndarray:+ return np.asarray(self.rows, dtype=np.float64).reshape(-1, ACTION_DIM)++ def record_start(self) -> None:+ self.reset()++ def record_stop(self) -> np.ndarray:+ return self.actions()++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ self.reset()+ for row in A:+ if self.step(row):+ break+ _slog("replay", env_id=self.env_id, rows=int(len(A)), executed=self.n_steps)+ return {**self.status(), "executed_rows": self.n_steps}++ def save_trajectory(self, actions, path="/app/output/trajectory.npz", meta: dict | None = None) -> None:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, task=np.array(self.env_id), actions=A, meta=np.array(json.dumps(meta or {})))++ # ------------------------------------------------------------------ state (privileged)+ def state_sha(self) -> str:+ """sha256 over every articulation's and rigid object's root state, joint positions and velocities."""+ m = hashlib.sha256()+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name in sorted(group):+ d = group[name].data+ for t in (d.root_state_w, getattr(d, "joint_pos", None), getattr(d, "joint_vel", None)):+ if t is not None:+ m.update(name.encode()); m.update(_np(t).tobytes())+ return m.hexdigest()++ def state(self) -> dict[str, Any]:+ """Privileged observation of the task (AM-Bench's own `policy` observation: robot, end effector, task objects and+ goal positions, relative to the environment's origin)."""+ obs = self.obs["policy"][0] if isinstance(self.obs.get("policy"), list) else self.obs.get("policy")+ return {k: _np(v).reshape(-1).tolist() for k, v in (obs.items() if isinstance(obs, dict) else [])}++ def objects(self) -> dict[str, dict]:+ """Every articulation (but the robot) and rigid object of the scene: root pose (wxyz) and velocities, joint state."""+ out, o = {}, _np(self.env.scene.env_origins[0])+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name, obj in group.items():+ if name == "robot":+ continue+ rs = _np(obj.data.root_state_w[0])+ ent = {"position": (rs[:3] - o).tolist(), "orientation_wxyz": rs[3:7].tolist(), "velocity": rs[7:10].tolist(),+ "angular_velocity": rs[10:13].tolist()}+ if getattr(obj.data, "joint_pos", None) is not None:+ ent["joint_pos"] = _np(obj.data.joint_pos[0]).tolist(); ent["joint_names"] = list(obj.joint_names)+ out[name] = ent+ return out++ def proprio(self) -> dict[str, Any]:+ """The robot's own state: base and end-effector poses (world, relative to the env origin; wxyz) and velocities, the+ gripper opening and the arm joints, the current end-effector command."""+ e = self.env; o = _np(e.scene.env_origins[0])+ base = _np(e.robot.data.body_link_state_w[0, e.base_link_idx]); ee = _np(e.robot.data.body_link_state_w[0, e.ee_link_idx])+ jp = _np(e.robot.data.joint_pos[0]); jv = _np(e.robot.data.joint_vel[0])+ return {"base_pose": np.r_[base[:3] - o, base[3:7]].tolist(), "base_vel": base[7:13].tolist(),+ "ee_pose": np.r_[ee[:3] - o, ee[3:7]].tolist(), "ee_vel": ee[7:13].tolist(),+ "gripper_width": float(np.sum(jp[e.gripper_joint_ids])),+ "arm_joint_pos": jp[e.arm_joint_ids].tolist(), "arm_joint_vel": jv[e.arm_joint_ids].tolist(),+ "command": self.hold_action().tolist()}++ # ------------------------------------------------------------------ cameras+ def render_frame(self, camera: str = "ee_camera") -> np.ndarray:+ """RGB uint8 (384, 384, 3) of the robot's onboard camera `ee_camera` (at the end effector) or `base_camera` (on the+ airframe, looking forward), as of the last step. Only in a Session(cameras=True): the cameras render every step+ and that makes the physics timing-dependent, so check what you find there with the replay CLI (no cameras)."""+ if not self.cameras:+ raise RuntimeError("no cameras in this Session: start the process with Session(..., cameras=True) to look "+ "(its numerics differ from the grader's camera-free replay; check trajectories with the CLI)")+ cam = getattr(self.env, camera, None)+ if cam is None:+ raise KeyError(f"no camera {camera!r}; cameras: {[c for c in CAMERAS if getattr(self.env, c, None) is not None]}")+ return _np(cam.data.output["rgb"][0])[..., :3].astype(np.uint8)++ def start_video(self, path, fps: int = 30, camera: str = "ee_camera") -> None:+ import imageio.v2 as imageio+ self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),+ "every": max(1, round(CONTROL_HZ / fps)), "camera": camera, "path": str(path)}+ self._video_add(force=True)++ def _video_add(self, force: bool = False) -> None:+ v = self._video+ if force or self.n_steps % v["every"] == 0 or self.done:+ frames = [self.render_frame(c) for c in CAMERAS if getattr(self.env, c, None) is not None]+ v["w"].append_data(np.concatenate(frames, axis=1))++ def stop_video(self):+ v, self._video = self._video, None+ if v:+ v["w"].close()+ return v["path"]++ def close(self) -> None:+ _slog("session_end", env_id=self.env_id, sim_steps=self.n_steps_total, resets=self.n_resets)+ try:+ self.env.close()+ except Exception: # noqa: BLE001+ pass+++def load_trajectory(path, env_id: str) -> np.ndarray:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != env_id:+ raise ValueError(f"trajectory is for {str(d['task'])!r}, not {env_id!r}")+ A = np.asarray(d["actions"], dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != ACTION_DIM or A.shape[0] > MAX_STEPS or not np.all(np.isfinite(A)):+ raise ValueError(f"actions must be a finite (T, {ACTION_DIM}) array with T <= {MAX_STEPS}, got {list(A.shape)}")+ return A+++def _replay_rows(s: "Session", A: np.ndarray) -> dict:+ for row in A: # the process's first episode+ if s.step(row):+ break+ res = s.status()+ return {**{k: res[k] for k in ("success", "state_sha", "end_reason", "control_steps", "sim_time_s")}, "executed_rows": s.n_steps}+++def _cli_replay(a) -> int:+ """The grader's replay: a fresh process, no cameras (bit-reproducible), the process's first episode."""+ t0 = time.time()+ s = Session(a.instance)+ out: dict[str, Any] = {"task": s.env_id, "instance_matches": bool(s.instance_matches), "initial_sha": s.initial_sha}+ try:+ A = load_trajectory(a.traj, s.env_id)+ except Exception as exc: # noqa: BLE001+ out["error"] = f"bad trajectory: {exc!r}"[:300]; print(json.dumps(out), flush=True); return 2+ out["replays"] = [_replay_rows(s, A)]+ out["n_actions"] = int(len(A)); out["replay_wall_s"] = round(time.time() - t0, 2)+ print(json.dumps(out), flush=True)+ s.close()+ return 0+++def _cli_film(a) -> int:+ """An illustration, never a verdict: the rows with the onboard cameras on, filmed (both cameras side by side) plus the+ last end-effector frame. Camera rendering makes the physics timing-dependent, so this episode may end differently."""+ t0 = time.time()+ s = Session(a.instance, cameras=True)+ A = load_trajectory(a.traj, s.env_id)+ s.start_video(a.video, fps=a.fps)+ res = _replay_rows(s, A)+ s.stop_video()+ from PIL import Image+ Image.fromarray(s.render_frame("ee_camera")).save(str(Path(a.video).with_suffix(".last.png")))+ print(json.dumps({"task": s.env_id, "film": res, "video": a.video, "film_wall_s": round(time.time() - t0, 2)}), flush=True)+ s.close()+ return 0+++def _cli_make_instance(a) -> int:+ inst = {"env_id": a.env_id, "seed": int(a.seed)}+ s = Session(inst)+ inst.update({"task": a.env_id.split("-")[0], "action_dim": ACTION_DIM, "control_hz": CONTROL_HZ,+ "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha})+ Path(a.out).write_text(json.dumps(inst, indent=1) + "\n")+ print(json.dumps({"env_id": a.env_id, "initial_sha": s.initial_sha}), flush=True)+ s.close()+ return 0+++def _cli_run_actions(a) -> int:+ s = Session(a.instance, strict=True)+ for row in np.load(a.actions): # the process's first episode (no second reset), as the grader's+ if s.step(row):+ break+ res = {**s.status(), "executed_rows": s.n_steps}+ s.save_trajectory(s.actions(), a.out, meta={"source": "reference rows"})+ print(json.dumps({k: res[k] for k in ("success", "end_reason", "state_sha", "control_steps", "executed_rows", "sim_time_s")}), flush=True)+ s.close()+ return 0+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay"); r.add_argument("--instance", required=True); r.add_argument("--traj", required=True)+ f = sub.add_parser("film"); f.add_argument("--instance", required=True); f.add_argument("--traj", required=True)+ f.add_argument("--video", required=True); f.add_argument("--fps", type=int, default=30)+ m = sub.add_parser("make-instance"); m.add_argument("--env-id", required=True); m.add_argument("--seed", type=int, default=0); m.add_argument("--out", required=True)+ x = sub.add_parser("run-actions"); x.add_argument("--instance", required=True); x.add_argument("--actions", required=True); x.add_argument("--out", required=True)+ a = ap.parse_args(argv)+ global SESSION_LOG+ SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "") # the CLI logs nothing unless asked+ try:+ rc = {"replay": _cli_replay, "film": _cli_film, "make-instance": _cli_make_instance, "run-actions": _cli_run_actions}[a.cmd](a)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error: report it and leave at once+ import traceback+ traceback.print_exc(); rc = 3+ sys.stdout.flush(); sys.stderr.flush()+ os._exit(rc) # Isaac Sim's shutdown can hang or crash after the result line; the result is printed+++if __name__ == "__main__":+ main()diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_limits.json b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_limits.jsonnew file mode 100644index 0000000000..55fc2d02e6--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_limits.json@@ -0,0 +1,33 @@+{+ "caps": {+ "main": {+ "cpus": 8.0,+ "memory_gb": 34.0,+ "pids": 16384+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": true,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 16.0,+ "max_memory_gb": 28.0,+ "max_processes": 512,+ "mode": "privileged",+ "scope": "trial",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "ambench-push-slider-fahexa-i00-privileged",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 16.0,+ "trial_max_memory_gb": 28.0,+ "window_sec": 120.0+}diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_limits.py b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_limits.pynew file mode 100644index 0000000000..a979bcdaff--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/rcb_limits.py@@ -0,0 +1,457 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/ambench-push-slider-fahexa-i00-privileged/tests/test.sh b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/test.shnew file mode 100755index 0000000000..de3fc8c811--- /dev/null+++ b/tasks/ambench-push-slider-fahexa-i00-privileged/tests/test.sh@@ -0,0 +1,11 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, see docs/PROTOCOL.md).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resource limits, after the grader (docs/PROTOCOL.md §2.10)+p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # the agent's files are untrusted input: no link out of /app/output, no FIFO or device (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \+ 2> /logs/verifier/grade.logdiff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/README.md b/tasks/ambench-rotate-valve-fahexa-i00-privileged/README.mdnew file mode 100644index 0000000000..f63c52e784--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/README.md@@ -0,0 +1,65 @@+# ambench-rotate-valve-fahexa-i00-privileged++| | |+|---|---|+| Benchmark | AM-Bench |+| Mode | privileged |+| Twin | — (privileged only) |+| Simulator / robot | `ambench` / `ambench-fahexa` |+| Family / instance | `rotate_valve_fahexa` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-ambench:0.1.0` |++## Task+A valve is mounted on the front face of a wall in front of the hovering aerial manipulator: a large red wheel disc on a short shaft, with a handle bar sticking out of the disc's face toward the robot. Turn the valve: rotate the wheel clockwise, as seen from the robot's side of the wall, by at least 170 degrees from its starting angle. AM-Bench environment `RotateValve-Am-FAHexa-Abs-PID-Direct-v0` (the fully actuated hexarotor with the 4-joint arm, AM-Bench's PID+controller), its seeded reset with seed 0. The deliverable is one replayable trajectory of AM-Bench's absolute+end-effector pose actions at 120 Hz (`/app/output/trajectory.npz`), graded by AM-Bench's own success check within the+task's episode length of 20 s.++## Difficulty+The wheel has to be turned through nearly half a revolution in one direction against joint damping and friction, in front of a wall, and the valve's place on the wall changes per instance. Privileged mode gives the full simulator state, unlimited resets and self-replay; the tooling offers only the+environment's own action, its state and its cameras.++## Reference solution+`solution/oracle_actions.npy` (run by `solution/oracle.py` through the agent's own tooling): AM-Bench's scripted expert+for this task, run on this instance (it reads the simulator's state in closed loop) and recorded, followed by 2 s of+holding its last command (a replay may succeed a step later than the live run; rows after success never run). The image+has no expert (`images/ambench/Dockerfile` removes them), and the agent's network reaches only the+model APIs and the package registries.++## Verification+`tests/grade.py` in a separate sandbox: two replays, each in a fresh process, from the verifier's own copy of the instance+(`tests/instance.json`; the rebuilt start is checked against its hash); pass iff AM-Bench's success check holds in both+and both end in the same state (`deterministic`); the replays run without the onboard cameras (camera rendering makes+GPU PhysX timing-dependent). `/logs/verifier/replay.mp4` (both onboard cameras) is filmed by a third process after the+verdict, an illustration only. Oracle:+success at control step 1002 (8.35 s simulated) in both fresh-process replays, which end in the same+state (hash `1b976104a88384d6`). `nop`: no trajectory, reward 0.++## Compute resources+Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]` in `task.toml`). The agent phase counts every container of the trial at once (the agent's, and in standard modes the simulator sidecar); the verifier phase runs after it.++| | Agent phase | Verifier |+|---|---|---|+| CPU cores | 8 | 4 |+| Memory | 16 GB | 16 GB |+| GPU memory | 8 GB | 8 GB |++- GPU: required, an RTX-class NVIDIA GPU (ray-tracing cores, for Isaac Sim / Omniverse RTX rendering); recommended: L40S 48GB / L4 24GB / RTX 4090 24GB.+- Measured: freezing the instances and three oracle trials (RTX 4090, 2026-10-13/14, docker stats and nvidia-smi every 10 s, rcb_monitor): a camera-free Isaac process (the default Session, the grader's replays) peaks at 2.9 GiB of memory and 3.2 GiB of GPU memory (oracle trials: 2.8 / 3.1); with the two onboard cameras on (Session(cameras=True), the verifier's filmed illustration) 13.2 GiB and 6.4 GiB; 6-10 cores while Isaac starts, about 1.5 after; the verifier runs one process at a time. The minimums cover one camera-on process+- Limits in the agent phase (docs/PROTOCOL.md §2.10; `[metadata.resources.limits]`, shown to the agent in `instruction.md`; always measured and reported, and exceeding one fails the trial only when the run sets `RCB_LIMITS_ENFORCE=1`), every container of the trial: 16 GiB GPU memory, 28 GiB memory, 512 processes, 20 GiB of new files under `/app`, `/tmp`, `/root`; 60 s within 120 s. Expected peak of the whole trial: 16 GiB GPU memory, 28 GiB memory. Limits measured: a camera-on Isaac process peaks at 13.2 GiB of memory and 6.4 GiB of GPU memory, a camera-free one at 2.9 / 3.2 (the rule's measurement); the agent may run two processes at once (a Session and the replay CLI): at most 26.4 GiB, 12.8 GiB -> memory 28 GiB (the container's cap 34 GiB: 34 / 1.2 >= 28), GPU 16 GiB (at least 16 for Isaac Sim); processes 512 and disk 20 GiB: design defaults, not yet measured.++## Details+| | |+|---|---|+| Upstream | AM-Bench @ 60bf5b7 (Apache-2.0) on Isaac Lab @ f4aa17f / Isaac Sim 5.1.0; Pyroki @ 2eafc99, acados @ fa0af20 |+| Instance | `RotateValve-Am-FAHexa-Abs-PID-Direct-v0`, seed 0, the start's state hash in `environment/instance.json` (`initial_sha` 5bfceb57120de994) |+| Actions | 8 per control step (1/120 s): end-effector target x y z (m), quaternion w x y z (command frame), gripper (-1 closed .. +1 open) |+| Physics | PhysX on the GPU (dt 1/120 s, one physics step per action); bit-reproducible in a fresh process without the onboard cameras, which the tooling builds only on request (`Session(cameras=True)`) |+| Image | built locally on every host (`images/ambench/BUILD_ONLY`: it contains Isaac Sim); needs an RTX-class NVIDIA GPU (`environment/docker-compose.yaml`) |+| Budget | the agent's cutoff is the `Agent time budget` row above (`scripts/task_cutoffs.toml`); out of it, every Python process pays ~2-6 min of Isaac Sim launch + scene build |++### Provenance+Generated by `scripts/ambench/mk_tasks.py` from `scripts/ambench/descr/rotate_valve_fahexa.json` and `scripts/ambench/frozen/rotate_valve-i00/`+(the expert's rows recorded with `scripts/ambench/freeze.py` in `ghcr.io/mll-lab-nu/eai-ambench:0.1.0`; provenance in `scripts/ambench/instances.json`).diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/Dockerfile b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/Dockerfilenew file mode 100644index 0000000000..9050e5343c--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# Base image = AM-Bench (scrubbed: no scripted experts) + Isaac Lab / Isaac Sim 5.1 + the baked web assets (see+# images/ambench/; BUILD_ONLY). Everything task-specific is copied here; no reference solution is in the image.+FROM ghcr.io/mll-lab-nu/eai-ambench:0.1.0+COPY instance.json /app/instance.json+COPY rcb_ambench.py /opt/tools/rcb_ambench.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/docker-compose.yaml b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/docker-compose.yamlnew file mode 100644index 0000000000..ef66ce03c4--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/docker-compose.yaml@@ -0,0 +1,47 @@+# Isaac Sim needs an RTX-class NVIDIA GPU even headless. Harbor's local docker sandbox rejects [environment].gpus, but+# merging this onto the main service passes the device through. Isaac's shader/extension cache gets a volume for the+# trial, named after the trial's compose project (no fixed name: side-by-side trials must not share it; Harbor's+# teardown, `compose down --volumes`, deletes it): every trial compiles its shaders once (~2 min).+services:+ main:+ pids_limit: 16384 # rcb-monitor+ shm_size: "8gb"+ volumes:+ - rcb_limits:/run/rcb-limits:ro # rcb-monitor+ - rcb_ambench_cache:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+ # >>> rcb_monitor (resource limits monitor, docs/PROTOCOL.md §2.10; generated by scripts/rcb_monitor/inject.py)+ rcb_monitor:+ image: ghcr.io/mll-lab-nu/eai-monitor:0.1.0@sha256:f2c910f53f79c2bfa4a71298b10c78383cae3afc40720ca562cc845b8d20fb0c+ pid: host # sees every container's processes (and NVML's host PIDs); the agent never sees it+ cgroup: host # reads each container's own cgroup (memory, OOM kills, caps)+ network_mode: none+ cap_add: [SYS_PTRACE] # reads /proc of processes running as other users+ cpus: 0.5+ mem_limit: 256m+ pids_limit: 64+ restart: on-failure:3+ working_dir: /var/rcb-monitor+ volumes:+ - ./rcb_monitor:/opt/rcb_monitor:ro+ - rcb_limits:/run/rcb-limits+ environment:+ RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} # 1: stop the agent at a confirmed violation, and fail the trial+ command: ["python3", "/opt/rcb_monitor/monitor.py", "run"]+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+ # <<< rcb_monitor+volumes:+ rcb_limits: # rcb-monitor+ rcb_ambench_cache:diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/instance.json b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/instance.jsonnew file mode 100644index 0000000000..b8a814fc56--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "RotateValve-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "RotateValve",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 20.0,+ "initial_sha": "5bfceb57120de994dca306348115910883573b611ba46d353754ebd5911772d4"+}diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_ambench.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_ambench.pynew file mode 100644index 0000000000..623d3522c8--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_ambench.py@@ -0,0 +1,451 @@+"""+rcb_ambench.py — task-local tooling for AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0: aerial manipulation on+Isaac Lab / Isaac Sim 5.1): frozen task instance, privileged state, action recording, fresh-process replay. Same shape as+the other benchmarks' rcb_<bench>.py.++Concepts+--------+instance : one AM-Bench environment (a task with one robot and controller profile, e.g.+ PressButton-Am-FAHexa-Abs-PID-Direct-v0) and the seed of its reset (instance.json). AM-Bench draws the task's+ variation (where the button, the slider, the valve or the ball is) from the seeded reset; `initial_sha` is the+ hash of the start it builds, which every replay checks (`instance_matches`).+trajectory : the (T, 8) actions handed to the environment, one row per control step (120 Hz: one physics step of 1/120 s):+ the absolute end-effector target, position x y z (m, world frame, relative to the environment's origin),+ orientation as a unit quaternion w x y z, and the gripper command (-1 = closed .. +1 = open). AM-Bench's own+ low-level controller (the profile's PID) and floating-base inverse kinematics turn it into rotor thrusts and arm+ joint targets inside every step. Physics is PhysX on the GPU: a fresh process replays the same rows to the+ same state (the first episode of a process; later resets in the same process need not be bit-identical)+ WITHOUT the onboard cameras. With them (`Session(cameras=True)`), the per-step rendering makes PhysX's results+ depend on timing (measured: two fresh replays of the same rows part after a few hundred steps), so the+ grader, the reference recordings and a default Session run without them; cameras are for looking only.+success : AM-Bench's own `_get_success` of the task (its `terminated` signal); the episode ends at the first control step+ where it holds, or at the task's episode length (a time-out, not a success). Rows after the end never run.+ Isaac Lab resets the scene inside the step that ends an episode; the tooling keeps the end state's hash+ (taken just before that reset) as the episode's `state_sha`.+ RotateValve: the valve's `base_to_shaft` joint has no limits, and PhysX reports an articulation's unlimited+ revolute joint wrapped into [-pi, pi] (omni.physx 107.3, Isaac Sim 5.1), so AM-Bench's check `joint_pos >=+ 17/18 pi` would also pass a counter-clockwise turn of 190 degrees. The tooling gives that task's+ `_get_success` the unwrapped angle instead: the sum of the joint's per-step changes since the reset (one+ physics step moves it at most 5 rad/s / 120 Hz, far less than pi), so only the clockwise turn the+ instruction asks for counts. Physics, states and hashes are unchanged; the episode just does not end on a+ wrapped reading.++CLI+---+ python rcb_ambench.py replay --instance instance.json --traj traj.npz # one fresh-process replay (the grader's, no cameras)+ python rcb_ambench.py film --instance instance.json --traj traj.npz --video replay.mp4 # the same rows with the cameras on,+ filmed: an illustration only (camera rendering changes the numerics; never a verdict)+ python rcb_ambench.py make-instance --env-id <id> --seed 0 --out instance.json+ python rcb_ambench.py run-actions --instance instance.json --actions actions.npy --out traj.npz+"""+from __future__ import annotations++import os+for _k, _v in (("OMNI_KIT_ACCEPT_EULA", "YES"), ("ACCEPT_EULA", "Y"), ("OMNI_KIT_ALLOW_ROOT", "1"), ("PYTHONUNBUFFERED", "1"),+ ("JAX_PLATFORMS", "cpu")):+ os.environ.setdefault(_k, _v)++import argparse+import hashlib+import json+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++ACTION_DIM = 8+CONTROL_HZ = 120+MAX_STEPS = 8000 # a technical cap above every task's episode length (at most 60 s = 7200 steps)+ASSET_ROOT = "/opt/isaac-assets/Assets/Isaac/5.1" # baked web assets (images/ambench/web_assets.txt)+CAMERAS = ("ee_camera", "base_camera") # the robot profile's onboard cameras (384 x 384 RGB), only with Session(cameras=True)+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")+_APP = None+_APP_CAMERAS = False+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG) or ".", exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ev": ev, "t": round(time.time(), 3), "pid": os.getpid(), **kw}) + "\n")+ except OSError:+ pass+++def _launch_app(cameras: bool = False):+ """Isaac Sim, headless, the asset root pointed at the baked copies (no network needed); rendering only with cameras.+ Once per process: the first Session decides."""+ global _APP, _APP_CAMERAS+ if _APP is not None and cameras != _APP_CAMERAS:+ raise RuntimeError(f"this process launched Isaac Sim with cameras={_APP_CAMERAS}: one Session (one setting) per process")+ if _APP is None:+ _APP_CAMERAS = cameras+ from isaaclab.app import AppLauncher+ ns = argparse.Namespace()+ p = argparse.ArgumentParser(); AppLauncher.add_app_launcher_args(p)+ ns = p.parse_args([])+ ns.headless = True; ns.enable_cameras = bool(cameras); ns.device = "cuda:0"+ ns.kit_args = f"--/persistent/isaac/asset_root/cloud={ASSET_ROOT}"+ _APP = AppLauncher(ns).app+ return _APP+++def load_instance(instance) -> dict:+ return instance if isinstance(instance, dict) else json.loads(Path(instance).read_text())+++def _np(x) -> np.ndarray:+ return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)+++class Session:+ """One AM-Bench environment of one frozen instance. One per process (Isaac Sim runs once per process)."""++ def __init__(self, instance="/app/instance.json", *, strict: bool = False, cameras: bool = False):+ _launch_app(cameras)+ self.cameras = bool(cameras)+ import gymnasium as gym+ import torch+ import ambench.tasks # noqa: F401 (registers the environments)+ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg+ self.torch = torch+ self.instance = load_instance(instance)+ I = self.instance+ self.env_id, self.seed = I["env_id"], int(I["seed"])+ cfg = parse_env_cfg(self.env_id, device="cuda:0", num_envs=1)+ cfg.seed = self.seed+ if not self.cameras: # the robot profile's onboard cameras (and any scene camera) are not built: no rendering+ cfg.robot_profile.ee_camera = None; cfg.robot_profile.base_camera = None; cfg.scene_camera_cfg = None+ self.env = gym.make(self.env_id, cfg=cfg).unwrapped+ # Isaac Lab resets an environment whose episode ended INSIDE that step (DirectRLEnv.step -> _reset_idx), so after the+ # last step the scene is already the next episode's start: keep the end state's hash, taken just before that reset+ self._in_step = False; self.end_sha = None+ _reset_idx = self.env._reset_idx++ def _keep_end_state(env_ids, _reset_idx=_reset_idx):+ if self._in_step:+ self.end_sha = self.state_sha()+ return _reset_idx(env_ids)+ self.env._reset_idx = _keep_end_state+ self._valve = None+ if self.env_id.startswith("RotateValve-"):+ self._unwrap_valve_angle()+ self.n_resets = 0; self.n_steps_total = 0; self.n_clipped = 0+ self._video = None+ self.reset()+ self.initial_sha = self.state_sha()+ want = I.get("initial_sha")+ self.instance_matches = want is None or want == self.initial_sha+ if strict and not self.instance_matches:+ raise RuntimeError(f"the rebuilt scene differs from the frozen instance: {self.initial_sha} != {want}")+ _slog("session_start", env_id=self.env_id, instance_matches=self.instance_matches, cameras=self.cameras)++ # ------------------------------------------------------------------ episode+ def reset(self) -> None:+ """Back to the frozen instance (the seeded reset). Only the first episode of a process is guaranteed bit-identical+ to a fresh process's: check a trajectory with the `replay` CLI."""+ with self.torch.inference_mode(): # as step(): after a step Isaac Lab's buffers are inference tensors+ self.obs, _ = self.env.reset(seed=self.seed)+ self.end_sha = None+ if self._valve is not None:+ self._valve.update(prev=None, angle=None) # the joint is back at 0 rad: count from here+ self.rows: list[np.ndarray] = []+ self.done = False; self.succeeded = False; self.timed_out = False+ self.n_resets += 1+ if self.n_resets > 1:+ _slog("reset", env_id=self.env_id)++ def _unwrap_valve_angle(self) -> None:+ """RotateValve's success on the valve's unwrapped angle (see the module docstring): AM-Bench's `_get_success`, with+ the joint position PhysX reports in [-pi, pi] replaced by the sum of its per-step changes since the reset."""+ env, torch, v = self.env, self.torch, {"prev": None, "angle": None}+ self._valve = v+ two_pi = 2.0 * float(np.pi)++ def _get_success():+ q = env.valve_object.data.joint_pos[:, env.valve_joint_idx].clone()+ if v["prev"] is None: # the first step after a reset, from 0 rad (|q| < 0.05 rad here)+ angle = q+ else:+ angle = v["angle"] + torch.remainder(q - v["prev"] + np.pi, two_pi) - np.pi+ v.update(prev=q, angle=angle)+ target = env.cfg.valve_target_angle+ rotated = angle >= target+ return rotated, {"valve_engaged": angle >= env.cfg.valve_engagement_ratio * target, "valve_rotated": rotated}+ env._get_success = _get_success++ def valve_angle(self) -> float | None:+ """RotateValve: the valve's unwrapped angle in rad since the reset (positive = clockwise from the robot's side),+ what the success check reads; None in other tasks or before the first step."""+ if self._valve is None or self._valve["angle"] is None:+ return None+ return float(_np(self._valve["angle"]).reshape(-1)[0])++ @property+ def n_steps(self) -> int:+ return len(self.rows)++ def clip(self, row) -> tuple[np.ndarray, int]:+ a = np.asarray(row, dtype=np.float64).reshape(-1).copy()+ if a.size != ACTION_DIM or not np.all(np.isfinite(a)):+ raise ValueError(f"an action row has {ACTION_DIM} finite values (x y z qw qx qy qz gripper), got {a.size}")+ n = 0+ g = float(np.clip(a[7], -1.0, 1.0)); n += int(g != a[7]); a[7] = g+ if float(np.linalg.norm(a[3:7])) < 1e-9: # passed on as it is (AM-Bench's controller takes the quaternion it gets)+ raise ValueError("the action's quaternion has zero length")+ return a, n++ def step(self, row) -> bool:+ """One control step (1/120 s). Returns True when the episode is over; a step after that executes nothing."""+ if self.done:+ return True+ a, n = self.clip(row)+ self.n_clipped += n+ t = self.torch.as_tensor(a, dtype=self.torch.float32, device=self.env.device).reshape(1, ACTION_DIM)+ self._in_step = True+ try:+ with self.torch.inference_mode():+ self.obs, _, term, trunc, _ = self.env.step(t)+ finally:+ self._in_step = False+ self.rows.append(a)+ self.n_steps_total += 1+ self.succeeded = bool(_np(term).reshape(-1)[0])+ self.timed_out = bool(_np(trunc).reshape(-1)[0]) and not self.succeeded+ self.done = self.succeeded or self.timed_out or self.n_steps >= MAX_STEPS+ if self._video is not None:+ self._video_add()+ return self.done++ def success(self) -> bool:+ return self.succeeded++ def end_reason(self) -> str | None:+ if self.succeeded:+ return "success"+ if self.timed_out:+ return "timeout"+ return "step_cap" if self.done else None++ def hold_action(self) -> np.ndarray:+ """A row that keeps the current end-effector target and gripper command."""+ cp = self.env.control_pipeline+ pos = _np(cp.ee_cmd_pos_w[0] - self.env.scene.env_origins[0]).astype(np.float64)+ quat = _np(cp.ee_cmd_quat_w[0]).astype(np.float64)+ g = self.rows[-1][7] if self.rows else 1.0+ return np.r_[pos, quat, g]++ def status(self) -> dict[str, Any]:+ # state_sha: the episode's end state once it is over (taken before Isaac Lab's reset), else the current state+ return {"success": self.succeeded, "done": self.done, "end_reason": self.end_reason(), "control_steps": self.n_steps,+ "sim_time_s": round(self.n_steps / CONTROL_HZ, 4), "episode_length_s": float(self.env.cfg.episode_length_s),+ "resets": self.n_resets, "state_sha": self.end_sha if (self.done and self.end_sha) else self.state_sha()}++ def actions(self) -> np.ndarray:+ return np.asarray(self.rows, dtype=np.float64).reshape(-1, ACTION_DIM)++ def record_start(self) -> None:+ self.reset()++ def record_stop(self) -> np.ndarray:+ return self.actions()++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ self.reset()+ for row in A:+ if self.step(row):+ break+ _slog("replay", env_id=self.env_id, rows=int(len(A)), executed=self.n_steps)+ return {**self.status(), "executed_rows": self.n_steps}++ def save_trajectory(self, actions, path="/app/output/trajectory.npz", meta: dict | None = None) -> None:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, task=np.array(self.env_id), actions=A, meta=np.array(json.dumps(meta or {})))++ # ------------------------------------------------------------------ state (privileged)+ def state_sha(self) -> str:+ """sha256 over every articulation's and rigid object's root state, joint positions and velocities."""+ m = hashlib.sha256()+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name in sorted(group):+ d = group[name].data+ for t in (d.root_state_w, getattr(d, "joint_pos", None), getattr(d, "joint_vel", None)):+ if t is not None:+ m.update(name.encode()); m.update(_np(t).tobytes())+ return m.hexdigest()++ def state(self) -> dict[str, Any]:+ """Privileged observation of the task (AM-Bench's own `policy` observation: robot, end effector, task objects and+ goal positions, relative to the environment's origin)."""+ obs = self.obs["policy"][0] if isinstance(self.obs.get("policy"), list) else self.obs.get("policy")+ return {k: _np(v).reshape(-1).tolist() for k, v in (obs.items() if isinstance(obs, dict) else [])}++ def objects(self) -> dict[str, dict]:+ """Every articulation (but the robot) and rigid object of the scene: root pose (wxyz) and velocities, joint state."""+ out, o = {}, _np(self.env.scene.env_origins[0])+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name, obj in group.items():+ if name == "robot":+ continue+ rs = _np(obj.data.root_state_w[0])+ ent = {"position": (rs[:3] - o).tolist(), "orientation_wxyz": rs[3:7].tolist(), "velocity": rs[7:10].tolist(),+ "angular_velocity": rs[10:13].tolist()}+ if getattr(obj.data, "joint_pos", None) is not None:+ ent["joint_pos"] = _np(obj.data.joint_pos[0]).tolist(); ent["joint_names"] = list(obj.joint_names)+ out[name] = ent+ return out++ def proprio(self) -> dict[str, Any]:+ """The robot's own state: base and end-effector poses (world, relative to the env origin; wxyz) and velocities, the+ gripper opening and the arm joints, the current end-effector command."""+ e = self.env; o = _np(e.scene.env_origins[0])+ base = _np(e.robot.data.body_link_state_w[0, e.base_link_idx]); ee = _np(e.robot.data.body_link_state_w[0, e.ee_link_idx])+ jp = _np(e.robot.data.joint_pos[0]); jv = _np(e.robot.data.joint_vel[0])+ return {"base_pose": np.r_[base[:3] - o, base[3:7]].tolist(), "base_vel": base[7:13].tolist(),+ "ee_pose": np.r_[ee[:3] - o, ee[3:7]].tolist(), "ee_vel": ee[7:13].tolist(),+ "gripper_width": float(np.sum(jp[e.gripper_joint_ids])),+ "arm_joint_pos": jp[e.arm_joint_ids].tolist(), "arm_joint_vel": jv[e.arm_joint_ids].tolist(),+ "command": self.hold_action().tolist()}++ # ------------------------------------------------------------------ cameras+ def render_frame(self, camera: str = "ee_camera") -> np.ndarray:+ """RGB uint8 (384, 384, 3) of the robot's onboard camera `ee_camera` (at the end effector) or `base_camera` (on the+ airframe, looking forward), as of the last step. Only in a Session(cameras=True): the cameras render every step+ and that makes the physics timing-dependent, so check what you find there with the replay CLI (no cameras)."""+ if not self.cameras:+ raise RuntimeError("no cameras in this Session: start the process with Session(..., cameras=True) to look "+ "(its numerics differ from the grader's camera-free replay; check trajectories with the CLI)")+ cam = getattr(self.env, camera, None)+ if cam is None:+ raise KeyError(f"no camera {camera!r}; cameras: {[c for c in CAMERAS if getattr(self.env, c, None) is not None]}")+ return _np(cam.data.output["rgb"][0])[..., :3].astype(np.uint8)++ def start_video(self, path, fps: int = 30, camera: str = "ee_camera") -> None:+ import imageio.v2 as imageio+ self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),+ "every": max(1, round(CONTROL_HZ / fps)), "camera": camera, "path": str(path)}+ self._video_add(force=True)++ def _video_add(self, force: bool = False) -> None:+ v = self._video+ if force or self.n_steps % v["every"] == 0 or self.done:+ frames = [self.render_frame(c) for c in CAMERAS if getattr(self.env, c, None) is not None]+ v["w"].append_data(np.concatenate(frames, axis=1))++ def stop_video(self):+ v, self._video = self._video, None+ if v:+ v["w"].close()+ return v["path"]++ def close(self) -> None:+ _slog("session_end", env_id=self.env_id, sim_steps=self.n_steps_total, resets=self.n_resets)+ try:+ self.env.close()+ except Exception: # noqa: BLE001+ pass+++def load_trajectory(path, env_id: str) -> np.ndarray:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != env_id:+ raise ValueError(f"trajectory is for {str(d['task'])!r}, not {env_id!r}")+ A = np.asarray(d["actions"], dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != ACTION_DIM or A.shape[0] > MAX_STEPS or not np.all(np.isfinite(A)):+ raise ValueError(f"actions must be a finite (T, {ACTION_DIM}) array with T <= {MAX_STEPS}, got {list(A.shape)}")+ return A+++def _replay_rows(s: "Session", A: np.ndarray) -> dict:+ for row in A: # the process's first episode+ if s.step(row):+ break+ res = s.status()+ return {**{k: res[k] for k in ("success", "state_sha", "end_reason", "control_steps", "sim_time_s")}, "executed_rows": s.n_steps}+++def _cli_replay(a) -> int:+ """The grader's replay: a fresh process, no cameras (bit-reproducible), the process's first episode."""+ t0 = time.time()+ s = Session(a.instance)+ out: dict[str, Any] = {"task": s.env_id, "instance_matches": bool(s.instance_matches), "initial_sha": s.initial_sha}+ try:+ A = load_trajectory(a.traj, s.env_id)+ except Exception as exc: # noqa: BLE001+ out["error"] = f"bad trajectory: {exc!r}"[:300]; print(json.dumps(out), flush=True); return 2+ out["replays"] = [_replay_rows(s, A)]+ out["n_actions"] = int(len(A)); out["replay_wall_s"] = round(time.time() - t0, 2)+ print(json.dumps(out), flush=True)+ s.close()+ return 0+++def _cli_film(a) -> int:+ """An illustration, never a verdict: the rows with the onboard cameras on, filmed (both cameras side by side) plus the+ last end-effector frame. Camera rendering makes the physics timing-dependent, so this episode may end differently."""+ t0 = time.time()+ s = Session(a.instance, cameras=True)+ A = load_trajectory(a.traj, s.env_id)+ s.start_video(a.video, fps=a.fps)+ res = _replay_rows(s, A)+ s.stop_video()+ from PIL import Image+ Image.fromarray(s.render_frame("ee_camera")).save(str(Path(a.video).with_suffix(".last.png")))+ print(json.dumps({"task": s.env_id, "film": res, "video": a.video, "film_wall_s": round(time.time() - t0, 2)}), flush=True)+ s.close()+ return 0+++def _cli_make_instance(a) -> int:+ inst = {"env_id": a.env_id, "seed": int(a.seed)}+ s = Session(inst)+ inst.update({"task": a.env_id.split("-")[0], "action_dim": ACTION_DIM, "control_hz": CONTROL_HZ,+ "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha})+ Path(a.out).write_text(json.dumps(inst, indent=1) + "\n")+ print(json.dumps({"env_id": a.env_id, "initial_sha": s.initial_sha}), flush=True)+ s.close()+ return 0+++def _cli_run_actions(a) -> int:+ s = Session(a.instance, strict=True)+ for row in np.load(a.actions): # the process's first episode (no second reset), as the grader's+ if s.step(row):+ break+ res = {**s.status(), "executed_rows": s.n_steps}+ s.save_trajectory(s.actions(), a.out, meta={"source": "reference rows"})+ print(json.dumps({k: res[k] for k in ("success", "end_reason", "state_sha", "control_steps", "executed_rows", "sim_time_s")}), flush=True)+ s.close()+ return 0+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay"); r.add_argument("--instance", required=True); r.add_argument("--traj", required=True)+ f = sub.add_parser("film"); f.add_argument("--instance", required=True); f.add_argument("--traj", required=True)+ f.add_argument("--video", required=True); f.add_argument("--fps", type=int, default=30)+ m = sub.add_parser("make-instance"); m.add_argument("--env-id", required=True); m.add_argument("--seed", type=int, default=0); m.add_argument("--out", required=True)+ x = sub.add_parser("run-actions"); x.add_argument("--instance", required=True); x.add_argument("--actions", required=True); x.add_argument("--out", required=True)+ a = ap.parse_args(argv)+ global SESSION_LOG+ SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "") # the CLI logs nothing unless asked+ try:+ rc = {"replay": _cli_replay, "film": _cli_film, "make-instance": _cli_make_instance, "run-actions": _cli_run_actions}[a.cmd](a)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error: report it and leave at once+ import traceback+ traceback.print_exc(); rc = 3+ sys.stdout.flush(); sys.stderr.flush()+ os._exit(rc) # Isaac Sim's shutdown can hang or crash after the result line; the result is printed+++if __name__ == "__main__":+ main()diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/limits.json b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/limits.jsonnew file mode 100644index 0000000000..6d37d09d1f--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/limits.json@@ -0,0 +1,33 @@+{+ "caps": {+ "main": {+ "cpus": 8.0,+ "memory_gb": 34.0,+ "pids": 16384+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": true,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 16.0,+ "max_memory_gb": 28.0,+ "max_processes": 512,+ "mode": "privileged",+ "scope": "trial",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "ambench-rotate-valve-fahexa-i00-privileged",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 16.0,+ "trial_max_memory_gb": 28.0,+ "window_sec": 120.0+}diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/monitor.pynew file mode 100644index 0000000000..81fdc91877--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/monitor.py@@ -0,0 +1,966 @@+#!/usr/bin/env python3+"""rcb_monitor: the trusted resource-limits monitor sidecar of every task (docs/PROTOCOL.md §2.10, record rcb-monitor/1).++Runs as the compose service `rcb_monitor` (generated by scripts/rcb_monitor/inject.py): `pid: host`, `cgroup: host`,+`network_mode: none`, CAP_SYS_PTRACE, the task's GPU reservation, its code read-only from the task directory. The agent+cannot see it (another PID namespace), reach it (no network) or write its record (its own file system).++Which containers it watches: the services that mount the trial's beacon volume `rcb_limits` (read-only at+/run/rcb-limits) are in scope, the ones that mount `rcb_observe` are only recorded (the benchmark's own services: the+simulator sidecar of standard modes, RoboPaint's privileged `scorer`). The compose project names both volumes, so they are unique to the trial; the monitor finds the containers as+the mount namespaces whose /run/rcb-limits is the same directory as its own (docker compose exec'd processes included).+A namespace that does not show the beacon is asked again at every tick (a container that is still being set up has the+host's root until its pivot_root: "no" is never remembered); a "yes" is kept only while the process that proved it lives.+A process whose first thread has exited is found through a thread that lives; a zombie counts in its parent's container.++Every tick (5 s; disk every 60 s) it samples, per container and summed over the scope: GPU memory (NVML, per process,+compute and graphics), memory (cgroup anon+shmem when the container has its own cgroup, else PSS anon+shmem), processes+(TGIDs, zombies included), disk growth under the limits' disk_paths in the agent's container (complete walks only, in+slices between the samples), CPU (recorded only). It appends to /var/rcb-monitor/samples.jsonl and+events.jsonl and writes the agent-visible /run/rcb-limits/usage.json.++Kernel OOM kills (`oom` events) are read from each watched container's cgroup `memory.events` by a thread of its own+(OomWatch), many times a second: a kill that takes the container's main process with it ends the container, and compose+restarts it with a new cgroup whose counters start at 0, within milliseconds -- a reading once per tick never sees it.+Every event says whom it hit (`scope`: a container the limits bind, or a benchmark-owned service that is only+recorded) and why (`cause`): "cap" when the container's own `oom` counter rose with it (the kernel says its memory+reached its own cap), else "host" (the host's OOM killer, or an enclosing cgroup's: not this container's doing).+Only a "cap" kill in the scope is a violation (rcb_limits.violations); the verifier step reports the others.++RCB_LIMITS_ENFORCE=1 (run-time switch; compose default 0; 0/1/true/false, anything else is a fatal record): once a+violation is confirmed (rcb_limits.violations, the verifier's own rule) the monitor SIGKILLs every in-scope process+except each container's PID 1, so the agent stops at once and Harbor goes on to collection and the verifier (an agent+killed this way ends like one that exited non-zero). It also protects the host (`emergency_kill` events, never a+violation by themselves): above EMERGENCY_GPU_FACTOR x the GPU-memory limit at one sample it kills the scope's process+that holds the most GPU memory; where the runtime applies no kernel memory cap, it stands in for it and kills the+largest process once the scope is above its declared memory caps.+0: it only records.++ python3 monitor.py run # the service's command+ python3 monitor.py seal --wait 90 # the first sidecar collect hook: seal the record (summary.json), print it+"""+import ctypes+import json+import os+import select+import signal+import stat as stat_mod+import sys+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import rcb_limits # noqa: E402+import selftest # noqa: E402++REC = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+PROC, CGROUP = "/proc", "/sys/fs/cgroup" # module globals: scripts/rcb_monitor/test_monitor.py points them at a fake tree+SCOPE_BEACON, OBSERVE_BEACON = "/run/rcb-limits", "/run/rcb-observe"+LIMITS = os.path.join(HERE, "limits.json")+HZ = os.sysconf("SC_CLK_TCK")+PAGE = os.sysconf("SC_PAGE_SIZE")+GIB = float(2 ** 30)+EMERGENCY_GPU_FACTOR = 1.5 # host protection (enforced runs): above this x the GPU-memory limit at one sample+DISK_SLICE_SEC = 1.5 # of every tick a running disk walk may take (the monitor's CPU cap is half a core)+DISK_WALK_MAX_SEC = 300.0 # a walk not finished by then is partial: a gap in the record, never a baseline+OOM_COLD_SEC = 0.02 # OomWatch: every memory.events is read this often (or at once, when the kernel notifies)+OOM_HOT_SEC = 0.002 # ... and this often for OOM_HOT_FOR_SEC after any of them changed (memory pressure)+OOM_HOT_FOR_SEC = 2.0+OOM_CAP_WINDOW_SEC = 10.0 # a kill is the container's own cap's when its `oom` counter rose with it or this shortly before+OOM_FORGET_SEC = 600.0 # a cgroup not seen by the sampler for this long is no longer watched+++# --------------------------------------------------------------------------------------------------- small helpers+def now():+ return time.time()+++def rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def read(p):+ try:+ with open(p) as f:+ return f.read()+ except OSError:+ return None+++def stat_id(p):+ try:+ st = os.stat(p)+ return (st.st_dev, st.st_ino)+ except OSError:+ return None+++def stat_of(base):+ """(starttime, utime+stime) of the process or thread at /proc path `base`, or None."""+ s = read(base + "/stat")+ if not s:+ return None+ try:+ f = s.rsplit(")", 1)[1].split()+ return int(f[19]), int(f[11]) + int(f[12])+ except (IndexError, ValueError):+ return None+++def proc_stat(pid):+ return stat_of(f"{PROC}/{pid}")+++def status(pid):+ s = read(f"{PROC}/{pid}/status")+ if not s:+ return {}+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v.strip()+ return d+++def kb(v):+ try:+ return int((v or "0").split()[0])+ except (ValueError, IndexError):+ return 0+++def append(name, obj):+ with open(os.path.join(REC, name), "a") as f:+ f.write(json.dumps(obj, separators=(",", ":")) + "\n")+++def write_json(path, obj):+ tmp = path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f, indent=1)+ os.replace(tmp, path)+++def event(kind, **kw):+ kw.update(t=round(now(), 2), event=kind)+ append("events.jsonl", kw)+++def no_dump():+ """Not dumpable: without CAP_SYS_PTRACE nobody (not even the same uid) can open /proc/<monitor>/{root,mem,fd}."""+ try:+ ctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLE = 4+ except Exception:+ pass+++# --------------------------------------------------------------------------------------------------- NVML+class Nvml:+ """Per-process GPU memory (host PIDs: the monitor runs in the host PID namespace) and per-card use, via libnvidia-ml+ (ctypes; no nvidia-smi child processes)."""++ class Proc(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong),+ ("gpuInstanceId", ctypes.c_uint), ("computeInstanceId", ctypes.c_uint)]++ class Proc1(ctypes.Structure):+ _fields_ = [("pid", ctypes.c_uint), ("usedGpuMemory", ctypes.c_ulonglong)]++ class Mem(ctypes.Structure):+ _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]++ def __init__(self):+ self.lib = ctypes.CDLL("libnvidia-ml.so.1")+ if self.lib.nvmlInit_v2() != 0:+ raise RuntimeError("nvmlInit failed")+ n = ctypes.c_uint(0)+ self.lib.nvmlDeviceGetCount_v2(ctypes.byref(n))+ self.handles = []+ for i in range(n.value):+ h = ctypes.c_void_p()+ if self.lib.nvmlDeviceGetHandleByIndex_v2(i, ctypes.byref(h)) == 0:+ self.handles.append(h)+ self.fns = []+ for name, st in (("nvmlDeviceGetComputeRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v3", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetGraphicsRunningProcesses_v2", self.Proc),+ ("nvmlDeviceGetComputeRunningProcesses", self.Proc1),+ ("nvmlDeviceGetGraphicsRunningProcesses", self.Proc1)):+ kind = "compute" if "Compute" in name else "graphics"+ if any(k == kind for k, _, _ in self.fns):+ continue+ try:+ self.fns.append((kind, getattr(self.lib, name), st))+ except AttributeError:+ pass++ def sample(self):+ """({host pid: MiB}, {card index: (used MiB, total MiB)}, {host pids whose memory NVML does not tell})."""+ per, cards, unknown = {}, {}, set()+ for i, h in enumerate(self.handles):+ m = self.Mem()+ if self.lib.nvmlDeviceGetMemoryInfo(h, ctypes.byref(m)) == 0:+ cards[i] = (m.used // 2 ** 20, m.total // 2 ** 20)+ seen = {}+ for _kind, fn, st in self.fns:+ cnt = ctypes.c_uint(0)+ rc = fn(h, ctypes.byref(cnt), None)+ if rc not in (0, 7): # 7 = NVML_ERROR_INSUFFICIENT_SIZE: cnt now holds the count+ continue+ cnt = ctypes.c_uint(cnt.value + 16)+ arr = (st * cnt.value)()+ if fn(h, ctypes.byref(cnt), arr) != 0:+ continue+ for k in range(cnt.value):+ mem = arr[k].usedGpuMemory+ if mem >= 2 ** 63: # NVML_VALUE_NOT_AVAILABLE (MIG / vGPU / WSL): not a zero+ unknown.add(arr[k].pid)+ mib = 0+ else:+ mib = mem // 2 ** 20+ seen[arr[k].pid] = max(seen.get(arr[k].pid, 0), mib) # a C+G process is in both lists+ for p, v in seen.items():+ per[p] = per.get(p, 0) + v+ return per, cards, unknown+++# --------------------------------------------------------------------------------------------------- disk+class DiskWalk:+ """One measurement of the files under `paths` below `root` (the agent container's root, seen through /proc): the+ sum of st_blocks, every hard-linked file once, never descending into another mount (a directory on another device;+ files are not asked for theirs: on an overlay root whose layers sit on different file systems they report their+ layer's), `exclude` skipped. It runs in+ slices (step) between the monitor's samples, so a large tree delays no sample. `done` only when every directory was+ read: only then is `bytes` a measurement; before that it is a lower bound."""++ def __init__(self, root, paths, exclude):+ self.root, self.t0 = root, now()+ self.bytes = self.entries = 0+ self.done, self.why = False, None+ self._it = self._walk(list(paths), {root + x.rstrip("/") for x in exclude})++ def _walk(self, paths, excl):+ linked = set() # (dev, ino) of files with several names: counted once+ for base in paths:+ top = self.root + base+ try:+ dev = os.lstat(top).st_dev+ except FileNotFoundError:+ continue # the path does not exist in this container: nothing under it+ except OSError as e:+ self.why = f"{base}: {type(e).__name__}"+ return+ stack = [top]+ while stack:+ d = stack.pop()+ try:+ it = os.scandir(d)+ except FileNotFoundError:+ continue # removed since its parent was read+ except OSError as e:+ self.why = f"{d[len(self.root):]}: {type(e).__name__}"+ return+ with it:+ for e in it:+ try:+ st = e.stat(follow_symlinks=False)+ except OSError:+ continue # removed meanwhile+ if stat_mod.S_ISDIR(st.st_mode):+ if st.st_dev != dev or e.path in excl:+ continue # another mount (never crossed: not the container's own files)+ stack.append(e.path)+ elif st.st_nlink > 1:+ k = (st.st_dev, st.st_ino)+ if k in linked:+ continue+ linked.add(k)+ self.bytes += st.st_blocks * 512+ self.entries += 1+ if self.entries % 256 == 0:+ yield+ yield+ self.done = True++ def step(self, budget_sec):+ """Walk on for at most `budget_sec`; True when the walk has ended (done, or failed with `why`)."""+ end = now() + budget_sec+ for _ in self._it:+ if now() >= end:+ return False+ return True+++# --------------------------------------------------------------------------------------------------- OOM kills+class OomWatch:+ """Kernel OOM kills of the watched containers, from each one's cgroup v2 `memory.events`:+ oom times the cgroup's memory reached its own limit (memory.max) and an allocation was about to fail+ oom_kill processes of the cgroup killed by any OOM killer (its own limit's, an enclosing cgroup's, the host's)+ A kill whose `oom` counter rose with it (or within OOM_CAP_WINDOW_SEC before) happened at the container's own cap+ (`cause: "cap"`); one without is the host's or an enclosing cgroup's OOM killer (`cause: "host"`), which the+ container did not cause by its own use (PROTOCOL §2.10: nothing another trial does can fail a trial).++ The counters live and die with the cgroup, and a container whose main process is killed is gone (and restarted by+ compose with fresh counters) within milliseconds. So the files are read by this object's own thread, every+ OOM_COLD_SEC, at once when the kernel signals a change (poll: memory.events notifies), and every OOM_HOT_SEC for a+ while after any change (the `max` counter rises under memory pressure, before a kill). A kill that removes the+ cgroup within about a millisecond can still be missed: such a kill is then in no record.++ scan() reads every file once; the sampler calls it at each tick when the thread does not run (the tests). The+ thread ends when the record is sealed."""++ def __init__(self):+ self.lock = threading.Lock()+ self.w = {} # cgroup dir -> {"role", "scope", "fd", "kill", "oom", "sig", "cap_t", "seen"}+ self.hot_until = 0.0+ self.thread = None+ self.stopped = False # set at the seal: the record is closed, like the samples++ def watch(self, cg, role, scope, t):+ """The sampler saw this container's cgroup at time t."""+ with self.lock:+ e = self.w.get(cg)+ if e is None:+ e = self.w[cg] = {"fd": None, "kill": None, "oom": None, "sig": None, "cap_t": None}+ e.update(role=role, scope=bool(scope), seen=t)++ @staticmethod+ def _close(e):+ if e["fd"] is not None:+ try:+ os.close(e["fd"])+ except OSError:+ pass+ e["fd"] = None++ def _read(self, cg, e):+ """The counters of the cgroup's memory.events ({} when the file cannot be read: the container is not up).+ A file that stops answering belonged to a cgroup that is gone; the same path opened again is a new cgroup (the+ container restarted: another directory, by its inode and creation time), whose counters all belong to the+ trial: they are compared with 0. The same cgroup opened again keeps what was already counted."""+ for _ in (0, 1):+ try:+ if e["fd"] is None:+ e["fd"] = os.open(cg + "/memory.events", os.O_RDONLY)+ st = os.stat(cg)+ ident = (st.st_dev, st.st_ino, st.st_ctime_ns)+ if e["sig"] is not None and ident != e.get("ident"):+ e["kill"] = e["oom"] = 0 # read before, gone, here again: another instance of the cgroup+ e["ident"] = ident+ os.lseek(e["fd"], 0, os.SEEK_SET)+ out = {}+ for line in os.read(e["fd"], 8192).decode("ascii", "replace").splitlines():+ k, _, v = line.partition(" ")+ if v.strip().isdigit():+ out[k] = int(v)+ return out+ except OSError:+ self._close(e)+ return {}++ def scan(self):+ """Read every watched file once and record the kills since the last reading. True when a counter changed."""+ changed = False+ with self.lock:+ t = now()+ for cg, e in list(self.w.items()):+ if t - e["seen"] > OOM_FORGET_SEC:+ self._close(e)+ del self.w[cg]+ continue+ c = self._read(cg, e)+ if "oom_kill" not in c:+ continue+ kill, oom = c["oom_kill"], c.get("oom", 0)+ sig = (kill, oom, c.get("max", 0))+ if e["kill"] is None or kill < e["kill"] or oom < e["oom"]:+ # the first reading is the baseline; counters that went back are a new cgroup under the same path+ e["kill"], e["oom"] = (kill, oom) if e["kill"] is None else (0, 0)+ changed |= sig != e["sig"]+ if oom > e["oom"]:+ e["cap_t"] = t+ if kill > e["kill"]:+ at_cap = e["cap_t"] is not None and t - e["cap_t"] <= OOM_CAP_WINDOW_SEC+ kw = {"role": e["role"], "scope": e["scope"], "count": kill - e["kill"],+ "cause": "cap" if at_cap else "host", "cap_hits": oom - e["oom"]}+ for name, key in (("memory.max", "memory_cap_gb"), ("memory.current", "memory_current_gb")):+ v = (read(cg + "/" + name) or "").strip() # evidence only: the cause is the counters'+ if v.isdigit():+ kw[key] = round(int(v) / GIB, 3)+ event("oom", **kw)+ e["kill"], e["oom"], e["sig"] = kill, oom, sig+ return changed++ def start(self):+ self.thread = threading.Thread(target=self._loop, name="rcb-oom-watch", daemon=True)+ self.thread.start()++ def _loop(self):+ said = False+ while not self.stopped:+ try:+ if self.scan():+ self.hot_until = now() + OOM_HOT_FOR_SEC+ if now() < self.hot_until:+ time.sleep(OOM_HOT_SEC)+ continue+ with self.lock:+ fds = [e["fd"] for e in self.w.values() if e["fd"] is not None]+ if not fds:+ time.sleep(OOM_COLD_SEC)+ continue+ p = select.poll() # memory.events notifies its readers (POLLPRI) when it changes+ for fd in fds:+ p.register(fd, select.POLLPRI | select.POLLERR)+ if p.poll(OOM_COLD_SEC * 1000):+ self.hot_until = now() + OOM_HOT_FOR_SEC+ except Exception as e: # never stop watching+ if not said:+ said = True+ try:+ event("error", why=f"oom watch: {type(e).__name__}: {e}"[:300])+ except Exception:+ pass+ time.sleep(OOM_COLD_SEC)+++# --------------------------------------------------------------------------------------------------- the monitor+class Monitor:+ def __init__(self):+ self.lim = rcb_limits.read_json(LIMITS) or {}+ self.tick = float(self.lim.get("tick_sec", 5))+ self.disk_tick = float(self.lim.get("disk_tick_sec", 60))+ self.enforce, self.switch_error = rcb_limits.parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ self.me_mnt = rl(f"{PROC}/self/ns/mnt")+ self.beacon = {"scope": stat_id(SCOPE_BEACON), "observe": stat_id(OBSERVE_BEACON)}+ self.cls = {} # mnt ns -> {"kind", "role", "witness": (proc path, starttime)}: only what IS watched+ self.neg, self.ok = set(), set() # this tick: namespaces that said no / whose witness still lives+ self.via = {} # pid -> /proc path of a living thread, for a process whose first thread has exited+ self.prev_cpu = {} # pid -> (starttime, ticks, t)+ self.oomw = OomWatch() # kernel OOM kills of the watched containers (its own thread in run())+ self.disk_base = None # GiB under disk_paths at the first complete walk (kept in state.json across restarts)+ self.disk_last = 0.0+ self.disk_gb = None+ self.walk = None # (DiskWalk, mnt ns, proc path, starttime) of the measurement under way+ self.series = [] # [(t, {metric: value})] of the last window, for enforcement decisions+ self.confirmed = {} # metric -> time+ self.kill_until = 0.0+ self.killed = 0+ self.emergency = [] # the emergency_kill events of this run+ self.scope_seen = False+ self.gpu_unknown = False+ self.caps = selftest.capabilities()+ self.nvml = None+ try:+ self.nvml = Nvml()+ except Exception as e:+ self.caps["nvml_error"] = f"{type(e).__name__}: {e}"[:200]+ self.caps["nvml"] = int(self.nvml is not None)+ self.caps["nvml_devices"] = len(self.nvml.handles) if self.nvml else 0+ self.t0 = now()+ self._last_measures, self._gpu_per = [], {}+ self.fatal_scope = False++ # ---- scope discovery+ def base(self, pid):+ """The /proc path to read a process's namespaces, root and memory from."""+ return self.via.get(pid) or f"{PROC}/{pid}"++ def classify(self, mnt, base):+ """{"kind": "scope" | "observe", "role": "main" | "sidecar"} when the mount namespace `mnt` (of the process or+ thread at /proc path `base`) is one of the trial's containers, else None.++ "No" is never remembered beyond this tick: while a container is set up, its init process is already in a new+ mount namespace but still has the host's root, and the beacon appears only with its pivot_root. "Yes" is+ remembered while the process that proved it lives in the namespace (the kernel may give the number of a+ namespace that ended to a new one)."""+ if mnt in self.ok:+ return self.cls[mnt]+ if mnt in self.neg:+ return None+ c = self.cls.get(mnt)+ if c is not None:+ wbase, wstart = c["witness"]+ ws = stat_of(wbase)+ if ws and ws[0] == wstart and rl(wbase + "/ns/mnt") == mnt:+ self.ok.add(mnt)+ return c+ del self.cls[mnt]+ root = base + "/root"+ kind = None+ if self.beacon["scope"] and stat_id(root + SCOPE_BEACON) == self.beacon["scope"]:+ kind = "scope"+ elif self.beacon["observe"] and stat_id(root + OBSERVE_BEACON) == self.beacon["observe"]:+ kind = "observe"+ st = stat_of(base)+ here = st is not None and rl(base + "/ns/mnt") == mnt # a vanished process tells nothing: ask the next+ if kind and here:+ c = {"kind": kind, "role": "main" if os.path.isdir(root + "/logs/agent") else "sidecar",+ "witness": (base, st[0])}+ self.cls[mnt] = c+ self.ok.add(mnt)+ return c+ if here:+ self.neg.add(mnt)+ return None++ def live_thread(self, pid):+ """/proc path of a thread of `pid` that still runs (its first thread has exited: /proc/<pid>/ns is empty)."""+ try:+ tids = os.listdir(f"{PROC}/{pid}/task")+ except OSError:+ return None+ for tid in tids:+ b = f"{PROC}/{pid}/task/{tid}"+ if tid != str(pid) and rl(b + "/ns/mnt"):+ return b+ return None++ def groups(self):+ """{mnt ns: {"kind", "role", "pids": [...], "zombies": n}} of the watched containers."""+ self.neg, self.ok, self.via = set(), set(), {}+ out, where, lost = {}, {}, []+ try:+ names = os.listdir(PROC)+ except OSError:+ names = []+ for d in names:+ if not d.isdigit():+ continue+ pid = int(d)+ mnt = rl(f"{PROC}/{pid}/ns/mnt")+ if mnt is None:+ lost.append(pid)+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, f"{PROC}/{pid}")+ if c:+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ zombies = []+ for pid in lost:+ b = self.live_thread(pid)+ if not b:+ zombies.append(pid)+ continue+ mnt = rl(b + "/ns/mnt") # its first thread exited, the others run on: a process like any other+ if mnt is None:+ continue+ where[pid] = mnt+ if mnt == self.me_mnt:+ continue+ c = self.classify(mnt, b)+ if c:+ self.via[pid] = b+ out.setdefault(mnt, {"kind": c["kind"], "role": c["role"], "pids": [], "zombies": 0})["pids"].append(pid)+ for pid in zombies:+ st = status(pid)+ if st.get("State", "").startswith("Z"): # a zombie holds a PID until its parent reaps it: counted there+ try:+ g = out.get(where.get(int(st.get("PPid", "0"))))+ except ValueError:+ g = None+ if g:+ g["zombies"] += 1+ self.cls = {m: c for m, c in self.cls.items() if m in self.ok}+ return out++ # ---- per-container measurements+ def cgroup_of(self, pids):+ """The container's own cgroup v2 directory (under the host tree, `cgroup: host`) when every process in it is this+ container's (rootless podman without cgroup delegation leaves containers in a shared one), else None."""+ paths = set()+ for p in pids[:8]:+ s = read(f"{PROC}/{p}/cgroup") or ""+ for line in s.splitlines():+ if line.startswith("0::"):+ paths.add(line[3:].strip())+ if len(paths) != 1:+ return None+ d = CGROUP + paths.pop()+ procs = read(d + "/cgroup.procs")+ if procs is None:+ return None+ members = {int(x) for x in procs.split() if x.isdigit()}+ return d if members and members <= set(pids) else None++ def mem_pss(self, pids):+ tot = 0+ for p in pids:+ s = read(self.base(p) + "/smaps_rollup")+ if s is None:+ st = status(p)+ tot += kb(st.get("RssAnon")) + kb(st.get("RssShmem"))+ continue+ d = {}+ for line in s.splitlines():+ k, _, v = line.partition(":")+ d[k] = v+ tot += (kb(d.get("Pss_Anon")) + kb(d.get("Pss_Shmem"))) if "Pss_Anon" in d else kb(d.get("Pss"))+ return tot / 1024.0 / 1024.0 # GiB++ def measure(self, g, gpu_per, t, gpu_unknown=()):+ pids = g["pids"]+ threads = cpu = 0.0+ for p in pids:+ threads += int(status(p).get("Threads", "0") or 0)+ ps = proc_stat(p)+ if ps:+ pv = self.prev_cpu.get(p)+ if pv and pv[0] == ps[0] and t > pv[2]:+ cpu += max(0, ps[1] - pv[1]) / HZ / (t - pv[2])+ self.prev_cpu[p] = (ps[0], ps[1], t)+ cg = self.cgroup_of(pids)+ m = {"kind": g["kind"], "role": g["role"], "processes": len(pids) + g.get("zombies", 0),+ "zombies": g.get("zombies", 0), "threads": int(threads), "cpu": round(cpu, 2),+ "gpu_memory_gb": round(sum(gpu_per.get(p, 0) for p in pids) / 1024.0, 3), "cgroup": int(cg is not None)}+ unknown = sum(1 for p in pids if p in gpu_unknown)+ if unknown:+ m["gpu_unmeasured"] = unknown # processes on the GPU whose memory NVML does not tell+ if cg:+ st = {}+ for line in (read(cg + "/memory.stat") or "").splitlines():+ k, _, v = line.partition(" ")+ st[k] = v+ try:+ m["memory_gb"] = round((int(st.get("anon", 0)) + int(st.get("shmem", 0))) / GIB, 3)+ except ValueError:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ mx = (read(cg + "/memory.max") or "").strip()+ m["memory_cap_gb"] = None if mx in ("", "max") else round(int(mx) / GIB, 2)+ self.oomw.watch(cg, g["role"], g["kind"] == "scope", now())+ else:+ m["memory_gb"] = round(self.mem_pss(pids), 3)+ return m++ # ---- disk+ def main_proc(self, groups):+ """(mnt ns, pid) to reach the agent container's files through: its PID 1 when visible (it outlives the others)."""+ for mnt, g in groups.items():+ if g["kind"] == "scope" and g["role"] == "main" and g["pids"]:+ init = [p for p in g["pids"] if (status(p).get("NSpid") or "").split()[-1:] == ["1"]]+ return mnt, (init[0] if init else min(g["pids"]))+ return None, None++ def disk_step(self, t, groups):+ """The disk value of this sample: GiB the files under disk_paths grew since the baseline, or None (not measured+ at this tick). Only a complete walk of a container that is still there is a measurement; only such a walk sets+ the baseline. A walk that did not finish is a lower bound: it can show that the limit is exceeded, never that it+ is not, and it never becomes the baseline."""+ if self.walk is None:+ mnt, pid = self.main_proc(groups)+ if pid is None or t - self.disk_last < self.disk_tick:+ return None+ b = self.base(pid)+ st = stat_of(b)+ if st is None:+ return None+ self.disk_last = t+ self.walk = (DiskWalk(b + "/root", self.lim.get("disk_paths") or ["/app"], self.lim.get("disk_exclude") or []),+ mnt, b, st[0])+ w, mnt, b, start = self.walk+ ended = w.step(DISK_SLICE_SEC)+ if not ended and now() - w.t0 <= DISK_WALK_MAX_SEC:+ return None # goes on at the next tick+ self.walk = None+ st = stat_of(b)+ there = st is not None and st[0] == start and rl(b + "/ns/mnt") == mnt # the same container, still up+ gb = w.bytes / GIB+ if ended and w.done and there:+ if self.disk_base is None:+ self.disk_base = gb+ self.save_state()+ event("disk_baseline", gb=round(gb, 3), entries=w.entries)+ self.disk_gb = round(max(0.0, gb - self.disk_base), 3)+ return self.disk_gb+ why = "the container's process ended during the walk" if not there else (w.why or "not finished in time")+ event("disk_partial", why=why, gb=round(gb, 3), entries=w.entries, sec=round(now() - w.t0, 1))+ lim = float(self.lim.get("max_disk_gb") or 0)+ if there and self.disk_base is not None and lim and gb - self.disk_base > lim:+ self.disk_gb = round(gb - self.disk_base, 3) # already over the limit, whatever the rest holds+ return self.disk_gb+ return None++ # ---- state that must outlive a restart of the monitor (restart: on-failure)+ def save_state(self):+ try:+ write_json(os.path.join(REC, "state.json"), {"disk_base": self.disk_base})+ except OSError:+ pass++ def restore(self):+ """After a restart: the disk baseline, the confirmed violations and the last window of samples come back from+ the record, so that a crash neither resets the baseline nor forgets time already spent over a limit."""+ st = rcb_limits.read_json(os.path.join(REC, "state.json")) or {}+ if isinstance(st.get("disk_base"), (int, float)):+ self.disk_base = float(st["disk_base"])+ _, samples, events = rcb_limits.load_record(REC)+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [(s["t"], s.get("scope") or {}) for s in samples+ if isinstance(s.get("t"), (int, float)) and s["t"] >= self.t0 - window - 3 * self.tick]+ for e in events:+ k = e.get("event")+ if k == "violation" and e.get("metric"):+ self.confirmed.setdefault(e["metric"], e.get("t") or self.t0)+ elif k in ("kill", "emergency_kill"):+ self.killed += int(e.get("processes") or 0)+ if k == "emergency_kill":+ self.emergency.append(e)+ elif k == "scope_found":+ self.scope_seen = True+ if self.enforce and self.confirmed and self.t0 - max(self.confirmed.values()) < 60:+ self.kill_until = max(self.confirmed.values()) + 60++ # ---- enforcement+ @staticmethod+ def spared(pids):+ """The container's own processes that must outlive a kill: its PID 1 and what PID 1 started with it (Harbor's+ `sh -c "sleep infinity"` keepalive). Agent processes are exec'd into the container (their parent is outside+ it) or, when orphaned, adopted by PID 1 later: those are never spared."""+ st = {p: status(p) for p in pids}+ init = [p for p in pids if (st[p].get("NSpid") or "").split()[-1:] == ["1"]]+ if not init:+ return set()+ t1 = (proc_stat(init[0]) or (0, 0))[0]+ keep = set(init)+ for p in pids:+ ns_ppid = None+ ns = (st[p].get("NSpid") or "").split()+ if ns and st[p].get("PPid") is not None:+ # PPid in /proc/<pid>/status is in the reader's namespace (host); compare with PID 1's host PID+ ns_ppid = int(st[p]["PPid"])+ ps = proc_stat(p)+ if ns_ppid == init[0] and ps and ps[0] - t1 <= 2 * HZ: # started with the container, not adopted later+ keep.add(p)+ return keep++ def kill_scope(self, groups, why):+ n = 0+ for mnt, g in groups.items():+ if g["kind"] != "scope":+ continue+ snap = {p: proc_stat(p) for p in g["pids"]}+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue # PID 1 and its keepalive: the container stays up for collection+ if rl(self.base(p) + "/ns/mnt") != mnt or not snap[p] or proc_stat(p) is None \+ or proc_stat(p)[0] != snap[p][0]:+ continue # gone, or its PID now names another process+ try:+ os.kill(p, signal.SIGKILL)+ n += 1+ except OSError:+ pass+ if n:+ self.killed += n+ event("kill", why=why, processes=n)+ return n++ def scope_memory_cap(self):+ """GiB: the declared memory caps of the services the limits bind, summed (None: not declared)."""+ caps = self.lim.get("caps") or {}+ names = self.lim.get("scope_services") or (+ [n for n in caps if n != "*"] if self.lim.get("scope") == "trial" else ["main"])+ vals = [float(caps[n]["memory_gb"]) for n in names if isinstance(caps.get(n), dict) and caps[n].get("memory_gb")]+ return sum(vals) if vals else None++ def check(self, t, scope_vals, groups):+ self.series.append((t, scope_vals))+ window = float(self.lim.get("window_sec", 2 * float(self.lim.get("sustain_sec", 60))))+ self.series = [x for x in self.series if x[0] >= t - window - 3 * self.tick]+ samples = [{"t": a, "scope": b} for a, b in self.series]+ for v in rcb_limits.violations(samples, self.lim):+ if v["metric"] not in self.confirmed:+ self.confirmed[v["metric"]] = t+ event("violation", **v)+ if self.enforce:+ self.kill_until = t + 60+ if self.enforce and t <= self.kill_until:+ self.kill_scope(groups, ",".join(sorted(self.confirmed)))+ # Host protection (enforced runs only; PROTOCOL §2.10). An emergency kill is never a violation by itself: the+ # trial fails only by the sustained rule above or a kernel OOM kill at its own memory cap. Both conditions are+ # the trial's own doing (its scope's use against its own limit or caps), never the state of a card or host it+ # shares with other trials.+ if self.enforce:+ cap = self.scope_memory_cap()+ lim_gpu = float(self.lim.get("max_gpu_memory_gb") or 0)+ if cap and scope_vals["memory_gb"] > cap and not any(+ m.get("memory_cap_gb") for m in self._last_measures if m["kind"] == "scope"):+ # no kernel memory cap holds here (e.g. rootless podman without cgroups): stand in for it+ self._emergency(groups, "memory", cap, scope_vals["memory_gb"], key="mem")+ if lim_gpu and scope_vals["gpu_memory_gb"] > EMERGENCY_GPU_FACTOR * lim_gpu:+ self._emergency(groups, "gpu_memory", lim_gpu, scope_vals["gpu_memory_gb"], key="gpu")++ def _emergency(self, groups, why, limit, observed, key):+ best, bv = None, 0 # only a process that holds some: never one with none of it+ for g in groups.values():+ if g["kind"] != "scope":+ continue+ keep = self.spared(g["pids"])+ for p in g["pids"]:+ if p in keep:+ continue+ v = self._gpu_per.get(p, 0) if key == "gpu" else self.rss_kb(p)+ if v > bv:+ best, bv = p, v+ if best:+ try:+ os.kill(best, signal.SIGKILL)+ self.killed += 1+ e = {"why": why, "limit": limit, "observed": round(observed, 3), "processes": 1}+ event("emergency_kill", **e)+ self.emergency.append(dict(e, t=round(now(), 2)))+ except OSError:+ pass++ def rss_kb(self, p):+ v = kb(status(p).get("VmRSS"))+ if not v and p in self.via: # the first thread has exited: its status has no memory lines+ for line in (read(self.via[p] + "/status") or "").splitlines():+ if line.startswith("VmRSS:"):+ v = kb(line.partition(":")[2])+ return v++ # ---- main loop+ def run(self):+ os.makedirs(REC, exist_ok=True)+ restarted = os.path.exists(os.path.join(REC, "meta.json"))+ meta = {"format": rcb_limits.FORMAT, "started": round(self.t0, 2), "enforce": self.enforce, "limits": self.lim,+ "capabilities": self.caps, "beacons": {k: bool(v) for k, v in self.beacon.items()}}+ if self.switch_error:+ meta["switch_error"] = self.switch_error+ if restarted:+ self.restore()+ event("restart", capabilities=self.caps)+ else:+ write_json(os.path.join(REC, "meta.json"), meta)+ event("start", enforce=self.enforce, capabilities=self.caps)+ if self.switch_error:+ event("fatal", why=self.switch_error + " (nothing is enforced; the trial is not a result)")+ if not self.beacon["scope"]:+ event("fatal", why="no scope beacon mounted at /run/rcb-limits")+ if self.lim.get("gpu") and not self.nvml:+ event("fatal", why="GPU task but NVML is unavailable: " + str(self.caps.get("nvml_error")))+ sys.setswitchinterval(0.001) # the OOM watch must get its turn within a millisecond+ self.oomw.start()+ while not os.path.exists(os.path.join(REC, "seal.request")):+ t = now()+ try:+ self.tick_once(t)+ except Exception as e: # a vanished process mid-read must never stop the record+ import traceback+ traceback.print_exc()+ event("error", why=f"{type(e).__name__}: {e}"[:300])+ for p in list(self.prev_cpu):+ if t - self.prev_cpu[p][2] > 60:+ del self.prev_cpu[p]+ time.sleep(max(0.2, self.tick - (now() - t)))+ self.seal()+ while True: # stay up: Harbor copies the record after the hook+ time.sleep(3600)++ def tick_once(self, t):+ groups = self.groups()+ gpu_per, cards, gpu_unknown = self.nvml.sample() if self.nvml else ({}, {}, set())+ self._gpu_per = gpu_per+ ms = [self.measure(g, gpu_per, t, gpu_unknown) for g in groups.values()]+ self._last_measures = ms+ if self.oomw.thread is None:+ self.oomw.scan() # no thread (tests): read the OOM counters with the sample+ scope = [m for m in ms if m["kind"] == "scope"]+ if scope and not self.scope_seen:+ self.scope_seen = True+ event("scope_found", containers=len(scope), roles=sorted(m["role"] for m in scope))+ if not self.scope_seen and not self.fatal_scope and t - self.t0 > 120:+ self.fatal_scope = True+ event("fatal", why="no container mounting the trial's beacon found within 120 s")+ disk_now = self.disk_step(t, groups)+ vals = {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in scope), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in scope), 3),+ "processes": sum(m["processes"] for m in scope), "disk_gb": disk_now}+ unknown = sum(m.get("gpu_unmeasured", 0) for m in scope)+ if unknown:+ vals["gpu_unmeasured"] = unknown+ if not self.gpu_unknown:+ self.gpu_unknown = True+ event("gpu_unmeasured", processes=unknown,+ why="NVML does not tell the GPU memory of processes in scope (MIG / vGPU?): counted as 0")+ obs = [m for m in ms if m["kind"] == "observe"]+ append("samples.jsonl", {"t": round(t, 2), "scope": vals,+ "observe": {"gpu_memory_gb": round(sum(m["gpu_memory_gb"] for m in obs), 3),+ "memory_gb": round(sum(m["memory_gb"] for m in obs), 3),+ "processes": sum(m["processes"] for m in obs)},+ "cards": {str(k): v for k, v in cards.items()}, "containers": ms})+ self.check(t, vals, groups)+ try:+ write_json(SCOPE_BEACON + "/usage.json", {+ "t": round(t, 2), "gpu_memory_gb": vals["gpu_memory_gb"], "memory_gb": vals["memory_gb"],+ "processes": vals["processes"], "disk_gb": self.disk_gb, "enforced": self.enforce,+ "limits": {k: self.lim.get(k) for k in ("max_gpu_memory_gb", "max_memory_gb", "max_processes",+ "max_disk_gb", "sustain_sec", "window_sec")},+ "violations": sorted(self.confirmed),+ # processes the monitor killed at once to protect the host (not violations by themselves)+ "emergency_kills": len(self.emergency), "last_emergency_kill": (self.emergency or [None])[-1]})+ except OSError:+ pass++ def seal(self):+ try:+ self.oomw.scan() # the counters once more, whatever the watch thread is doing+ except Exception:+ pass+ # The record ends here, for OOM kills as for the samples: what happens to a sidecar in the collect hooks that+ # follow (its replays) is the grader's to judge, from the hook's own evidence.+ self.oomw.stopped = True+ summary, samples, events = rcb_limits.load_record(REC)+ viol = rcb_limits.violations(samples, self.lim, events)+ meta = rcb_limits.read_json(os.path.join(REC, "meta.json")) or {}+ out = {+ "format": rcb_limits.FORMAT, "sealed": True, "enforce": meta.get("enforce", self.enforce),+ "started": meta.get("started"), "ended": round(now(), 2), "n_samples": len(samples),+ "scope_seen": self.scope_seen or any((s.get("scope") or {}).get("processes") for s in samples),+ "peaks": rcb_limits.peaks(samples), "violations": viol,+ "killed": sum(int(e.get("processes") or 0) for e in events if e.get("event") in ("kill", "emergency_kill")),+ "emergency_kills": sum(1 for e in events if e.get("event") == "emergency_kill"),+ "disk_baseline_gb": self.disk_base,+ "disk_partial_walks": sum(1 for e in events if e.get("event") == "disk_partial"),+ "restarts": sum(1 for e in events if e.get("event") == "restart"),+ "capabilities": meta.get("capabilities", self.caps), "limits": self.lim}+ if meta.get("switch_error") or self.switch_error:+ out["switch_error"] = meta.get("switch_error") or self.switch_error+ write_json(os.path.join(REC, "summary.json"), out)+ event("seal", violations=len(viol))+++def seal_cmd(wait):+ open(os.path.join(REC, "seal.request"), "a").close()+ path = os.path.join(REC, "summary.json")+ t_end = now() + wait+ while now() < t_end and not os.path.exists(path):+ time.sleep(0.5)+ s = rcb_limits.read_json(path)+ print(json.dumps({k: (s or {}).get(k) for k in ("sealed", "enforce", "n_samples", "peaks", "violations", "killed")}))+ return 0+++def main(argv):+ if argv[:1] == ["seal"]:+ wait = float(argv[argv.index("--wait") + 1]) if "--wait" in argv else 90.0+ return seal_cmd(wait)+ if argv[:1] in (["run"], []):+ no_dump()+ Monitor().run()+ return 0+ print(__doc__)+ return 2+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.pynew file mode 100644index 0000000000..a979bcdaff--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/rcb_limits.py@@ -0,0 +1,457 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/selftest.pynew file mode 100644index 0000000000..89d553743f--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/environment/rcb_monitor/selftest.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""What the resource monitor can measure where it runs (capabilities(), written into its record), and a self-test of+the shared violation rule and the verifier step (no containers needed; ci_checks/check-monitor.py runs it):++ python3 scripts/rcb_monitor/selftest.py+"""+import json+import os+import sys+import tempfile++HERE = os.path.dirname(os.path.abspath(__file__))+++def _rl(p):+ try:+ return os.readlink(p)+ except OSError:+ return None+++def capabilities():+ """Facts the verifier and the results footnotes need: does the monitor see the host's processes (pid: host), the+ host's cgroup tree (cgroup: host; per-container memory and OOM counts), """+ c = {}+ try:+ pids = [d for d in os.listdir("/proc") if d.isdigit()]+ except OSError:+ pids = []+ try:+ c["pid_host"] = int(len(pids) > 1 and open("/proc/1/comm").read().strip() != open("/proc/self/comm").read().strip())+ except OSError:+ c["pid_host"] = 0+ own = ""+ try:+ own = [ln[3:].strip() for ln in open("/proc/self/cgroup") if ln.startswith("0::")][0]+ except (OSError, IndexError):+ pass+ c["cgroup_v2"] = int(os.path.exists("/sys/fs/cgroup/cgroup.controllers"))+ c["cgroup_host"] = int(bool(own) and own != "/" and os.path.isdir("/sys/fs/cgroup" + own))+ return c+++# --------------------------------------------------------------------------------------------------- self-test+def _check(cond, msg):+ if not cond:+ raise AssertionError(msg)+++def test_rule():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ tick = 5.0+ over = [(i * tick, 10.0 if 20 <= i < 33 else 1.0) for i in range(60)] # 65 s over the limit+ _check(abs(r.sustained(over, 5, 60, 120, tick) - 160.0) < 0.01, "65 s over: confirmed at 60 s")+ short = [(i * tick, 10.0 if 20 <= i < 31 else 1.0) for i in range(60)] # 55 s+ _check(r.sustained(short, 5, 60, 120, tick) is None, "55 s over: no violation")+ flap = [(i * tick, 10.0 if (i % 2 == 0 and i >= 20) else 1.0) for i in range(80)] # half the time, never 60 s straight+ _check(r.sustained(flap, 5, 60, 120, tick) is not None, "59 s on / 1 s off does not escape: 60 s in any 120 s")+ sparse = [(i * 25.0, 10.0) for i in range(4)] # 25 s gaps count 15 s each+ _check(r.sustained(sparse, 5, 60, 120, tick) is None, "gaps never count against the agent")+ _check(r.sustained(over, 0, 60, 120, tick) is None, "limit 0 = not limited")+ disk = [(0, 1.0), (60, 30.0), (120, 1.0), (180, 30.0), (240, 31.0)]+ _check(r.consecutive(disk, 20) == 240, "disk: two consecutive measurements over")+++def test_verify():+ sys.path.insert(0, HERE)+ import rcb_limits as r+ lim = {"max_gpu_memory_gb": 4.0, "max_memory_gb": 8.0, "max_processes": 100, "max_disk_gb": 10.0,+ "sustain_sec": 60, "window_sec": 120, "tick_sec": 5}+ for enforce, gpu, want in ((1, 6.0, "fail"), (0, 6.0, "observe"), (1, 3.0, "pass")):+ with tempfile.TemporaryDirectory() as d:+ rec, tests, logs = (os.path.join(d, x) for x in ("rec", "tests", "logs"))+ for x in (rec, tests, logs):+ os.makedirs(x)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ with open(os.path.join(rec, "samples.jsonl"), "w") as f:+ for i in range(40):+ f.write(json.dumps({"t": 1000 + 5 * i, "scope": {"gpu_memory_gb": gpu if i > 5 else 0.5,+ "memory_gb": 2.0, "processes": 10,+ "disk_gb": 0.1 if i % 12 == 0 else None}}) + "\n")+ open(os.path.join(rec, "events.jsonl"), "w").close()+ json.dump({"format": r.FORMAT, "sealed": True, "enforce": enforce, "scope_seen": True},+ open(os.path.join(rec, "summary.json"), "w"))+ json.dump({"success": 1, "infra_error": 0}, open(os.path.join(logs, "reward.json"), "w"))+ open(os.path.join(logs, "reward.txt"), "w").write("1\n")+ import shutil+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=rec, RCB_VERIFIER_LOGS=logs)+ import subprocess+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ txt = open(os.path.join(logs, "reward.txt")).read().strip()+ if want == "fail":+ _check(out["success"] == 0 and out["resource_limit_exceeded"] == 1 and out["success_before_limits"] == 1+ and txt == "0" and out["over_gpu_memory_gb"] == 1, f"enforced violation fails: {out}")+ elif want == "observe":+ _check(out["success"] == 1 and out["limits_violation_observed"] == 1 and txt == "1"+ and "resource_limit_exceeded" not in out, f"observe mode only records: {out}")+ else:+ _check(out["success"] == 1 and out["limits_violation_observed"] == 0 and out["resource_monitor_missing"] == 0,+ f"within limits: {out}")+ _check(out["peak_gpu_memory_gb"] == gpu, "peak recorded")+ # no record at all: enforced = infra, observed = flagged only+ for enforce in (1, 0):+ with tempfile.TemporaryDirectory() as d:+ logs, tests = os.path.join(d, "logs"), os.path.join(d, "tests")+ os.makedirs(logs)+ os.makedirs(tests)+ json.dump(lim, open(os.path.join(tests, "rcb_limits.json"), "w"))+ json.dump({"success": 1}, open(os.path.join(logs, "reward.json"), "w"))+ import shutil+ import subprocess+ shutil.copy(os.path.join(HERE, "rcb_limits.py"), tests)+ env = dict(os.environ, RCB_MONITOR_RECORD=os.path.join(d, "none"), RCB_VERIFIER_LOGS=logs,+ RCB_LIMITS_ENFORCE=str(enforce))+ subprocess.run([sys.executable, os.path.join(tests, "rcb_limits.py"), "verify"], env=env, check=True,+ capture_output=True)+ out = json.load(open(os.path.join(logs, "reward.json")))+ _check(out["resource_monitor_missing"] == 1 and out.get("infra_error", 0) == enforce,+ f"missing record (enforce={enforce}): {out}")+++def main():+ if sys.argv[1:2] == ["caps"]:+ print(json.dumps(capabilities()))+ return 0+ test_rule()+ test_verify()+ print("rcb_monitor selftest: ok")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/instruction.md b/tasks/ambench-rotate-valve-fahexa-i00-privileged/instruction.mdnew file mode 100644index 0000000000..d058ae851c--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/instruction.md@@ -0,0 +1,87 @@+# AM-Bench · Rotate Valve — frozen instance i00++You control a simulated **aerial manipulator**: a fully actuated hexarotor (six tilted rotors, so it can hold any attitude+while hovering) carrying a small arm (four joints: three pitch joints and a roll joint) with a two-finger gripper, in+AM-Bench on Isaac Lab / Isaac Sim 5.1 (PhysX), via Python. **Task:** A valve is mounted on the front face of a wall in front of the hovering aerial manipulator: a large red wheel disc on a short shaft, with a handle bar sticking out of the disc's face toward the robot. Turn the valve: rotate the wheel clockwise, as seen from the robot's side of the wall, by at least 170 degrees from its starting angle.++This is a *fixed scene instance*: the scene and the robot start the same way after every reset, and you may reset and+retry as many times as you want. Your deliverable is **one replayable trajectory** of the robot's low-level actions, not a+general policy.++## Scene+The ground is the world's z = 0 plane. In front of the robot stands an immovable (kinematic) wall: a slab 0.1 m thick, 2.0 m wide and 2.0 m tall with a concrete-block surface, its front face turned toward the robot. The wall is upright (no tilt in this task); its distance and sideways offset vary between instances. A valve is mounted on the wall's front face with its axis perpendicular to the wall: a dark-blue circular base plate (about 47 cm across) fixed just in front of the wall, a short shaft, and a red disc of the same size that turns with the shaft. On the disc's robot-facing side, off the axis, is a handle bar (square cross-section about 6 cm, 16 cm long, parallel to the axis); at reset it sits directly below the hub (the 6 o'clock position), and it can also spin freely about its own long axis. The valve's height and sideways position on the wall vary between instances. The shaft has no spring and no end stops: it stays at whatever angle it is left, its motion resisted by damping and friction. Nothing moves by itself. The robot starts hovering level and motionless, facing the wall, with its arm at its zero joint configuration (end effector a little ahead of and above the airframe) and the gripper closed.++Exactly (privileged information, also readable through the tooling): One environment; its origin is the world origin. Robot at every reset: base_link at (0, 0, 1.0) m with orientation (1, 0, 0, 0) wxyz (body +x is the world +x direction), zero velocity; arm_link1_pitch_joint = arm_link2_pitch_joint = arm_link3_pitch_joint = arm_link4_roll_joint = 0 rad; arm_lfinger_joint = arm_rfinger_joint = 0.001 m (their lower limit: gripper closed, gripper_width 0.002 m). By the robot's URDF kinematics this puts ee_link at about (0.227, 0, 1.124) m with identity orientation and the tool-tip point (ee_link origin + 0.18 m along the ee_link x axis) at about (0.407, 0, 1.124) m; the end-effector command is initialised to the current ee_link pose. Wall: kinematic cuboid 0.1 (x) x 2.0 (y) x 2.0 (z) m, nominal centre (2.0, 0.0, 1.0) m and orientation identity (front face the plane x = centre_x - 0.05, normal -x, toward the robot); friction 1.0 static / 1.0 dynamic, restitution 0; visual material NVIDIA Concrete_Block.mdl. At each reset (Isaac Lab mdp.reset_root_state_uniform) the centre becomes (2.0 + dx, 0.0 + dy, 1.0) with dx, dy ~ U(-0.2, 0.2) m independently; the configured pitch range is (0, 0), so the wall keeps the identity orientation (upright, front normal -x). Valve: articulation valve.usd with a fixed root body base_link, self-collisions disabled, solver iterations 16 position / 4 velocity, spawned with scale (1.8, 1.0, 1.8) in the asset's own frame (radial dimensions x1.8, axial dimensions unchanged), mass_props mass = 0.05 kg set on each of the valve's rigid links (the USD authors 0.01 kg per link, 0.005 kg for the handle), contact offset 0.005 m, rest offset 0. At each reset, after the wall, base_link is placed at wall_centre + R_wall (-0.06, vy, vz) with vy, vz ~ U(-0.2, 0.2) m independently (the base-plate centre 0.01 m in front of the wall surface) with orientation R_wall composed with (0.5, 0.5, 0.5, 0.5) wxyz, so the shaft axis (base_link local +z) is world +x, pointing into the wall. Along the axis toward the robot, from the base-plate centre: blue base plate radius 0.234 m, thickness 0.015 m, colour (0.018, 0.115, 0.232); shaft radius 0.108 m from 0.0075 to 0.0475 m; red disc radius 0.234 m from 0.048 to 0.058 m (OmniPBR diffuse tint (0.99, 0.01, 0.01)); handle bar (body handle_link, 0.063 x 0.063 m cross-section, 0.16 m long along the axis) on the robot-facing side of the disc, below the hub at reset (the USD authors its centre 0.135 m out along the axis and 0.144 m below it after scaling, but its joint anchor on the disc is authored elsewhere, so the simulated pose follows the joint: read handle_link's position, which is AM-Bench's goal_pos observation). Joints: base_to_shaft, revolute about base_link +z (world +x), no position limits, reset to 0 rad with zero velocity every episode, Isaac Lab implicit actuator stiffness 0, damping 15.0, friction 0.2 (static and dynamic), effort limit 20, velocity limit 5.0 rad/s; shaft_to_disk fixed; disk_to_handle, revolute about the handle's long axis, unlimited, reset to 0, stiffness 0, damping 10.0, friction 0.1, effort limit 20, velocity limit 5.0 rad/s. Physics material on base plate, shaft and disc: static and dynamic friction 10000; the handle uses the scene default (friction 1.0 / 1.0, restitution 0).++## Success (AM-Bench's own check)+Success when the valve has turned clockwise by at least 17/18 pi = 2.96706 rad (170 degrees; valve_target_angle): the unwrapped angle of the revolute joint base_to_shaft, counted from its 0 rad at the reset, is >= 2.96706 rad. Positive is the right-hand rotation about the shaft axis base_link +z, which points into the wall (world +x): clockwise when viewed from the robot's side, so a handle starting straight below the hub first moves toward world +y (the robot's left) and at 170 degrees is 10 degrees short of straight up. The joint has no limits, and PhysX reports its position wrapped into [-pi, pi] (s.objects() shows that raw value): AM-Bench's check compares that raw value, which a counter-clockwise turn of 190 degrees would also bring to +170 degrees, so the tooling (and the grader, with the same tooling) gives the check the unwrapped angle instead, the sum of the joint's per-step changes since the reset, readable as s.valve_angle() (rad). Only a clockwise turn counts; turning the wheel back counter-clockwise subtracts. AM-Bench also reports a subtask criterion valve_engaged (joint position >= 0.05 x 17/18 pi = 0.1484 rad); it is informational only. Evaluated after every control step (decimation 1, so after every 1/120 s physics step) on the simulated state; no hold time is required. The episode terminates at the first step where it holds. Otherwise it is truncated by the time limit: episode_length_s = 20 s, i.e. max_episode_length = 2400 control steps; AM-Bench raises the time-out when episode_length_buf >= max_episode_length - 1, i.e. at the 2399th step.+The episode **ends by itself** at the first control step where the check holds (success; rows after it are never+executed), or when the task's episode length of **20 s** runs out (a failure: AM-Bench's time-out ends the episode+at control step 2399). Isaac Lab resets the scene inside the step that ends an episode, so after it `s.state()`,+`s.objects()` and the cameras show the start again; `s.status()` keeps the outcome and the end state's hash.++## Deliverable+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed+open-loop from the same initial state in two fresh processes and scored 1 if the task succeeds in both replays and both+end in the same state, else 0. Also leave the script that produced it at `/app/output/gen.py`. Save a working trajectory+as soon as you have one and overwrite it as you improve it: whatever is in `/app/output/` when the time is up is graded.+The file holds `task` and `actions`, a (T, 8) float array of at most **8,000 rows** (one per control step); anything else+(another shape, NaN, more rows, a file that is not such an npz) scores 0.++## Tooling (already installed; run `python` from any directory)+```python+from rcb_ambench import Session+s = Session(instance="/app/instance.json") # ~2-6 min: launches Isaac Sim, builds the scene, resets to the frozen instance+ # (no cameras, as the grader; Session(..., cameras=True) to look: see below)+s.reset() # back to the frozen instance (the seeded reset; as often as you like)+s.step(row) # one control step (1/120 s): row = 8 values (below); True once the episode is over+s.hold_action() # a row that keeps the current end-effector target and gripper command+s.status() # {'success', 'done', 'end_reason', 'control_steps', 'sim_time_s', 'episode_length_s', 'state_sha', ...}+s.state() # privileged: AM-Bench's own observation of the task (robot, end effector, task objects, goal)+s.objects() # every task object and fixture: pose (xyz + quaternion wxyz), velocities, joint state+s.proprio() # the robot: base and end-effector poses and velocities, gripper width, arm joints, current command+s.actions() # (T, 8) rows executed since the last reset: the trajectory of this episode+s.replay(actions) # reset, run the rows open-loop until the episode ends, return status (+ executed_rows)+s.save_trajectory(actions, "/app/output/trajectory.npz")+s.render_frame("ee_camera") # cameras=True only: RGB uint8 (384, 384, 3) at the end effector, or "base_camera" (on the airframe, looking forward)+s.start_video("/app/output/try.mp4"); ...; s.stop_video() # cameras=True only: film the steps in between (both cameras side by side)+s.env # the Isaac Lab environment itself (AM-Bench's source is in /opt/ambench: read-only reference)+```+The tooling is deliberately thin: the environment's own action, its state and its cameras. Reaching, pressing, pushing,+turning and throwing are yours to build. Isaac Sim runs once per process, and only the first episode of a process is+guaranteed to be bit-identical to a fresh process's: after changes, check your trajectory with the grader's CLI.+**Cameras.** The robot's two onboard cameras exist only in a `Session(..., cameras=True)` (decided once per process). With+them, Isaac renders every step and that makes PhysX's results depend on timing: two runs of the same rows can part after a+few hundred steps. The grader replays without cameras, where a fresh process reproduces a trajectory bit for bit, so use+the cameras to look and check every trajectory with the CLI below.++The grader replays in two fresh processes; each is exactly this CLI (a fresh process, so run it to self-check):+`python /opt/tools/rcb_ambench.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`+(`... film --instance ... --traj ... --video out.mp4` films the rows with the cameras on: an illustration, not a verdict).++## Conventions+- World frame: metres, z up, the ground is the plane z = 0; positions are relative to the environment's origin (the+ tooling and the actions use the same origin); quaternions are **wxyz**.+- Action row (8 values per control step), AM-Bench's absolute end-effector pose action: the target position of the+ end-effector link (x, y, z, m) and its target orientation (qw, qx, qy, qz, in AM-Bench's command frame of the end+ effector: `s.proprio()["command"]` and `hold_action()` give the current target in the same convention), then the gripper+ command (-1 = closed .. +1 = open). Every step, AM-Bench's floating-base inverse kinematics turns the target into an+ airframe pose and arm joint targets, its PID controller turns the airframe pose into the six rotor thrusts, and the arm+ joints track their targets.+- Control and physics run at 120 Hz (one physics step per row). There is no step budget: the time limit (`## Time limit`)+ is your only budget; an episode lasts at most 20 s of simulated time.+- One `Session` per process (Isaac Sim launches once, then the scene builds: ~2-6 min, the upper end on a busy host).+ Physics is PhysX on the **GPU** (about 10-15 control steps per second of wall time). One Isaac process takes up to+ ~13 GiB of memory and ~6.5 GiB of GPU memory: run at most two at once. Do not call `s.close()` before writing every+ output.++## External material+You may install packages you need (pip, apt). Please solve the task yourself: do not look up or download a solution to it, such as this benchmark's own source code, published or reference solutions, recorded demonstrations, or policies trained for it. This is an honour rule; trials are reviewed. The network reaches your model's API and the package registries (PyPI, Debian / Ubuntu archives) only.++## Resource limits+Limits for the whole trial, all its processes together (every simulator you start included): at most **16 GiB of GPU memory**, **28 GiB of memory**, **512 processes** and **20 GiB** of new files under `/app`, `/tmp` and `/root`. GPU memory counts what a process reserves (JAX, for example, reserves most of the card unless told not to). These limits may be enforced (from protocol v1.2 on): when enforcement is on, exceeding one for 60 s within any 2 minutes, or a process killed for lack of memory, ends the trial as a failure (reward 0), whatever the deliverable. A monitor outside your container measures every few seconds; the current values are in `/run/rcb-limits/usage.json`. When enforcement is on and GPU memory goes above 1.5 times its limit, the monitor also kills the process holding the most of it at once, to protect the machine; that alone does not fail the trial. CPU is capped at 8 cores for your container; the cap only slows you down.++## Time limit+You have 3600 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task.++This is wall-clock time from the start of your session; the time a simulator takes to start counts. When it is up you are stopped without warning and only what is in `/app/output/` at that moment is graded, so save a deliverable as soon as you have one and overwrite it whenever you have a better one. Your session started when you received this task: run `date` now, and again before you decide that time is short; work out the time left from those readings, never from a guess. Installing packages is not cheating (`## External material` above).diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/oracle.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/oracle.pynew file mode 100644index 0000000000..b695ebf3dc--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/oracle.py@@ -0,0 +1,15 @@+"""Oracle (privileged): run the reference rows on the frozen instance with the agent's tooling, stopping at the end of+the episode, and save the rows that ran as /app/output/trajectory.npz."""+import json, os+import numpy as np+from rcb_ambench import Session+HERE = os.path.dirname(os.path.abspath(__file__))+s = Session(instance="/app/instance.json", strict=True)+for row in np.load(os.path.join(HERE, "oracle_actions.npy")).astype(np.float64): # the process's first episode, as the grader's+ if s.step(row):+ break+st = {**s.status(), "executed_rows": s.n_steps}+s.save_trajectory(s.actions(), "/app/output/trajectory.npz", meta={"source": "reference rows"})+print(json.dumps({k: st[k] for k in ("success", "end_reason", "executed_rows", "sim_time_s", "state_sha")}), flush=True)+s.close()+os._exit(0 if st["success"] else 1)diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/oracle_actions.npy b/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/oracle_actions.npynew file mode 100644index 0000000000..bf350d9841Binary files /dev/null and b/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/oracle_actions.npy differdiff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/solve.sh b/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/solve.shnew file mode 100755index 0000000000..365611c270--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/solution/solve.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Oracle: replay the reference rows (solution/oracle_actions.npy: AM-Bench's scripted expert for this task, run on this+# instance and recorded, then 2 s of holding its last command; the expert reads the simulator's true state) through the+# agent's own tooling, and save the trajectory. The rows live in solution/ only (never in the agent image, which has no+# expert).+set -e+mkdir -p /app/output+cp /solution/oracle.py /app/output/gen.py+python /solution/oracle.pydiff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/task.toml b/tasks/ambench-rotate-valve-fahexa-i00-privileged/task.tomlnew file mode 100644index 0000000000..5bfe430dda--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/task.toml@@ -0,0 +1,97 @@+# Generated by scripts/ambench/mk_tasks.py -- edit the template or scripts/ambench/descr/, not this.+schema_version = "1.3"+artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]++[task]+name = "robot-coding-bench/ambench-rotate-valve-fahexa-i00-privileged"+description = "AM-Bench RotateValve-Am-FAHexa-Abs-PID-Direct-v0 (a fully actuated hexarotor with a 4-joint arm and a two-finger gripper, Isaac Lab / Isaac Sim 5.1): produce one replayable trajectory of AM-Bench's absolute end-effector pose actions at 120 Hz. Task: A valve is mounted on the front face of a wall in front of the hovering aerial manipulator: a large red wheel disc on a short shaft, with a handle bar sticking out of the disc's face toward the robot. Turn the valve: rotate the wheel clockwise, as seen from the robot's side of the wall, by at least 170 degrees from its starting angle. Frozen scene instance: AM-Bench's seeded reset, seed 0; graded by AM-Bench's own success check in two fresh-process replays."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "ambench", "aerial-manipulation", "isaac-lab", "isaac-sim", "hexarotor", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "ambench" # AM-Bench @ 60bf5b7 on Isaac Lab @ f4aa17f / Isaac Sim 5.1 (PhysX on the GPU, RTX rendering)+robot = "ambench-fahexa"+family = "rotate_valve_fahexa"+mode = "privileged"+dynamics = "static" # scene dynamics (docs/PROTOCOL.md §2.14): scripts/task_dynamics.toml+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 2.0++[metadata.resources]+# minimum compute to run this task (docs/PROTOCOL.md §2.9)+min_cpus = 8.0+min_memory_gb = 16.0+min_gpu_memory_gb = 8.0+gpu_required = true+gpu_class = "rtx"+recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"+verifier_min_cpus = 4.0+verifier_min_memory_gb = 16.0+verifier_min_gpu_memory_gb = 8.0+measured = "freezing the instances and three oracle trials (RTX 4090, 2026-10-13/14, docker stats and nvidia-smi every 10 s, rcb_monitor): a camera-free Isaac process (the default Session, the grader's replays) peaks at 2.9 GiB of memory and 3.2 GiB of GPU memory (oracle trials: 2.8 / 3.1); with the two onboard cameras on (Session(cameras=True), the verifier's filmed illustration) 13.2 GiB and 6.4 GiB; 6-10 cores while Isaac starts, about 1.5 after; the verifier runs one process at a time. The minimums cover one camera-on process"++[metadata.resources.limits]+# agent-phase limits in GiB (docs/PROTOCOL.md §2.10); scope: trial = every container, agent = the agent's container;+# enforced from protocol v1.2 when RCB_LIMITS_ENFORCE=1 (a violation fails the trial), otherwise recorded only+scope = "trial"+max_gpu_memory_gb = 16.0+max_memory_gb = 28.0+max_processes = 512+max_disk_gb = 20.0+disk_paths = ["/app", "/tmp", "/root"]+disk_exclude = []+sustain_sec = 60.0+window_sec = 120.0+trial_max_gpu_memory_gb = 16.0+trial_max_memory_gb = 28.0+measured = "a camera-on Isaac process peaks at 13.2 GiB of memory and 6.4 GiB of GPU memory, a camera-free one at 2.9 / 3.2 (the rule's measurement); the agent may run two processes at once (a Session and the replay CLI): at most 26.4 GiB, 12.8 GiB -> memory 28 GiB (the container's cap 34 GiB: 34 / 1.2 >= 28), GPU 16 GiB (at least 16 for Isaac Sim); processes 512 and disk 20 GiB: design defaults, not yet measured"++[metadata.resources.caps]+# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)+main = { cpus = 8.0, memory_gb = 34.0, pids = 16384 }++[metadata.seeds]+# the instances this task may run from (docs/PROTOCOL.md §2.13): the default, the ones a runner may draw+# from (a list, { from = A, to = B } or "any"), and the ones the reference solution under solution/ is for+default = 0+allowed = [0]+oracle = [0]++[verifier]+timeout_sec = 9000.0 # tests/grade.py's limits for the longest episode (3120 rows: 1500 s + 3120 / 4 = 2280 s per+ # process): two fresh-process replays (no cameras), one rerun of a replay that died early,+ # and the filmed illustration (cameras on; its time-out only costs the video); measured:+ # 1.5-6 min of Isaac start, the verifier's first one compiling its shaders, + 9-12 control+ # steps/s+environment_mode = "separate" # verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then+network_mode = "no-network" # Isaac Sim starts and renders offline: every asset is in the image (images/ambench/web_assets.txt)++# Resource limits (docs/PROTOCOL.md §2.10): seal the monitor's record first, before any other sidecar ends the episode.+[[verifier.collect]]+service = "rcb_monitor"+command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90"+timeout_sec = 120++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 8+memory_mb = 24576++[agent]+timeout_sec = 3600.0 # the agent's cutoff: scripts/task_cutoffs.toml, the one table (written by normalize, PROTOCOL §2.12)+# AM-Bench's scripted experts and its datasets are public upstream, so the agent reaches the model APIs and the package+# registries, nothing else (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com", "pypi.org", "files.pythonhosted.org", "deb.debian.org", "security.debian.org", "archive.ubuntu.com", "security.ubuntu.com", "snapshot.ubuntu.com"]++[environment]+build_timeout_sec = 3600.0+cpus = 8+memory_mb = 34816++[verifier.env]+RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/Dockerfile b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/Dockerfilenew file mode 100644index 0000000000..32e315793a--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/Dockerfile@@ -0,0 +1,11 @@+# Separate verifier sandbox (PROTOCOL §4): the same simulator image with the verifier's own copies of the tooling and the+# frozen instance baked in. Nothing the agent did in its container reaches this one -- Harbor uploads only the declared+# artifacts (/app/output/), so a patched success check or a swapped interpreter in the agent container cannot influence+# the verdict.+FROM ghcr.io/mll-lab-nu/eai-ambench:0.1.0+COPY grade.py instance.json rcb_ambench.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /tests+# resource limits: the verifier step and its copy of the limits (docs/PROTOCOL.md §2.10) # rcb-monitor+COPY rcb_limits.py rcb_limits.json /tests/diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/docker-compose.yaml b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/docker-compose.yamlnew file mode 100644index 0000000000..eaf78d197a--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/docker-compose.yaml@@ -0,0 +1,16 @@+# The verifier replays in Isaac Sim, which needs the GPU. Its Kit cache is a TRUSTED volume: Isaac keeps generated+# Python there that Kit imports at startup, so a cache the agent could write must never reach the grader.+services:+ main:+ shm_size: "8gb"+ volumes:+ - rcb_ambench_cache_trusted:/cache+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: 1+ capabilities: [gpu]+volumes:+ rcb_ambench_cache_trusted:diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/grade.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/grade.pynew file mode 100644index 0000000000..580b28b5aa--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/grade.py@@ -0,0 +1,177 @@+"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2++Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a+human-viewable video /logs/verifier/replay.mp4 (the robot's two onboard cameras) plus replay.last.png, filmed AFTER the+verdict by a third process (`rcb_ambench.py film`) with the cameras on: camera rendering makes the physics timing-dependent,+so the verdict replays run without cameras and the video is an illustration that never enters the reward.+Replays `--repeat` times, each in its own FRESH process (`rcb_ambench.py replay`, no cameras), so fresh process == fresh+process is the determinism check. Success requires every replay to complete the task (AM-Bench's own `_get_success`) AND all+final-state hashes to agree, so a lucky non-deterministic run cannot pass. The frozen scene rebuilt here from+tests/instance.json must also match the recorded one (`instance_ok`: the exact state hash of the seeded reset).++Whose failure a 0 is (every path writes a reward; `deterministic`, `grader_error` and `infra_error` are always present):+- the agent's: no file (`missing_trajectory`), another task's trajectory (`wrong_task`), a file that is not a+ trajectory (`bad_trajectory`: not an npz, no `task` / `actions` entry, pickled or object arrays, the wrong shape, NaN/inf,+ more than MAX_STEPS rows), or a replay that does not complete the task or is not deterministic;+- the verifier's (`grader_error` = 1, with `infra_error` = 1: no verdict on the agent): a replay process that ends+ without a result (Isaac died) or runs out of its time limit (`replay_timed_out`), the rebuilt frozen scene not matching+ the recorded instance (`instance_ok` = 0: the host, not the trajectory), or any other error in this script.+"""+from __future__ import annotations+import argparse, json, os, subprocess, sys, time, traceback+import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+# Wall-clock limit of ONE replay process, scaled with the rows that can run (time limits only; the verdict rules do not+# depend on them). The grader accepts up to MAX_STEPS rows, but the episode ends at the task's own episode length (10-26 s+# here: at most 3119 control steps), so later rows never run. Measured on an RTX 4090 host: Isaac start + scene build+# 1.5-6 min (the upper end with other Isaac jobs on the GPU; the verifier's first start also compiles the shaders into its+# fresh Kit cache), then about 12 control steps/s (the onboard cameras render every step). The allowance is REPLAY_STARTUP_S for the start plus the runnable rows at REPLAY_MIN_RATE control steps/s+# (the same for the filming process, whose time-out only ends the video), never below REPLAY_FLOOR_S; task.toml's+# [verifier] timeout_sec fits the three processes of the longest episode, so a replay that is too slow ends here with a+# written reward (`replay_timed_out`), never with Harbor killing the verifier.+REPLAY_FLOOR_S, REPLAY_STARTUP_S, REPLAY_MIN_RATE = 1800.0, 1500.0, 4.0+++def replay_timeout(n_steps: int) -> float:+ return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_steps / REPLAY_MIN_RATE)+++def load_trajectory(path: str, family: str, action_dim: int, max_steps: int):+ """(actions, None), or (None, reward fields) when the file is not a gradable trajectory of this task. Everything+ here is the agent's deliverable: a file that cannot be read is the agent's 0 (`bad_trajectory`), not a grader error."""+ try:+ d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...+ task = str(d["task"]) # no `task` entry: KeyError; an object array: ValueError+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable trajectory: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if task != family:+ return None, {"wrong_task": 1}+ try:+ acts = np.asarray(d["actions"], dtype=np.float32)+ except Exception as exc: # noqa: BLE001+ print(f"[grade] unreadable actions: {exc!r}", file=sys.stderr, flush=True)+ return None, {"bad_trajectory": 1}+ if acts.ndim != 2 or acts.shape[1] != action_dim or acts.shape[0] > max_steps or not np.all(np.isfinite(acts)):+ return None, {"bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0}+ return acts, None+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)+ ap.add_argument("--no-video", action="store_true"); ap.add_argument("--video-fps", type=int, default=30)+ a = ap.parse_args()+ # Agent interaction cost from the tooling's append-only log (whole debugging history, not just the deliverable).+ # The log lives in the agent's container, so these fields are SELF-REPORTED cost accounting, not evidence+ # (agent_cost_self_reported = 1); the parser must survive any content the agent may have written there.+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ try:+ with open("/app/output/rcb_session_log.jsonl") as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000: break+ try:+ e = json.loads(line); ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start": cost["agent_sessions"] += 1+ elif ev == "reset": cost["agent_resets"] += 1+ elif ev == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ elif ev == "record": cost["agent_records"] += 1+ elif ev == "replay": cost["agent_replays"] += 1+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict+ continue+ except Exception: # noqa: BLE001+ pass+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions must not be counted+ ZERO = {"success": 0, "deterministic": 0, "grader_error": 0, "infra_error": 0} # an early exit: the agent's 0+ ERR = {"success": 0, "deterministic": 0, "grader_error": 1, "infra_error": 1} # no verdict on the agent+ if not os.path.isfile(a.traj):+ write(False, {**ZERO, "missing_trajectory": 1, **cost}); return 0+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling+ from rcb_ambench import MAX_STEPS, ACTION_DIM+ inst = json.load(open(a.instance)); env_id = inst["env_id"]+ acts, bad = load_trajectory(a.traj, env_id, ACTION_DIM, MAX_STEPS)+ if bad is not None:+ write(False, {**ZERO, **bad, **cost}); return 0+ tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_ambench.py")+ runnable = min(int(acts.shape[0]), int(round(float(inst["episode_length_s"]) * int(inst["control_hz"]))))+ t0 = time.time(); runs = []+ attempts = []+ for i in range(a.repeat):+ limit = replay_timeout(runnable)+ for attempt in (1, 2): # a process that died without a result (Isaac) is run once more+ cmd = [sys.executable, tool, "replay", "--instance", a.instance, "--traj", a.traj]+ try:+ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})+ stdout, run = p.stdout, {"error": f"replay process rc={p.returncode}"}+ except subprocess.TimeoutExpired as exc:+ print(f"[grade] replay {i + 1} exceeded its {limit:.0f} s limit ({len(acts)} rows)", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_timed_out": 1, "replay_timeout_s": round(limit, 1), "n_actions": int(len(acts)),+ "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ for line in stdout.splitlines(): # the last JSON object the CLI printed (Isaac writes to stdout too)+ if line.startswith("{"):+ try:+ v = json.loads(line)+ except ValueError:+ continue+ if isinstance(v, dict): run = v+ print(f"[grade] replay {i + 1}: {json.dumps(run)[:800]}", file=sys.stderr, flush=True)+ attempts.append(attempt)+ if "replays" in run or attempt == 2:+ break+ print(f"[grade] replay {i + 1} gave no result ({run.get('error')}): running it once more", file=sys.stderr, flush=True)+ runs.append(run)+ outs = [(r.get("replays") or [{}])[0] for r in runs]+ if any("error" in r or not o for r, o in zip(runs, outs)):+ print(f"[grade] a replay process gave no result: {[r.get('error') for r in runs]}", file=sys.stderr, flush=True)+ write(False, {**ERR, "replay_failed": 1, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0+ replay_wall = round(time.time() - t0, 1)+ all_success = all(o.get("success") for o in outs)+ deterministic = len({o.get("state_sha") for o in outs}) == 1+ instance_ok = all(bool(r.get("instance_matches")) for r in runs)+ ok = all_success and deterministic and instance_ok+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "replays": len(outs),+ "sim_steps": int(outs[0].get("control_steps") or 0), "sim_time_s": float(outs[0].get("sim_time_s") or 0.0),+ "timed_out": int(outs[-1].get("end_reason") == "timeout"),+ "replay_wall_s": replay_wall, "replay_timeout_s": round(limit, 1),+ # the rebuilt frozen scene is not the recorded one: this host, not the trajectory (no verdict on the agent)+ "grader_error": int(not instance_ok), "infra_error": int(not instance_ok),+ "replay_retries": int(sum(x - 1 for x in attempts)), **cost}+ write(ok, out) # the verdict is written before the illustration is filmed+ film = {}+ if not a.no_video: # an illustration after the verdict: never part of the reward+ try:+ p = subprocess.run([sys.executable, tool, "film", "--instance", a.instance, "--traj", a.traj, "--video",+ os.path.join(LOG_DIR, "replay.mp4"), "--fps", str(a.video_fps)], stdout=subprocess.PIPE,+ stderr=sys.stderr, text=True, timeout=replay_timeout(runnable), env={**os.environ, "RCB_SESSION_LOG": ""})+ for line in p.stdout.splitlines():+ if line.startswith("{"):+ try:+ film = json.loads(line).get("film") or {}+ except (ValueError, AttributeError):+ pass+ except Exception as exc: # noqa: BLE001 — a time-out or a crash only costs the video+ print(f"[grade] filming failed: {exc!r}"[:300], file=sys.stderr, flush=True)+ out.update(video_rendered=int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))),+ video_episode_success=int(bool(film.get("success"))))+ write(ok, out)+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {**ERR, **cost})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/instance.json b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/instance.jsonnew file mode 100644index 0000000000..b8a814fc56--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/instance.json@@ -0,0 +1,9 @@+{+ "env_id": "RotateValve-Am-FAHexa-Abs-PID-Direct-v0",+ "seed": 0,+ "task": "RotateValve",+ "action_dim": 8,+ "control_hz": 120,+ "episode_length_s": 20.0,+ "initial_sha": "5bfceb57120de994dca306348115910883573b611ba46d353754ebd5911772d4"+}diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_ambench.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_ambench.pynew file mode 100644index 0000000000..623d3522c8--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_ambench.py@@ -0,0 +1,451 @@+"""+rcb_ambench.py — task-local tooling for AM-Bench (github.com/ambench/ambench @ 60bf5b7, Apache-2.0: aerial manipulation on+Isaac Lab / Isaac Sim 5.1): frozen task instance, privileged state, action recording, fresh-process replay. Same shape as+the other benchmarks' rcb_<bench>.py.++Concepts+--------+instance : one AM-Bench environment (a task with one robot and controller profile, e.g.+ PressButton-Am-FAHexa-Abs-PID-Direct-v0) and the seed of its reset (instance.json). AM-Bench draws the task's+ variation (where the button, the slider, the valve or the ball is) from the seeded reset; `initial_sha` is the+ hash of the start it builds, which every replay checks (`instance_matches`).+trajectory : the (T, 8) actions handed to the environment, one row per control step (120 Hz: one physics step of 1/120 s):+ the absolute end-effector target, position x y z (m, world frame, relative to the environment's origin),+ orientation as a unit quaternion w x y z, and the gripper command (-1 = closed .. +1 = open). AM-Bench's own+ low-level controller (the profile's PID) and floating-base inverse kinematics turn it into rotor thrusts and arm+ joint targets inside every step. Physics is PhysX on the GPU: a fresh process replays the same rows to the+ same state (the first episode of a process; later resets in the same process need not be bit-identical)+ WITHOUT the onboard cameras. With them (`Session(cameras=True)`), the per-step rendering makes PhysX's results+ depend on timing (measured: two fresh replays of the same rows part after a few hundred steps), so the+ grader, the reference recordings and a default Session run without them; cameras are for looking only.+success : AM-Bench's own `_get_success` of the task (its `terminated` signal); the episode ends at the first control step+ where it holds, or at the task's episode length (a time-out, not a success). Rows after the end never run.+ Isaac Lab resets the scene inside the step that ends an episode; the tooling keeps the end state's hash+ (taken just before that reset) as the episode's `state_sha`.+ RotateValve: the valve's `base_to_shaft` joint has no limits, and PhysX reports an articulation's unlimited+ revolute joint wrapped into [-pi, pi] (omni.physx 107.3, Isaac Sim 5.1), so AM-Bench's check `joint_pos >=+ 17/18 pi` would also pass a counter-clockwise turn of 190 degrees. The tooling gives that task's+ `_get_success` the unwrapped angle instead: the sum of the joint's per-step changes since the reset (one+ physics step moves it at most 5 rad/s / 120 Hz, far less than pi), so only the clockwise turn the+ instruction asks for counts. Physics, states and hashes are unchanged; the episode just does not end on a+ wrapped reading.++CLI+---+ python rcb_ambench.py replay --instance instance.json --traj traj.npz # one fresh-process replay (the grader's, no cameras)+ python rcb_ambench.py film --instance instance.json --traj traj.npz --video replay.mp4 # the same rows with the cameras on,+ filmed: an illustration only (camera rendering changes the numerics; never a verdict)+ python rcb_ambench.py make-instance --env-id <id> --seed 0 --out instance.json+ python rcb_ambench.py run-actions --instance instance.json --actions actions.npy --out traj.npz+"""+from __future__ import annotations++import os+for _k, _v in (("OMNI_KIT_ACCEPT_EULA", "YES"), ("ACCEPT_EULA", "Y"), ("OMNI_KIT_ALLOW_ROOT", "1"), ("PYTHONUNBUFFERED", "1"),+ ("JAX_PLATFORMS", "cpu")):+ os.environ.setdefault(_k, _v)++import argparse+import hashlib+import json+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++ACTION_DIM = 8+CONTROL_HZ = 120+MAX_STEPS = 8000 # a technical cap above every task's episode length (at most 60 s = 7200 steps)+ASSET_ROOT = "/opt/isaac-assets/Assets/Isaac/5.1" # baked web assets (images/ambench/web_assets.txt)+CAMERAS = ("ee_camera", "base_camera") # the robot profile's onboard cameras (384 x 384 RGB), only with Session(cameras=True)+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")+_APP = None+_APP_CAMERAS = False+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG) or ".", exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ev": ev, "t": round(time.time(), 3), "pid": os.getpid(), **kw}) + "\n")+ except OSError:+ pass+++def _launch_app(cameras: bool = False):+ """Isaac Sim, headless, the asset root pointed at the baked copies (no network needed); rendering only with cameras.+ Once per process: the first Session decides."""+ global _APP, _APP_CAMERAS+ if _APP is not None and cameras != _APP_CAMERAS:+ raise RuntimeError(f"this process launched Isaac Sim with cameras={_APP_CAMERAS}: one Session (one setting) per process")+ if _APP is None:+ _APP_CAMERAS = cameras+ from isaaclab.app import AppLauncher+ ns = argparse.Namespace()+ p = argparse.ArgumentParser(); AppLauncher.add_app_launcher_args(p)+ ns = p.parse_args([])+ ns.headless = True; ns.enable_cameras = bool(cameras); ns.device = "cuda:0"+ ns.kit_args = f"--/persistent/isaac/asset_root/cloud={ASSET_ROOT}"+ _APP = AppLauncher(ns).app+ return _APP+++def load_instance(instance) -> dict:+ return instance if isinstance(instance, dict) else json.loads(Path(instance).read_text())+++def _np(x) -> np.ndarray:+ return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)+++class Session:+ """One AM-Bench environment of one frozen instance. One per process (Isaac Sim runs once per process)."""++ def __init__(self, instance="/app/instance.json", *, strict: bool = False, cameras: bool = False):+ _launch_app(cameras)+ self.cameras = bool(cameras)+ import gymnasium as gym+ import torch+ import ambench.tasks # noqa: F401 (registers the environments)+ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg+ self.torch = torch+ self.instance = load_instance(instance)+ I = self.instance+ self.env_id, self.seed = I["env_id"], int(I["seed"])+ cfg = parse_env_cfg(self.env_id, device="cuda:0", num_envs=1)+ cfg.seed = self.seed+ if not self.cameras: # the robot profile's onboard cameras (and any scene camera) are not built: no rendering+ cfg.robot_profile.ee_camera = None; cfg.robot_profile.base_camera = None; cfg.scene_camera_cfg = None+ self.env = gym.make(self.env_id, cfg=cfg).unwrapped+ # Isaac Lab resets an environment whose episode ended INSIDE that step (DirectRLEnv.step -> _reset_idx), so after the+ # last step the scene is already the next episode's start: keep the end state's hash, taken just before that reset+ self._in_step = False; self.end_sha = None+ _reset_idx = self.env._reset_idx++ def _keep_end_state(env_ids, _reset_idx=_reset_idx):+ if self._in_step:+ self.end_sha = self.state_sha()+ return _reset_idx(env_ids)+ self.env._reset_idx = _keep_end_state+ self._valve = None+ if self.env_id.startswith("RotateValve-"):+ self._unwrap_valve_angle()+ self.n_resets = 0; self.n_steps_total = 0; self.n_clipped = 0+ self._video = None+ self.reset()+ self.initial_sha = self.state_sha()+ want = I.get("initial_sha")+ self.instance_matches = want is None or want == self.initial_sha+ if strict and not self.instance_matches:+ raise RuntimeError(f"the rebuilt scene differs from the frozen instance: {self.initial_sha} != {want}")+ _slog("session_start", env_id=self.env_id, instance_matches=self.instance_matches, cameras=self.cameras)++ # ------------------------------------------------------------------ episode+ def reset(self) -> None:+ """Back to the frozen instance (the seeded reset). Only the first episode of a process is guaranteed bit-identical+ to a fresh process's: check a trajectory with the `replay` CLI."""+ with self.torch.inference_mode(): # as step(): after a step Isaac Lab's buffers are inference tensors+ self.obs, _ = self.env.reset(seed=self.seed)+ self.end_sha = None+ if self._valve is not None:+ self._valve.update(prev=None, angle=None) # the joint is back at 0 rad: count from here+ self.rows: list[np.ndarray] = []+ self.done = False; self.succeeded = False; self.timed_out = False+ self.n_resets += 1+ if self.n_resets > 1:+ _slog("reset", env_id=self.env_id)++ def _unwrap_valve_angle(self) -> None:+ """RotateValve's success on the valve's unwrapped angle (see the module docstring): AM-Bench's `_get_success`, with+ the joint position PhysX reports in [-pi, pi] replaced by the sum of its per-step changes since the reset."""+ env, torch, v = self.env, self.torch, {"prev": None, "angle": None}+ self._valve = v+ two_pi = 2.0 * float(np.pi)++ def _get_success():+ q = env.valve_object.data.joint_pos[:, env.valve_joint_idx].clone()+ if v["prev"] is None: # the first step after a reset, from 0 rad (|q| < 0.05 rad here)+ angle = q+ else:+ angle = v["angle"] + torch.remainder(q - v["prev"] + np.pi, two_pi) - np.pi+ v.update(prev=q, angle=angle)+ target = env.cfg.valve_target_angle+ rotated = angle >= target+ return rotated, {"valve_engaged": angle >= env.cfg.valve_engagement_ratio * target, "valve_rotated": rotated}+ env._get_success = _get_success++ def valve_angle(self) -> float | None:+ """RotateValve: the valve's unwrapped angle in rad since the reset (positive = clockwise from the robot's side),+ what the success check reads; None in other tasks or before the first step."""+ if self._valve is None or self._valve["angle"] is None:+ return None+ return float(_np(self._valve["angle"]).reshape(-1)[0])++ @property+ def n_steps(self) -> int:+ return len(self.rows)++ def clip(self, row) -> tuple[np.ndarray, int]:+ a = np.asarray(row, dtype=np.float64).reshape(-1).copy()+ if a.size != ACTION_DIM or not np.all(np.isfinite(a)):+ raise ValueError(f"an action row has {ACTION_DIM} finite values (x y z qw qx qy qz gripper), got {a.size}")+ n = 0+ g = float(np.clip(a[7], -1.0, 1.0)); n += int(g != a[7]); a[7] = g+ if float(np.linalg.norm(a[3:7])) < 1e-9: # passed on as it is (AM-Bench's controller takes the quaternion it gets)+ raise ValueError("the action's quaternion has zero length")+ return a, n++ def step(self, row) -> bool:+ """One control step (1/120 s). Returns True when the episode is over; a step after that executes nothing."""+ if self.done:+ return True+ a, n = self.clip(row)+ self.n_clipped += n+ t = self.torch.as_tensor(a, dtype=self.torch.float32, device=self.env.device).reshape(1, ACTION_DIM)+ self._in_step = True+ try:+ with self.torch.inference_mode():+ self.obs, _, term, trunc, _ = self.env.step(t)+ finally:+ self._in_step = False+ self.rows.append(a)+ self.n_steps_total += 1+ self.succeeded = bool(_np(term).reshape(-1)[0])+ self.timed_out = bool(_np(trunc).reshape(-1)[0]) and not self.succeeded+ self.done = self.succeeded or self.timed_out or self.n_steps >= MAX_STEPS+ if self._video is not None:+ self._video_add()+ return self.done++ def success(self) -> bool:+ return self.succeeded++ def end_reason(self) -> str | None:+ if self.succeeded:+ return "success"+ if self.timed_out:+ return "timeout"+ return "step_cap" if self.done else None++ def hold_action(self) -> np.ndarray:+ """A row that keeps the current end-effector target and gripper command."""+ cp = self.env.control_pipeline+ pos = _np(cp.ee_cmd_pos_w[0] - self.env.scene.env_origins[0]).astype(np.float64)+ quat = _np(cp.ee_cmd_quat_w[0]).astype(np.float64)+ g = self.rows[-1][7] if self.rows else 1.0+ return np.r_[pos, quat, g]++ def status(self) -> dict[str, Any]:+ # state_sha: the episode's end state once it is over (taken before Isaac Lab's reset), else the current state+ return {"success": self.succeeded, "done": self.done, "end_reason": self.end_reason(), "control_steps": self.n_steps,+ "sim_time_s": round(self.n_steps / CONTROL_HZ, 4), "episode_length_s": float(self.env.cfg.episode_length_s),+ "resets": self.n_resets, "state_sha": self.end_sha if (self.done and self.end_sha) else self.state_sha()}++ def actions(self) -> np.ndarray:+ return np.asarray(self.rows, dtype=np.float64).reshape(-1, ACTION_DIM)++ def record_start(self) -> None:+ self.reset()++ def record_stop(self) -> np.ndarray:+ return self.actions()++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ self.reset()+ for row in A:+ if self.step(row):+ break+ _slog("replay", env_id=self.env_id, rows=int(len(A)), executed=self.n_steps)+ return {**self.status(), "executed_rows": self.n_steps}++ def save_trajectory(self, actions, path="/app/output/trajectory.npz", meta: dict | None = None) -> None:+ A = np.asarray(actions, dtype=np.float64).reshape(-1, ACTION_DIM)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, task=np.array(self.env_id), actions=A, meta=np.array(json.dumps(meta or {})))++ # ------------------------------------------------------------------ state (privileged)+ def state_sha(self) -> str:+ """sha256 over every articulation's and rigid object's root state, joint positions and velocities."""+ m = hashlib.sha256()+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name in sorted(group):+ d = group[name].data+ for t in (d.root_state_w, getattr(d, "joint_pos", None), getattr(d, "joint_vel", None)):+ if t is not None:+ m.update(name.encode()); m.update(_np(t).tobytes())+ return m.hexdigest()++ def state(self) -> dict[str, Any]:+ """Privileged observation of the task (AM-Bench's own `policy` observation: robot, end effector, task objects and+ goal positions, relative to the environment's origin)."""+ obs = self.obs["policy"][0] if isinstance(self.obs.get("policy"), list) else self.obs.get("policy")+ return {k: _np(v).reshape(-1).tolist() for k, v in (obs.items() if isinstance(obs, dict) else [])}++ def objects(self) -> dict[str, dict]:+ """Every articulation (but the robot) and rigid object of the scene: root pose (wxyz) and velocities, joint state."""+ out, o = {}, _np(self.env.scene.env_origins[0])+ sc = self.env.scene+ for group in (sc.articulations, sc.rigid_objects):+ for name, obj in group.items():+ if name == "robot":+ continue+ rs = _np(obj.data.root_state_w[0])+ ent = {"position": (rs[:3] - o).tolist(), "orientation_wxyz": rs[3:7].tolist(), "velocity": rs[7:10].tolist(),+ "angular_velocity": rs[10:13].tolist()}+ if getattr(obj.data, "joint_pos", None) is not None:+ ent["joint_pos"] = _np(obj.data.joint_pos[0]).tolist(); ent["joint_names"] = list(obj.joint_names)+ out[name] = ent+ return out++ def proprio(self) -> dict[str, Any]:+ """The robot's own state: base and end-effector poses (world, relative to the env origin; wxyz) and velocities, the+ gripper opening and the arm joints, the current end-effector command."""+ e = self.env; o = _np(e.scene.env_origins[0])+ base = _np(e.robot.data.body_link_state_w[0, e.base_link_idx]); ee = _np(e.robot.data.body_link_state_w[0, e.ee_link_idx])+ jp = _np(e.robot.data.joint_pos[0]); jv = _np(e.robot.data.joint_vel[0])+ return {"base_pose": np.r_[base[:3] - o, base[3:7]].tolist(), "base_vel": base[7:13].tolist(),+ "ee_pose": np.r_[ee[:3] - o, ee[3:7]].tolist(), "ee_vel": ee[7:13].tolist(),+ "gripper_width": float(np.sum(jp[e.gripper_joint_ids])),+ "arm_joint_pos": jp[e.arm_joint_ids].tolist(), "arm_joint_vel": jv[e.arm_joint_ids].tolist(),+ "command": self.hold_action().tolist()}++ # ------------------------------------------------------------------ cameras+ def render_frame(self, camera: str = "ee_camera") -> np.ndarray:+ """RGB uint8 (384, 384, 3) of the robot's onboard camera `ee_camera` (at the end effector) or `base_camera` (on the+ airframe, looking forward), as of the last step. Only in a Session(cameras=True): the cameras render every step+ and that makes the physics timing-dependent, so check what you find there with the replay CLI (no cameras)."""+ if not self.cameras:+ raise RuntimeError("no cameras in this Session: start the process with Session(..., cameras=True) to look "+ "(its numerics differ from the grader's camera-free replay; check trajectories with the CLI)")+ cam = getattr(self.env, camera, None)+ if cam is None:+ raise KeyError(f"no camera {camera!r}; cameras: {[c for c in CAMERAS if getattr(self.env, c, None) is not None]}")+ return _np(cam.data.output["rgb"][0])[..., :3].astype(np.uint8)++ def start_video(self, path, fps: int = 30, camera: str = "ee_camera") -> None:+ import imageio.v2 as imageio+ self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),+ "every": max(1, round(CONTROL_HZ / fps)), "camera": camera, "path": str(path)}+ self._video_add(force=True)++ def _video_add(self, force: bool = False) -> None:+ v = self._video+ if force or self.n_steps % v["every"] == 0 or self.done:+ frames = [self.render_frame(c) for c in CAMERAS if getattr(self.env, c, None) is not None]+ v["w"].append_data(np.concatenate(frames, axis=1))++ def stop_video(self):+ v, self._video = self._video, None+ if v:+ v["w"].close()+ return v["path"]++ def close(self) -> None:+ _slog("session_end", env_id=self.env_id, sim_steps=self.n_steps_total, resets=self.n_resets)+ try:+ self.env.close()+ except Exception: # noqa: BLE001+ pass+++def load_trajectory(path, env_id: str) -> np.ndarray:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != env_id:+ raise ValueError(f"trajectory is for {str(d['task'])!r}, not {env_id!r}")+ A = np.asarray(d["actions"], dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != ACTION_DIM or A.shape[0] > MAX_STEPS or not np.all(np.isfinite(A)):+ raise ValueError(f"actions must be a finite (T, {ACTION_DIM}) array with T <= {MAX_STEPS}, got {list(A.shape)}")+ return A+++def _replay_rows(s: "Session", A: np.ndarray) -> dict:+ for row in A: # the process's first episode+ if s.step(row):+ break+ res = s.status()+ return {**{k: res[k] for k in ("success", "state_sha", "end_reason", "control_steps", "sim_time_s")}, "executed_rows": s.n_steps}+++def _cli_replay(a) -> int:+ """The grader's replay: a fresh process, no cameras (bit-reproducible), the process's first episode."""+ t0 = time.time()+ s = Session(a.instance)+ out: dict[str, Any] = {"task": s.env_id, "instance_matches": bool(s.instance_matches), "initial_sha": s.initial_sha}+ try:+ A = load_trajectory(a.traj, s.env_id)+ except Exception as exc: # noqa: BLE001+ out["error"] = f"bad trajectory: {exc!r}"[:300]; print(json.dumps(out), flush=True); return 2+ out["replays"] = [_replay_rows(s, A)]+ out["n_actions"] = int(len(A)); out["replay_wall_s"] = round(time.time() - t0, 2)+ print(json.dumps(out), flush=True)+ s.close()+ return 0+++def _cli_film(a) -> int:+ """An illustration, never a verdict: the rows with the onboard cameras on, filmed (both cameras side by side) plus the+ last end-effector frame. Camera rendering makes the physics timing-dependent, so this episode may end differently."""+ t0 = time.time()+ s = Session(a.instance, cameras=True)+ A = load_trajectory(a.traj, s.env_id)+ s.start_video(a.video, fps=a.fps)+ res = _replay_rows(s, A)+ s.stop_video()+ from PIL import Image+ Image.fromarray(s.render_frame("ee_camera")).save(str(Path(a.video).with_suffix(".last.png")))+ print(json.dumps({"task": s.env_id, "film": res, "video": a.video, "film_wall_s": round(time.time() - t0, 2)}), flush=True)+ s.close()+ return 0+++def _cli_make_instance(a) -> int:+ inst = {"env_id": a.env_id, "seed": int(a.seed)}+ s = Session(inst)+ inst.update({"task": a.env_id.split("-")[0], "action_dim": ACTION_DIM, "control_hz": CONTROL_HZ,+ "episode_length_s": float(s.env.cfg.episode_length_s), "initial_sha": s.initial_sha})+ Path(a.out).write_text(json.dumps(inst, indent=1) + "\n")+ print(json.dumps({"env_id": a.env_id, "initial_sha": s.initial_sha}), flush=True)+ s.close()+ return 0+++def _cli_run_actions(a) -> int:+ s = Session(a.instance, strict=True)+ for row in np.load(a.actions): # the process's first episode (no second reset), as the grader's+ if s.step(row):+ break+ res = {**s.status(), "executed_rows": s.n_steps}+ s.save_trajectory(s.actions(), a.out, meta={"source": "reference rows"})+ print(json.dumps({k: res[k] for k in ("success", "end_reason", "state_sha", "control_steps", "executed_rows", "sim_time_s")}), flush=True)+ s.close()+ return 0+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay"); r.add_argument("--instance", required=True); r.add_argument("--traj", required=True)+ f = sub.add_parser("film"); f.add_argument("--instance", required=True); f.add_argument("--traj", required=True)+ f.add_argument("--video", required=True); f.add_argument("--fps", type=int, default=30)+ m = sub.add_parser("make-instance"); m.add_argument("--env-id", required=True); m.add_argument("--seed", type=int, default=0); m.add_argument("--out", required=True)+ x = sub.add_parser("run-actions"); x.add_argument("--instance", required=True); x.add_argument("--actions", required=True); x.add_argument("--out", required=True)+ a = ap.parse_args(argv)+ global SESSION_LOG+ SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "") # the CLI logs nothing unless asked+ try:+ rc = {"replay": _cli_replay, "film": _cli_film, "make-instance": _cli_make_instance, "run-actions": _cli_run_actions}[a.cmd](a)+ except BaseException: # noqa: BLE001 — Isaac Sim can hang at exit after an error: report it and leave at once+ import traceback+ traceback.print_exc(); rc = 3+ sys.stdout.flush(); sys.stderr.flush()+ os._exit(rc) # Isaac Sim's shutdown can hang or crash after the result line; the result is printed+++if __name__ == "__main__":+ main()diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_limits.json b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_limits.jsonnew file mode 100644index 0000000000..6d37d09d1f--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_limits.json@@ -0,0 +1,33 @@+{+ "caps": {+ "main": {+ "cpus": 8.0,+ "memory_gb": 34.0,+ "pids": 16384+ }+ },+ "disk_exclude": [],+ "disk_paths": [+ "/app",+ "/tmp",+ "/root"+ ],+ "disk_tick_sec": 60,+ "format": "rcb-limits/1",+ "gpu": true,+ "max_disk_gb": 20.0,+ "max_gpu_memory_gb": 16.0,+ "max_memory_gb": 28.0,+ "max_processes": 512,+ "mode": "privileged",+ "scope": "trial",+ "scope_services": [+ "main"+ ],+ "sustain_sec": 60.0,+ "task": "ambench-rotate-valve-fahexa-i00-privileged",+ "tick_sec": 5,+ "trial_max_gpu_memory_gb": 16.0,+ "trial_max_memory_gb": 28.0,+ "window_sec": 120.0+}diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_limits.py b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_limits.pynew file mode 100644index 0000000000..a979bcdaff--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/rcb_limits.py@@ -0,0 +1,457 @@+#!/usr/bin/env python3+"""Resource limits (docs/PROTOCOL.md §2.10): the sustained-violation rule, shared by the monitor sidecar (monitor.py) and+the verifier step, and the verifier step itself.++Copies of this file live in every task (environment/rcb_monitor/ for the monitor, tests/ for the verifier), byte-identical+to scripts/rcb_monitor/rcb_limits.py (ci_checks/check-monitor.py). Python 3.8+, standard library only: it runs inside+benchmark verifier images.++ python3 /tests/rcb_limits.py verify # test.sh runs it on exit (trap), after the grader+ python3 /tests/rcb_limits.py sanitize /app/output # test.sh runs it before the grader (see sanitize())++The verifier step reads the monitor's sealed record (/var/rcb-monitor/, collected from the rcb_monitor sidecar, a+channel the agent cannot write), recomputes every violation from the raw samples with its own copy of the limits+(/tests/rcb_limits.json), and adds to /logs/verifier/reward.json:+ always: resource_enforced, limits_violation_observed, resource_monitor_missing, peak_gpu_memory_gb, peak_memory_gb,+ peak_processes, peak_disk_gb, resource_emergency_kills; over_<metric>=1 for every violation; the kernel's+ OOM kills in the record: resource_oom_kills (in the scope, at the container's own memory cap: the+ violation), resource_host_oom_kills (in the scope, not at its cap: the host's OOM killer or an enclosing+ cgroup's), resource_service_oom_kills (in a benchmark-owned service that is only recorded: the simulator+ sidecar of standard modes, RoboPaint's scorer)+ enforced (the record's mode, RCB_LIMITS_ENFORCE=1) and violated: resource_limit_exceeded=1, success=0 (reward.txt 0),+ success_before_limits = the grader's success+ enforced and no usable record: infra_error=1 (not a result). Not enforced (the default): a missing or unusable+ record is only reported (resource_monitor_missing=1); the grader's verdict stands.+ enforced, no violation, and a process in the scope was killed by an OOM killer that is not its own cap's:+ infra_error=1, resource_host_oom=1 (not a result: another trial's or the host's doing, never the agent's)+ RCB_LIMITS_ENFORCE neither 0/1/true/false: infra_error=1, resource_switch_error=1 (nobody knows what was asked for)+ in both modes: the kernel OOM-killed a benchmark-owned service and the grader's verdict is not a success:+ infra_error=1, resource_service_oom=1 (PROTOCOL §2.10: such a service is recorded, never a failure; an+ episode that ended without success after its simulator was killed for memory is not the agent's 0). A+ success stands: the service recovered and the grader accepted the episode.+Wherever this step says "not a result" (infra_error=1) it also sets success=0 and reward.txt 0 and keeps the grader's+verdict in success_before_limits, so that no reader sees a success next to an infrastructure error.+With the default (not enforced, a readable switch) the step changes nothing of the grader's verdict (reward.txt,+success, reward) and sets infra_error only in the one case above (a benchmark-owned service OOM-killed, no success).+A violation is a limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill+in the scope at the container's own memory cap (the monitor's `oom` event with cause "cap"). The monitor's emergency+kills (host protection) are counted, never violations by themselves.+The reasons, in words, go to /logs/verifier/resource_limits.json. If this step itself fails, it says so in reward.json+(resource_step_error=1, resource_monitor_missing=1; infra_error=1 when the switch asks for enforcement).+"""+import json+import os+import stat+import sys++FORMAT = "rcb-monitor/1"+RECORD = os.environ.get("RCB_MONITOR_RECORD", "/var/rcb-monitor")+METRICS = ("gpu_memory_gb", "memory_gb", "processes", "disk_gb")+LIMIT_KEY = {"gpu_memory_gb": "max_gpu_memory_gb", "memory_gb": "max_memory_gb", "processes": "max_processes",+ "disk_gb": "max_disk_gb"}+MAX_GAP_FRACTION = 0.10 # more of the agent phase than this unobserved: the record is not usable+++def parse_switch(value):+ """RCB_LIMITS_ENFORCE -> (1 or 0, None), or (0, why) for a value that is neither on nor off (never a silent off)."""+ s = str("" if value is None else value).strip().lower()+ if s in ("", "0", "false"):+ return 0, None+ if s in ("1", "true"):+ return 1, None+ return 0, f"RCB_LIMITS_ENFORCE={value!r} is not one of 0, 1, true, false"+++def sustained(series, limit, sustain_sec, window_sec, tick_sec):+ """First time a sustained violation is confirmed, or None.++ series: [(t, value)] in time order (value None = not measured: never over). Each sample stands for the time to the+ next one (the last for none), at most 3 ticks (a gap in the record never counts against the agent). A violation is confirmed at the+ first moment when the time over `limit` within the last `window_sec` reaches `sustain_sec` (so going under for a+ moment does not reset it)."""+ if limit is None or limit <= 0:+ return None+ iv = [] # (start, end) of the time over the limit+ for i, (t, v) in enumerate(series):+ if i + 1 == len(series):+ break # the last sample has not lasted yet+ d = max(0.0, min(series[i + 1][0] - t, 3 * tick_sec))+ if v is not None and v > limit and d > 0:+ if iv and abs(iv[-1][1] - t) < 1e-9:+ iv[-1] = (iv[-1][0], t + d)+ else:+ iv.append((t, t + d))+ if not iv:+ return None+ # the over-time in a window (e - W, e] only grows while e moves through an interval: check each interval's end,+ # and inside the first one that reaches it, bisect for the exact moment+ def over_in(e):+ """Over-time inside (e - window, e]."""+ s = e - window_sec+ tot = 0.0+ for a, b in iv:+ if b <= s:+ continue+ if a >= e:+ break+ tot += min(b, e) - max(a, s)+ return tot++ for a, b in iv:+ if over_in(b) + 1e-9 >= sustain_sec:+ # bisect for the first moment in [a, b] at which it is reached+ x, y = a, b+ for _ in range(40):+ m = (x + y) / 2+ if over_in(m) + 1e-9 >= sustain_sec:+ y = m+ else:+ x = m+ return y+ return None+++def consecutive(series, limit, n=2):+ """First time `n` consecutive measured samples are over `limit` (disk: measured once a minute), or None."""+ if limit is None or limit <= 0:+ return None+ run = 0+ for t, v in series:+ if v is None:+ continue+ run = run + 1 if v > limit else 0+ if run >= n:+ return t+ return None+++def violations(samples, limits, events=()):+ """Every violation in a record: [{metric, limit, at, peak}] (empty: none). samples: the record's sample dicts.+ A limit exceeded for sustain_sec within window_sec (disk: two measurements in a row), or a kernel OOM kill in the+ scope at the container's own memory cap (cause "cap": the cgroup's own `oom` counter rose with the kill). A kill+ by the host's OOM killer (any other cause) is not the trial's doing and never a violation: oom_kills() counts it.+ The monitor's own `emergency_kill` events protect the host and are not violations (PROTOCOL §2.10)."""+ tick = float(limits.get("tick_sec", 5))+ sustain = float(limits.get("sustain_sec", 60))+ window = float(limits.get("window_sec", 2 * sustain))+ out = []+ for m in METRICS:+ lim = limits.get(LIMIT_KEY[m])+ if lim is None:+ continue+ lim = float(lim)+ ser = [(s["t"], (s.get("scope") or {}).get(m)) for s in samples]+ at = consecutive(ser, lim) if m == "disk_gb" else sustained(ser, lim, sustain, window, tick)+ if at is not None:+ peak = max((v for _, v in ser if v is not None), default=None)+ out.append({"metric": m, "limit": lim, "at": round(at, 2), "peak": peak})+ for e in events:+ if isinstance(e, dict) and e.get("event") == "oom" and e.get("scope") and e.get("cause") == "cap":+ out.append({"metric": "oom", "limit": None, "at": e.get("t"), "peak": e.get("count"),+ "service": e.get("role")})+ return sorted(out, key=lambda v: v["at"] if isinstance(v["at"], (int, float)) else 0)+++def oom_kills(events):+ """The kernel's OOM kills in a record: {"cap": in the scope at the container's own memory cap (the violation),+ "host": in the scope by another OOM killer (the host's, an enclosing cgroup's; also an event that does not say),+ "service": in a benchmark-owned service that is only recorded (whatever the cause)}."""+ out = {"cap": 0, "host": 0, "service": 0}+ for e in events:+ if not isinstance(e, dict) or e.get("event") != "oom":+ continue+ n = e.get("count")+ n = int(n) if isinstance(n, (int, float)) and not isinstance(n, bool) and n == n and 1 <= n < 1e9 else 1+ out["service" if not e.get("scope") else "cap" if e.get("cause") == "cap" else "host"] += n+ return out+++def peaks(samples):+ p = {}+ for m in METRICS:+ vals = [(s.get("scope") or {}).get(m) for s in samples]+ vals = [v for v in vals if v is not None]+ p[m] = round(max(vals), 3) if vals else 0.0+ return p+++def read_jsonl(path):+ out = []+ try:+ with open(path) as f:+ for line in f:+ line = line.strip()+ if line:+ try:+ out.append(json.loads(line))+ except ValueError:+ pass # a torn last line (the monitor was killed mid-write)+ except OSError:+ pass+ return out+++def read_json(path):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError):+ return None+++def load_record(record=None):+ """(summary or None, samples, events)."""+ record = record or os.environ.get("RCB_MONITOR_RECORD", RECORD)+ return (read_json(os.path.join(record, "summary.json")), read_jsonl(os.path.join(record, "samples.jsonl")),+ [e for e in read_jsonl(os.path.join(record, "events.jsonl")) if isinstance(e, dict)])+++def record_problems(summary, samples, events, limits):+ """Why a record cannot be used ([] = usable)."""+ why = []+ if not summary:+ why.append("no sealed record (/var/rcb-monitor/summary.json missing: the monitor did not run, crashed, or was not collected)")+ elif summary.get("format") != FORMAT:+ why.append(f"record format {summary.get('format')!r}, expected {FORMAT}")+ if not samples:+ why.append("no samples")+ fatal = [e for e in events if e.get("event") == "fatal"]+ if fatal:+ why.append("monitor fatal: " + "; ".join(str(e.get("why")) for e in fatal)[:300])+ if samples and summary and not summary.get("scope_seen"):+ why.append("the monitor never found the containers it watches (no beacon seen)")+ if float(limits.get("max_gpu_memory_gb") or 0) > 0 and samples:+ blind = sum(1 for s in samples if (s.get("scope") or {}).get("gpu_unmeasured"))+ if blind / len(samples) > MAX_GAP_FRACTION:+ why.append(f"NVML did not tell the GPU memory of processes in scope in {blind} of {len(samples)} samples "+ "(MIG / vGPU?): the GPU-memory limit was not measured")+ if len(samples) >= 2:+ tick = float(limits.get("tick_sec", 5))+ span = samples[-1]["t"] - samples[0]["t"]+ gaps = sum(max(0.0, b["t"] - a["t"] - 3 * tick) for a, b in zip(samples, samples[1:]))+ if span > 0 and gaps / span > MAX_GAP_FRACTION:+ why.append(f"{gaps:.0f} s of {span:.0f} s unobserved")+ return why+++def switch_of(summary):+ """(enforce, why the switch cannot be read or None): the record's mode when there is a record, else this step's+ own environment (the same run-time variable, task.toml [verifier.env])."""+ if summary and summary.get("switch_error"):+ return 0, str(summary["switch_error"])+ if summary and "enforce" in summary:+ return parse_switch(summary.get("enforce"))+ return parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+++def not_a_result(reward, add):+ """This step found that the trial is not a result (infra_error=1): no success is left beside it. The grader's+ verdict stays readable in success_before_limits."""+ add["infra_error"] = 1+ add["success_before_limits"] = int(bool(reward.get("success", 0)))+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+++def verify(argv=()):+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ tests = os.path.dirname(os.path.abspath(__file__))+ limits_file = read_json(os.path.join(tests, "rcb_limits.json"))+ limits = limits_file or {}+ summary, samples, events = load_record()+ enforce, switch_error = switch_of(summary)+ rj_path, rt_path = os.path.join(log, "reward.json"), os.path.join(log, "reward.txt")+ reward = read_json(rj_path)+ have_grade = isinstance(reward, dict)+ reward = reward if have_grade else {}+ problems = record_problems(summary, samples, events, limits)+ if limits_file is None:+ problems.append("the verifier's copy of the limits (tests/rcb_limits.json) is missing or unreadable")+ if switch_error and not any(switch_error in p for p in problems):+ problems.append(switch_error)+ viol = violations(samples, limits, events) if samples else []+ pk = peaks(samples)+ emergency = [e for e in events if e.get("event") == "emergency_kill"]+ oom = oom_kills(events)+ detail = {"format": FORMAT, "enforced": enforce, "limits": {k: v for k, v in limits.items()},+ "peaks": pk, "violations": viol, "record_problems": problems, "emergency_kills": emergency,+ "oom_kills": [e for e in events if e.get("event") == "oom"],+ "monitor": {k: (summary or {}).get(k) for k in ("started", "ended", "n_samples", "capabilities", "killed",+ "restarts", "disk_baseline_gb", "disk_partial_walks")}}+ add = {"resource_enforced": enforce, "limits_violation_observed": int(bool(viol)),+ "resource_monitor_missing": int(bool(problems)),+ "peak_gpu_memory_gb": pk["gpu_memory_gb"], "peak_memory_gb": pk["memory_gb"],+ "peak_processes": pk["processes"], "peak_disk_gb": pk["disk_gb"],+ "resource_emergency_kills": len(emergency), "resource_oom_kills": oom["cap"],+ "resource_host_oom_kills": oom["host"], "resource_service_oom_kills": oom["service"]}+ for v in viol:+ add["over_" + v["metric"]] = 1+ failed = void = False # void: this step says "not a result" (infra_error=1) and takes the success away+ if switch_error:+ # nobody knows whether enforcement was asked for: not a result in either mode+ add["resource_switch_error"] = 1+ void = True+ detail["verdict"] = "not a result: " + switch_error+ elif enforce and viol:+ # a confirmed violation fails the trial whatever the deliverable (and wins over a grader's infra flag: the+ # agent's processes were stopped for it)+ failed = True+ add["success_before_limits"] = int(reward.get("success", 0) or 0)+ add["resource_limit_exceeded"] = 1+ add["success"] = 0+ if "reward" in reward:+ add["reward"] = 0+ if reward.get("infra_error"):+ add["grader_infra_error"] = 1+ add["infra_error"] = 0+ detail["verdict"] = "failed: resource limit exceeded (" + ", ".join(v["metric"] for v in viol) + ")"+ elif enforce and problems:+ void = True+ detail["verdict"] = "not a result: the resource monitor's record is not usable"+ elif enforce and oom["host"]:+ # a process the limits bind was killed for memory, but not at its container's own cap: the host ran out of+ # memory (other trials), or an enclosing cgroup did. Never the agent's failure, and not a clean run either.+ add["resource_host_oom"] = 1+ void = True+ detail["verdict"] = ("not a result: an out-of-memory killer other than the container's own cap (the host's) "+ f"killed {oom['host']} process(es) of the trial")+ elif oom["service"] and have_grade and not reward.get("success"):+ # in both modes: the kernel killed a benchmark-owned service (the simulator sidecar, a scorer) for memory and+ # the episode did not end in a success. Such a service is recorded, never a failure (PROTOCOL §2.10): whatever+ # the grader made of the crash, this is not the agent's 0.+ add["resource_service_oom"] = 1+ add["infra_error"] = 1+ detail["verdict"] = (f"not a result: the kernel OOM-killed a benchmark-owned service ({oom['service']} kill(s)) "+ "and the episode did not end in a success")+ else:+ # not enforced: observe only. A missing or unusable record is reported (resource_monitor_missing), never infra.+ detail["verdict"] = ("observed only (RCB_LIMITS_ENFORCE=0): " + ", ".join(v["metric"] for v in viol)) if viol \+ else "within limits" if not problems else "observed only (RCB_LIMITS_ENFORCE=0): no usable record"+ if void:+ not_a_result(reward, add)+ os.makedirs(log, exist_ok=True)+ if have_grade or failed:+ reward.update(add)+ reward.setdefault("success", 0)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if failed or void:+ with open(rt_path, "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump(detail, f, indent=1)+ print("resource limits: " + detail["verdict"], file=sys.stderr)+ return 0+++def step_failed(err):+ """This step raised: say so in the grader's reward.json instead of leaving the trial without its resource fields+ (and, when the switch asks for enforcement or cannot be read, as an infrastructure error: nothing was judged)."""+ log = os.environ.get("RCB_VERIFIER_LOGS", "/logs/verifier")+ rj_path = os.path.join(log, "reward.json")+ reward = read_json(rj_path)+ enforce, switch_error = parse_switch(os.environ.get("RCB_LIMITS_ENFORCE"))+ add = {"resource_step_error": 1, "resource_monitor_missing": 1, "resource_enforced": enforce}+ if isinstance(reward, dict):+ if enforce or switch_error:+ not_a_result(reward, add)+ reward.update(add)+ tmp = rj_path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(reward, f, indent=1)+ os.replace(tmp, rj_path)+ if add.get("infra_error"):+ with open(os.path.join(log, "reward.txt"), "w") as f:+ f.write("0\n")+ with open(os.path.join(log, "resource_limits.json"), "w") as f:+ json.dump({"format": FORMAT, "enforced": enforce, "verdict": "the verifier's resource step failed: " + err,+ "record_problems": [err]}, f, indent=1)+++MAX_SESSION_LOG = 64 * 2 ** 20 # bytes of /app/output/rcb_session_log.jsonl a grader is given to read+++def sanitize(roots=("/app/output",), max_log=MAX_SESSION_LOG):+ """Before the grader: the files the agent left (PROTOCOL §2.6: collected from its container as they are, links and+ all) are untrusted input, and a grader opens some of them by name. Remove what is not a file of the agent's own+ under the root: a symbolic link that leaves it or does not end at a regular file (`rcb_session_log.jsonl ->+ /dev/zero` made a grader read until the verifier ran out of memory or time: no verdict), and every FIFO, device and+ socket (opening a FIFO blocks). A session log larger than `max_log` is cut there (graders read it line by line,+ and one endless line is as bad). Regular files, directories and links to regular files inside the root stay as+ they are: nothing a grader could have read safely changes. Returns what it removed or cut (also printed)."""+ done = []+ for root in roots:+ real_root = os.path.realpath(root)+ if not os.path.isdir(real_root) or os.path.islink(root):+ if os.path.islink(root): # the root itself must be a directory of its own+ try:+ os.unlink(root)+ done.append(f"removed {root}: a symbolic link")+ except OSError:+ pass+ continue+ for dirpath, dirnames, filenames in os.walk(real_root, followlinks=False):+ for name in list(dirnames) + filenames:+ path = os.path.join(dirpath, name)+ try:+ st = os.lstat(path)+ if stat.S_ISLNK(st.st_mode):+ target = os.path.realpath(path)+ inside = target.startswith(real_root + os.sep)+ if inside and stat.S_ISREG(os.stat(target).st_mode):+ continue+ why = "a symbolic link that leaves the directory or does not end at a regular file"+ elif stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):+ continue+ else:+ why = "not a regular file (FIFO, device or socket)"+ os.unlink(path)+ if name in dirnames:+ dirnames.remove(name)+ done.append(f"removed {path}: {why}")+ except OSError as e: # a dangling link, a file that is gone: remove what can be removed+ try:+ if stat.S_ISLNK(os.lstat(path).st_mode):+ os.unlink(path)+ done.append(f"removed {path}: a symbolic link that cannot be resolved ({type(e).__name__})")+ except OSError:+ pass+ log = os.path.join(real_root, "rcb_session_log.jsonl")+ try:+ if os.path.isfile(log) and not os.path.islink(log) and os.path.getsize(log) > max_log:+ os.truncate(log, max_log)+ done.append(f"cut {log} to {max_log} bytes")+ except OSError:+ pass+ for d in done:+ print("verifier input: " + d, file=sys.stderr)+ return done+++def run_step(argv=()):+ """verify(), and whatever it raises reported instead of breaking the grader's own verdict. Always 0."""+ try:+ verify(argv)+ except Exception as e:+ msg = f"{type(e).__name__}: {e}"+ print(f"resource limits: verifier step failed: {msg}", file=sys.stderr)+ try:+ step_failed(msg)+ except Exception:+ pass+ return 0+++if __name__ == "__main__":+ if sys.argv[1:2] == ["verify"]:+ sys.exit(run_step(sys.argv[2:]))+ if sys.argv[1:2] == ["sanitize"]:+ try:+ sanitize(sys.argv[2:] or ("/app/output",))+ except Exception as e: # never keep the grader from running+ print(f"verifier input: sanitize failed: {type(e).__name__}: {e}", file=sys.stderr)+ sys.exit(0)+ print(__doc__)diff --git a/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/test.sh b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/test.shnew file mode 100755index 0000000000..de3fc8c811--- /dev/null+++ b/tasks/ambench-rotate-valve-fahexa-i00-privileged/tests/test.sh@@ -0,0 +1,11 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, see docs/PROTOCOL.md).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resource limits, after the grader (docs/PROTOCOL.md §2.10)+p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # the agent's files are untrusted input: no link out of /app/output, no FIFO or device (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \+ 2> /logs/verifier/grade.log