Safety

From davidhozic/mujoco-rs · View interactive version

Safety is an AI agent skill from the GitHub repository davidhozic/mujoco-rs. Adversarial multi-agent soundness audit of the mujoco-rs SAFE API surface -- memory safety, thread safety (every unsafe impl Send/Sync), &self vs &mut self mutability, and lifetime/variance correctness, restricted to defects reachable from 100% safe code. Produces a single self-contained HTML report

How to use this skill

Skill file

Safety & Soundness Audit (Claude Code only)

Obey all files in .claude/rules/ at all times. Re-read them after any context compaction.

Ground rules (non-negotiable scope)

a mechanism, never reported as a finding.

Anything only reachable through an unsafe fn or an unsafe block the caller must write is

out of scope, unless it is always a bug/UB -- regardless of how the user uses it.

The safe/unsafe tier is the dividing line.

it.

The outputs are the HTML report and the repro examples (see "Repro examples"). Fixes, changelog

entries, and regression guards are out of scope -- the audit just identifies and documents

findings.

The four dimensions

  1. Memory safety / UB -- OOB read/write reachable from safe code; invalid transmute / invalid

enum discriminant (e.g. force_cast of unchecked C int* into a fieldless #[repr] enum);

use-after-free; uninitialized/stale reads; integer-overflow-driven OOB (e.g. w*h*3 usize

overflow defeating a buffer check); mis-sized buffers handed to C; len() as i32 truncation.

For enum/discriminant casts specifically: only flag if a safe-code caller can supply or

mutate the integer value that is later cast to the enum (e.g. via a public integer setter on

the same field). If the integer is written exclusively by MuJoCo internals and the safe API

exposes no setter for it, the user cannot produce an invalid discriminant through safe code

and the cast is out of scope.

  1. Thread safety -- examine every unsafe impl Send and unsafe impl Sync in src/

(rg "unsafe impl (Send|Sync)" src/). For each, decide whether the assertion is actually

sound, then hunt for a SAFE-code path that turns an unsound impl into a data race. The classic

pattern here: a lending iterator whose type Item = &'a mut T is tied to the iterator's

lifetime (not to next()'s &mut self), so collect() yields many simultaneously-live

&mut handles; if the handle is Send, those move to different threads and race on shared

C++ state.

  1. &self vs &mut self mutability -- if the wrapped C/C++ call mutates the item or shared

model-global state, the method MUST take &mut self. A &self method that drives C-side

mutation is a soundness bug: it breaks & aliasing guarantees and any Sync assumption.

  1. Lifetimes / variance -- every child handle must carry its parent's lifetime (a child must

not outlive its parent -> no use-after-free), and variance must be sound. Confirm conditional

impls (e.g. MjData<M>: Send/Sync conditional on M) are correct.

Methodology -- adversarial multi-agent (drive with the `Workflow` tool)

Phase 0 -- Recon & task list (inline, before any fan-out)

  1. Read src/util.rs (all macros) and glob + read src/wrappers/**/*.rs.
  2. Enumerate every unsafe impl Send/Sync site, every lending/mutable iterator, and every

element-handle type (e.g. the mjs_struct!-generated Mjs* aliases).

  1. Record the MuJoCo build env for later compile checks (see "Build env" below).

Phase 1 -- FINDERS (parallel `agent()` calls, structured output)

**Derive the finder categories yourself from Phase 0 recon -- do NOT just reuse a fixed

(dimension x subsystem) grid.** A (dimension x subsystem) split is one valid decomposition,

but the main agent should think about what this codebase actually exposes and invent finder

cells that cut across the surface in complementary ways. Categories worth deriving (illustrative,

not exhaustive): ownership / Drop ordering / Clone / double-free; panic-unwind across the FFI

boundary; global callback / plugin function-pointer registration; macro-generated safe code (audit

the expanded output of getter_setter!, array_slice_dyn!, view_creator!, etc.); shared-model

aliasing across multiple MjData; resource / IO / string-buffer handling; plus the classic

per-subsystem memory sweeps. Aim for cells that minimize overlap and maximize coverage of the

specific risks this code presents -- if you run the audit more than once, vary the decomposition

so successive runs explore different angles.

Each finder reads src/ and the relevant mujoco/include/ headers and mujoco/src/ C++

source to confirm any claimed C/C++ behavior. Whatever categories you derive, always include

three specialists: a thread-safety finder that walks every Send/Sync site, a

mutability finder hunting &self methods that drive C-side mutation, and a

lifetime/variance finder. Each returns structured candidates: `{ dimension, location

(file:line), mechanism, safe_code_trigger, severity, reachable_from_safe }`.

Every finder must read the actual C/C++ source before claiming that a C function mutates

state, performs an unchecked access, or does anything else relevant to the finding. Citing a

function name without reading its implementation is not sufficient. If the C/C++ source was

not read, the candidate must be dropped.

Phase 2 -- TRIAGE / DEDUP (barrier)

Collect all candidates; dedupe by location+mechanism; drop out-of-scope items

(unsafe-only-reachable; stride/length/type).

The classify step after Phase 3 assigns the origin section (A or B, see the Deliverable).

Phase 3 -- ADVERSARIAL VERIFICATION (pipeline, per surviving candidate)

For each candidate spawn, independently:

code* (default to "refuted" when uncertain), and

finder's notes.

Keep a finding only if it survives both (genuinely reachable + independently reproduced).

Apply the same C/C++ citation rule from Phase 1: read the source, cite file:line, or drop the claim.

For thread-safety and other type-level claims, settle disputes with compile-level evidence:

type-checks against the real types -- e.g. that

body.geom_iter_mut(true).collect::<Vec<&mut MjsGeom>>() followed by thread::scope spawning

per-handle compiles, and that &mut MjsGeom: Send.

Name throwaway probes examples/repro_tmpcheck_<tag>.rs and delete them afterward.

Phase 4 -- COMPLETENESS CRITIC

A final agent asks: "which dimension / module / Send-Sync site / claim was not covered or not

verified?" Each gap becomes another finder round. Loop until a round produces no new candidates.

Severities: Critical / High / Medium / Low / Uncertain.

Statuses (exactly four -- do not invent others; there is NO "Accepted"):

| Status | When to use | Assignment rule |

|---|---|---|

| Open | Confirmed, not yet fixed | everything else |

| Defer (MuJoCo) | Root cause is upstream; unfixable in the Rust wrapper alone | root cause is in MuJoCo C/C++ |

| Open (latent) | Real bug, not practically triggerable today | requires e.g. >2^31 elements or similar |

| Fixed | Fix was applied outside this skill run | only when the fix already exists in the codebase |

Build env for compile-level verification

cargo check/build run build.rs, which must discover MuJoCo. Use the absolute env-var path so

the pinned-version pkg-config check is bypassed (cargo check does not link, so a version

mismatch is irrelevant):

export MUJOCO_DYNAMIC_LINK_DIR="$(realpath mujoco-3.9.0/lib)"
export LD_LIBRARY_PATH="$MUJOCO_DYNAMIC_LINK_DIR"

(See the build and run-example skills.) Use cargo check for type-level probes; only

cargo build/run when demonstrating a runtime crash.

Repro examples

Write one runnable reproduction example per confirmed finding, after the IDs are final. The user

keeps and runs them, so do not delete them.

  1. Make sure .git/info/excludes contains /examples/repro_*.rs. If it does not, append it with a comment

that marks it temporary ("remove before commit"), and tell the user.

  1. Write examples/repro_safety_<ID>.rs (<ID> is S1, S2, ...). Use the public crate API

(use mujoco_rs::prelude::*, an inline MJCF model). Do not register it in Cargo.toml; Cargo

discovers it.

  1. Start the file with a //! header: the ID, the problem in one line, the exact run command (env

vars and --features), and the expected symptom.

For a thread or type-level finding, also write examples/repro_safety_<ID>_standalone.rs: a

program without the crate that mirrors the pattern and shows the UB under Miri.

  1. cargo check --example repro_safety_<ID> must pass. Run it with timeout 60 when this machine

can, and record the result.

  1. Add a Repro: field (file and run command) to each detail entry of the report.

Only repro_safety_<ID>*.rs files stay in examples/. Name any intermediate probe

examples/repro_tmpcheck_<tag>.rs and delete it after use. Move any other leftover probe to

~/.cache/mujoco-rs-results/<agent>-<task>/.

Deliverable -- a single self-contained HTML report

Write/overwrite mujoco-rs-memory-safety-audit.html at the repo root.

Scope: the current chat session. The report accumulates findings across ALL /safety runs

within this chat. Findings fixed between runs stay in the report with status fixed -- they

are never silently removed. Do NOT carry over findings from a prior chat.

Concretely:

and must be discarded entirely.

prior findings (including their current statuses) as args to the Workflow so the new run

can merge with them: update statuses where fixes were applied, add any new confirmed findings.

chats or from memory.

The file must be self-contained (inline <style>), ASCII-only, and contain:

Two origin sections. Split both the compact list and the detail list into two sections, each

grouped by severity inside. Assign the origin when the finding is classified, not after the report.

missing (read = unsafe) / (mut = unsafe) marking, an unsound Send/Sync, a viewer or

renderer logic bug, a build.rs bug.

the guard must go into our wrapper. Examples: an int overflow in a size product, an unchecked

index or format string, no stage-order check. Every Defer (MuJoCo) finding goes here.

Headings: 1A. Compact list: Our wrappers / usage, 1B. Compact list: Inadequate MuJoCo checks,

2A. Details: ..., 2B. Details: .... Omit empty severity groups. Write "None." for an empty

section.

No prose anywhere in the report: no method note, no introduction, no paragraphs. Only the

lists below. Every description is a fragment of at most ~8 words.

  1. Compact list (top of page) of all findings accumulated this chat, grouped by severity

(CRITICAL, HIGH, MEDIUM, LOW, UNCERTAIN; omit empty groups). One line per finding:

ID file:line item: problem [status]. Each ID links to its detail entry. If no findings

exist, the list is the single line "No findings confirmed in this session."

```

HIGH

S1 mj_rendering.rs:412 geoms_mut: matid unchecked -> OOB read [open]

S2 mj_data.rs:88 Send impl: no M: Send bound [open]

MEDIUM

S3 mj_model.rs:1301 name(): &str outlives model [fixed]

```

  1. Detail list (below), one entry per finding, same order. Header line

ID SEVERITY dimension status (dimension: mem / thread / mut / life), then

labeled fields, each at most one line except the code:

```

S1 HIGH mem open

Where: src/wrappers/mj_rendering.rs:412 (MjvScene::geoms_mut)

Problem: C indexes the material table with matid and does no bounds check.

Trigger:

scene.geoms_mut()[0].matid = 9999;

renderer.render(&scene); // OOB read in mjr_render

Fix: make geoms_mut an unsafe fn.

```

Trigger is a minimal safe-code snippet. Fix describes a fix only; do NOT implement it.

  1. Observations: one line each, mujoco/src/...:line fact. Include ONLY items that were

actually verified against mujoco/src/ or mujoco/include/ during this session.

Unverified hypotheticals ("if X were to do Y...") are forbidden.

  1. Found sound: one line each, item -> OK (reason fragment), inside a details element.

Styling: reproduce the same Claude aesthetic as mujoco-rs-memory-safety-audit.html -- ivory

canvas background, coral accent, warm near-black ink, Georgia serif headings. Render both lists

in a monospace font on white blocks, with the columns aligned. Color the severity group headings

(sev-critical/high/medium/low/uncertain) and the status tags (st-open / st-fixed /

st-defer-mujoco / st-open-latent).

After the audit

Assign statuses using the table in Phase 4 -- do NOT pause to ask the user. Present the

compact list to the user verbatim, with no added prose. No interactive questions. Do NOT modify

any source files, tests, docs, or the changelog -- the audit is strictly read-only (the repro

examples are the only files it adds).

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.